viewer.js 5.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define("BabylonViewer", [], factory);
  6. else if(typeof exports === 'object')
  7. exports["BabylonViewer"] = factory();
  8. else
  9. root["BabylonViewer"] = factory();
  10. })(this, function() {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId]) {
  20. /******/ return installedModules[moduleId].exports;
  21. /******/ }
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ i: moduleId,
  25. /******/ l: false,
  26. /******/ exports: {}
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.l = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // define getter function for harmony exports
  47. /******/ __webpack_require__.d = function(exports, name, getter) {
  48. /******/ if(!__webpack_require__.o(exports, name)) {
  49. /******/ Object.defineProperty(exports, name, {
  50. /******/ configurable: false,
  51. /******/ enumerable: true,
  52. /******/ get: getter
  53. /******/ });
  54. /******/ }
  55. /******/ };
  56. /******/
  57. /******/ // getDefaultExport function for compatibility with non-harmony modules
  58. /******/ __webpack_require__.n = function(module) {
  59. /******/ var getter = module && module.__esModule ?
  60. /******/ function getDefault() { return module['default']; } :
  61. /******/ function getModuleExports() { return module; };
  62. /******/ __webpack_require__.d(getter, 'a', getter);
  63. /******/ return getter;
  64. /******/ };
  65. /******/
  66. /******/ // Object.prototype.hasOwnProperty.call
  67. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  68. /******/
  69. /******/ // __webpack_public_path__
  70. /******/ __webpack_require__.p = "";
  71. /******/
  72. /******/ // Load entry module and return exports
  73. /******/ return __webpack_require__(__webpack_require__.s = 14);
  74. /******/ })
  75. /************************************************************************/
  76. /******/ ([
  77. /* 0 */
  78. /***/ (function(module, exports, __webpack_require__) {
  79. /* WEBPACK VAR INJECTION */(function(global) {var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  80. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  81. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  82. 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;
  83. return c > 3 && r && Object.defineProperty(target, key, r), r;
  84. };
  85. var __extends = (this && this.__extends) || (function () {
  86. var extendStatics = Object.setPrototypeOf ||
  87. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  88. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  89. return function (d, b) {
  90. extendStatics(d, b);
  91. function __() { this.constructor = d; }
  92. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  93. };
  94. })();
  95. //# sourceMappingURL=babylon.types.js.map
  96. var BABYLON;
  97. (function (BABYLON) {
  98. var KeyboardEventTypes = /** @class */ (function () {
  99. function KeyboardEventTypes() {
  100. }
  101. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  102. get: function () {
  103. return KeyboardEventTypes._KEYDOWN;
  104. },
  105. enumerable: true,
  106. configurable: true
  107. });
  108. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  109. get: function () {
  110. return KeyboardEventTypes._KEYUP;
  111. },
  112. enumerable: true,
  113. configurable: true
  114. });
  115. KeyboardEventTypes._KEYDOWN = 0x01;
  116. KeyboardEventTypes._KEYUP = 0x02;
  117. return KeyboardEventTypes;
  118. }());
  119. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  120. var KeyboardInfo = /** @class */ (function () {
  121. function KeyboardInfo(type, event) {
  122. this.type = type;
  123. this.event = event;
  124. }
  125. return KeyboardInfo;
  126. }());
  127. BABYLON.KeyboardInfo = KeyboardInfo;
  128. /**
  129. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  130. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  131. */
  132. var KeyboardInfoPre = /** @class */ (function (_super) {
  133. __extends(KeyboardInfoPre, _super);
  134. function KeyboardInfoPre(type, event) {
  135. var _this = _super.call(this, type, event) || this;
  136. _this.skipOnPointerObservable = false;
  137. return _this;
  138. }
  139. return KeyboardInfoPre;
  140. }(KeyboardInfo));
  141. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  142. })(BABYLON || (BABYLON = {}));
  143. //# sourceMappingURL=babylon.keyboardEvents.js.map
  144. var BABYLON;
  145. (function (BABYLON) {
  146. var PointerEventTypes = /** @class */ (function () {
  147. function PointerEventTypes() {
  148. }
  149. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  150. get: function () {
  151. return PointerEventTypes._POINTERDOWN;
  152. },
  153. enumerable: true,
  154. configurable: true
  155. });
  156. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  157. get: function () {
  158. return PointerEventTypes._POINTERUP;
  159. },
  160. enumerable: true,
  161. configurable: true
  162. });
  163. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  164. get: function () {
  165. return PointerEventTypes._POINTERMOVE;
  166. },
  167. enumerable: true,
  168. configurable: true
  169. });
  170. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  171. get: function () {
  172. return PointerEventTypes._POINTERWHEEL;
  173. },
  174. enumerable: true,
  175. configurable: true
  176. });
  177. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  178. get: function () {
  179. return PointerEventTypes._POINTERPICK;
  180. },
  181. enumerable: true,
  182. configurable: true
  183. });
  184. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  185. get: function () {
  186. return PointerEventTypes._POINTERTAP;
  187. },
  188. enumerable: true,
  189. configurable: true
  190. });
  191. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  192. get: function () {
  193. return PointerEventTypes._POINTERDOUBLETAP;
  194. },
  195. enumerable: true,
  196. configurable: true
  197. });
  198. PointerEventTypes._POINTERDOWN = 0x01;
  199. PointerEventTypes._POINTERUP = 0x02;
  200. PointerEventTypes._POINTERMOVE = 0x04;
  201. PointerEventTypes._POINTERWHEEL = 0x08;
  202. PointerEventTypes._POINTERPICK = 0x10;
  203. PointerEventTypes._POINTERTAP = 0x20;
  204. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  205. return PointerEventTypes;
  206. }());
  207. BABYLON.PointerEventTypes = PointerEventTypes;
  208. var PointerInfoBase = /** @class */ (function () {
  209. function PointerInfoBase(type, event) {
  210. this.type = type;
  211. this.event = event;
  212. }
  213. return PointerInfoBase;
  214. }());
  215. BABYLON.PointerInfoBase = PointerInfoBase;
  216. /**
  217. * This class is used to store pointer related info for the onPrePointerObservable event.
  218. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  219. */
  220. var PointerInfoPre = /** @class */ (function (_super) {
  221. __extends(PointerInfoPre, _super);
  222. function PointerInfoPre(type, event, localX, localY) {
  223. var _this = _super.call(this, type, event) || this;
  224. _this.skipOnPointerObservable = false;
  225. _this.localPosition = new BABYLON.Vector2(localX, localY);
  226. return _this;
  227. }
  228. return PointerInfoPre;
  229. }(PointerInfoBase));
  230. BABYLON.PointerInfoPre = PointerInfoPre;
  231. /**
  232. * This type contains all the data related to a pointer event in Babylon.js.
  233. * 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.
  234. */
  235. var PointerInfo = /** @class */ (function (_super) {
  236. __extends(PointerInfo, _super);
  237. function PointerInfo(type, event, pickInfo) {
  238. var _this = _super.call(this, type, event) || this;
  239. _this.pickInfo = pickInfo;
  240. return _this;
  241. }
  242. return PointerInfo;
  243. }(PointerInfoBase));
  244. BABYLON.PointerInfo = PointerInfo;
  245. })(BABYLON || (BABYLON = {}));
  246. //# sourceMappingURL=babylon.pointerEvents.js.map
  247. var BABYLON;
  248. (function (BABYLON) {
  249. BABYLON.ToGammaSpace = 1 / 2.2;
  250. BABYLON.ToLinearSpace = 2.2;
  251. BABYLON.Epsilon = 0.001;
  252. var Color3 = /** @class */ (function () {
  253. /**
  254. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  255. */
  256. function Color3(r, g, b) {
  257. if (r === void 0) { r = 0; }
  258. if (g === void 0) { g = 0; }
  259. if (b === void 0) { b = 0; }
  260. this.r = r;
  261. this.g = g;
  262. this.b = b;
  263. }
  264. /**
  265. * Returns a string with the Color3 current values.
  266. */
  267. Color3.prototype.toString = function () {
  268. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  269. };
  270. /**
  271. * Returns the string "Color3".
  272. */
  273. Color3.prototype.getClassName = function () {
  274. return "Color3";
  275. };
  276. /**
  277. * Returns the Color3 hash code.
  278. */
  279. Color3.prototype.getHashCode = function () {
  280. var hash = this.r || 0;
  281. hash = (hash * 397) ^ (this.g || 0);
  282. hash = (hash * 397) ^ (this.b || 0);
  283. return hash;
  284. };
  285. // Operators
  286. /**
  287. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  288. * Returns the Color3.
  289. */
  290. Color3.prototype.toArray = function (array, index) {
  291. if (index === undefined) {
  292. index = 0;
  293. }
  294. array[index] = this.r;
  295. array[index + 1] = this.g;
  296. array[index + 2] = this.b;
  297. return this;
  298. };
  299. /**
  300. * Returns a new Color4 object from the current Color3 and the passed alpha.
  301. */
  302. Color3.prototype.toColor4 = function (alpha) {
  303. if (alpha === void 0) { alpha = 1; }
  304. return new Color4(this.r, this.g, this.b, alpha);
  305. };
  306. /**
  307. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  308. */
  309. Color3.prototype.asArray = function () {
  310. var result = new Array();
  311. this.toArray(result, 0);
  312. return result;
  313. };
  314. /**
  315. * Returns the luminance value (float).
  316. */
  317. Color3.prototype.toLuminance = function () {
  318. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  319. };
  320. /**
  321. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  322. * Returns this new object.
  323. */
  324. Color3.prototype.multiply = function (otherColor) {
  325. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  326. };
  327. /**
  328. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  329. * Returns the current Color3.
  330. */
  331. Color3.prototype.multiplyToRef = function (otherColor, result) {
  332. result.r = this.r * otherColor.r;
  333. result.g = this.g * otherColor.g;
  334. result.b = this.b * otherColor.b;
  335. return this;
  336. };
  337. /**
  338. * Boolean : True if the rgb values are equal to the passed ones.
  339. */
  340. Color3.prototype.equals = function (otherColor) {
  341. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  342. };
  343. /**
  344. * Boolean : True if the rgb values are equal to the passed ones.
  345. */
  346. Color3.prototype.equalsFloats = function (r, g, b) {
  347. return this.r === r && this.g === g && this.b === b;
  348. };
  349. /**
  350. * Multiplies in place each rgb value by scale.
  351. * Returns the updated Color3.
  352. */
  353. Color3.prototype.scale = function (scale) {
  354. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  355. };
  356. /**
  357. * Multiplies the rgb values by scale and stores the result into "result".
  358. * Returns the unmodified current Color3.
  359. */
  360. Color3.prototype.scaleToRef = function (scale, result) {
  361. result.r = this.r * scale;
  362. result.g = this.g * scale;
  363. result.b = this.b * scale;
  364. return this;
  365. };
  366. /**
  367. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  368. */
  369. Color3.prototype.add = function (otherColor) {
  370. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  371. };
  372. /**
  373. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  374. * Returns the unmodified current Color3.
  375. */
  376. Color3.prototype.addToRef = function (otherColor, result) {
  377. result.r = this.r + otherColor.r;
  378. result.g = this.g + otherColor.g;
  379. result.b = this.b + otherColor.b;
  380. return this;
  381. };
  382. /**
  383. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  384. */
  385. Color3.prototype.subtract = function (otherColor) {
  386. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  387. };
  388. /**
  389. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  390. * Returns the unmodified current Color3.
  391. */
  392. Color3.prototype.subtractToRef = function (otherColor, result) {
  393. result.r = this.r - otherColor.r;
  394. result.g = this.g - otherColor.g;
  395. result.b = this.b - otherColor.b;
  396. return this;
  397. };
  398. /**
  399. * Returns a new Color3 copied the current one.
  400. */
  401. Color3.prototype.clone = function () {
  402. return new Color3(this.r, this.g, this.b);
  403. };
  404. /**
  405. * Copies the rgb values from the source in the current Color3.
  406. * Returns the updated Color3.
  407. */
  408. Color3.prototype.copyFrom = function (source) {
  409. this.r = source.r;
  410. this.g = source.g;
  411. this.b = source.b;
  412. return this;
  413. };
  414. /**
  415. * Updates the Color3 rgb values from the passed floats.
  416. * Returns the Color3.
  417. */
  418. Color3.prototype.copyFromFloats = function (r, g, b) {
  419. this.r = r;
  420. this.g = g;
  421. this.b = b;
  422. return this;
  423. };
  424. /**
  425. * Updates the Color3 rgb values from the passed floats.
  426. * Returns the Color3.
  427. */
  428. Color3.prototype.set = function (r, g, b) {
  429. return this.copyFromFloats(r, g, b);
  430. };
  431. /**
  432. * Returns the Color3 hexadecimal code as a string.
  433. */
  434. Color3.prototype.toHexString = function () {
  435. var intR = (this.r * 255) | 0;
  436. var intG = (this.g * 255) | 0;
  437. var intB = (this.b * 255) | 0;
  438. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  439. };
  440. /**
  441. * Returns a new Color3 converted to linear space.
  442. */
  443. Color3.prototype.toLinearSpace = function () {
  444. var convertedColor = new Color3();
  445. this.toLinearSpaceToRef(convertedColor);
  446. return convertedColor;
  447. };
  448. /**
  449. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  450. * Returns the unmodified Color3.
  451. */
  452. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  453. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  454. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  455. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  456. return this;
  457. };
  458. /**
  459. * Returns a new Color3 converted to gamma space.
  460. */
  461. Color3.prototype.toGammaSpace = function () {
  462. var convertedColor = new Color3();
  463. this.toGammaSpaceToRef(convertedColor);
  464. return convertedColor;
  465. };
  466. /**
  467. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  468. * Returns the unmodified Color3.
  469. */
  470. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  471. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  472. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  473. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  474. return this;
  475. };
  476. // Statics
  477. /**
  478. * Creates a new Color3 from the string containing valid hexadecimal values.
  479. */
  480. Color3.FromHexString = function (hex) {
  481. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  482. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  483. return new Color3(0, 0, 0);
  484. }
  485. var r = parseInt(hex.substring(1, 3), 16);
  486. var g = parseInt(hex.substring(3, 5), 16);
  487. var b = parseInt(hex.substring(5, 7), 16);
  488. return Color3.FromInts(r, g, b);
  489. };
  490. /**
  491. * Creates a new Vector3 from the startind index of the passed array.
  492. */
  493. Color3.FromArray = function (array, offset) {
  494. if (offset === void 0) { offset = 0; }
  495. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  496. };
  497. /**
  498. * Creates a new Color3 from integer values ( < 256).
  499. */
  500. Color3.FromInts = function (r, g, b) {
  501. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  502. };
  503. /**
  504. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  505. */
  506. Color3.Lerp = function (start, end, amount) {
  507. var r = start.r + ((end.r - start.r) * amount);
  508. var g = start.g + ((end.g - start.g) * amount);
  509. var b = start.b + ((end.b - start.b) * amount);
  510. return new Color3(r, g, b);
  511. };
  512. Color3.Red = function () { return new Color3(1, 0, 0); };
  513. Color3.Green = function () { return new Color3(0, 1, 0); };
  514. Color3.Blue = function () { return new Color3(0, 0, 1); };
  515. Color3.Black = function () { return new Color3(0, 0, 0); };
  516. Color3.White = function () { return new Color3(1, 1, 1); };
  517. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  518. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  519. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  520. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  521. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  522. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  523. return Color3;
  524. }());
  525. BABYLON.Color3 = Color3;
  526. var Color4 = /** @class */ (function () {
  527. /**
  528. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  529. */
  530. function Color4(r, g, b, a) {
  531. if (r === void 0) { r = 0; }
  532. if (g === void 0) { g = 0; }
  533. if (b === void 0) { b = 0; }
  534. if (a === void 0) { a = 1; }
  535. this.r = r;
  536. this.g = g;
  537. this.b = b;
  538. this.a = a;
  539. }
  540. // Operators
  541. /**
  542. * Adds in place the passed Color4 values to the current Color4.
  543. * Returns the updated Color4.
  544. */
  545. Color4.prototype.addInPlace = function (right) {
  546. this.r += right.r;
  547. this.g += right.g;
  548. this.b += right.b;
  549. this.a += right.a;
  550. return this;
  551. };
  552. /**
  553. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  554. */
  555. Color4.prototype.asArray = function () {
  556. var result = new Array();
  557. this.toArray(result, 0);
  558. return result;
  559. };
  560. /**
  561. * Stores from the starting index in the passed array the Color4 successive values.
  562. * Returns the Color4.
  563. */
  564. Color4.prototype.toArray = function (array, index) {
  565. if (index === undefined) {
  566. index = 0;
  567. }
  568. array[index] = this.r;
  569. array[index + 1] = this.g;
  570. array[index + 2] = this.b;
  571. array[index + 3] = this.a;
  572. return this;
  573. };
  574. /**
  575. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  576. */
  577. Color4.prototype.add = function (right) {
  578. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  579. };
  580. /**
  581. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  582. */
  583. Color4.prototype.subtract = function (right) {
  584. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  585. };
  586. /**
  587. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  588. * Returns the Color4.
  589. */
  590. Color4.prototype.subtractToRef = function (right, result) {
  591. result.r = this.r - right.r;
  592. result.g = this.g - right.g;
  593. result.b = this.b - right.b;
  594. result.a = this.a - right.a;
  595. return this;
  596. };
  597. /**
  598. * Creates a new Color4 with the current Color4 values multiplied by scale.
  599. */
  600. Color4.prototype.scale = function (scale) {
  601. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  602. };
  603. /**
  604. * Multiplies the current Color4 values by scale and stores the result in "result".
  605. * Returns the Color4.
  606. */
  607. Color4.prototype.scaleToRef = function (scale, result) {
  608. result.r = this.r * scale;
  609. result.g = this.g * scale;
  610. result.b = this.b * scale;
  611. result.a = this.a * scale;
  612. return this;
  613. };
  614. /**
  615. * Multipy an RGBA Color4 value by another and return a new Color4 object
  616. * @param color The Color4 (RGBA) value to multiply by
  617. * @returns A new Color4.
  618. */
  619. Color4.prototype.multiply = function (color) {
  620. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  621. };
  622. /**
  623. * Multipy an RGBA Color4 value by another and push the result in a reference value
  624. * @param color The Color4 (RGBA) value to multiply by
  625. * @param result The Color4 (RGBA) to fill the result in
  626. * @returns the result Color4.
  627. */
  628. Color4.prototype.multiplyToRef = function (color, result) {
  629. result.r = this.r * color.r;
  630. result.g = this.g * color.g;
  631. result.b = this.b * color.b;
  632. result.a = this.a * color.a;
  633. return result;
  634. };
  635. /**
  636. * Returns a string with the Color4 values.
  637. */
  638. Color4.prototype.toString = function () {
  639. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  640. };
  641. /**
  642. * Returns the string "Color4"
  643. */
  644. Color4.prototype.getClassName = function () {
  645. return "Color4";
  646. };
  647. /**
  648. * Return the Color4 hash code as a number.
  649. */
  650. Color4.prototype.getHashCode = function () {
  651. var hash = this.r || 0;
  652. hash = (hash * 397) ^ (this.g || 0);
  653. hash = (hash * 397) ^ (this.b || 0);
  654. hash = (hash * 397) ^ (this.a || 0);
  655. return hash;
  656. };
  657. /**
  658. * Creates a new Color4 copied from the current one.
  659. */
  660. Color4.prototype.clone = function () {
  661. return new Color4(this.r, this.g, this.b, this.a);
  662. };
  663. /**
  664. * Copies the passed Color4 values into the current one.
  665. * Returns the updated Color4.
  666. */
  667. Color4.prototype.copyFrom = function (source) {
  668. this.r = source.r;
  669. this.g = source.g;
  670. this.b = source.b;
  671. this.a = source.a;
  672. return this;
  673. };
  674. /**
  675. * Copies the passed float values into the current one.
  676. * Returns the updated Color4.
  677. */
  678. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  679. this.r = r;
  680. this.g = g;
  681. this.b = b;
  682. this.a = a;
  683. return this;
  684. };
  685. /**
  686. * Copies the passed float values into the current one.
  687. * Returns the updated Color4.
  688. */
  689. Color4.prototype.set = function (r, g, b, a) {
  690. return this.copyFromFloats(r, g, b, a);
  691. };
  692. /**
  693. * Returns a string containing the hexadecimal Color4 code.
  694. */
  695. Color4.prototype.toHexString = function () {
  696. var intR = (this.r * 255) | 0;
  697. var intG = (this.g * 255) | 0;
  698. var intB = (this.b * 255) | 0;
  699. var intA = (this.a * 255) | 0;
  700. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  701. };
  702. /**
  703. * Returns a new Color4 converted to linear space.
  704. */
  705. Color4.prototype.toLinearSpace = function () {
  706. var convertedColor = new Color4();
  707. this.toLinearSpaceToRef(convertedColor);
  708. return convertedColor;
  709. };
  710. /**
  711. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  712. * Returns the unmodified Color4.
  713. */
  714. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  715. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  716. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  717. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  718. convertedColor.a = this.a;
  719. return this;
  720. };
  721. /**
  722. * Returns a new Color4 converted to gamma space.
  723. */
  724. Color4.prototype.toGammaSpace = function () {
  725. var convertedColor = new Color4();
  726. this.toGammaSpaceToRef(convertedColor);
  727. return convertedColor;
  728. };
  729. /**
  730. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  731. * Returns the unmodified Color4.
  732. */
  733. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  734. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  735. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  736. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  737. convertedColor.a = this.a;
  738. return this;
  739. };
  740. // Statics
  741. /**
  742. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  743. */
  744. Color4.FromHexString = function (hex) {
  745. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  746. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  747. return new Color4(0.0, 0.0, 0.0, 0.0);
  748. }
  749. var r = parseInt(hex.substring(1, 3), 16);
  750. var g = parseInt(hex.substring(3, 5), 16);
  751. var b = parseInt(hex.substring(5, 7), 16);
  752. var a = parseInt(hex.substring(7, 9), 16);
  753. return Color4.FromInts(r, g, b, a);
  754. };
  755. /**
  756. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  757. */
  758. Color4.Lerp = function (left, right, amount) {
  759. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  760. Color4.LerpToRef(left, right, amount, result);
  761. return result;
  762. };
  763. /**
  764. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  765. */
  766. Color4.LerpToRef = function (left, right, amount, result) {
  767. result.r = left.r + (right.r - left.r) * amount;
  768. result.g = left.g + (right.g - left.g) * amount;
  769. result.b = left.b + (right.b - left.b) * amount;
  770. result.a = left.a + (right.a - left.a) * amount;
  771. };
  772. /**
  773. * Creates a new Color4 from the starting index element of the passed array.
  774. */
  775. Color4.FromArray = function (array, offset) {
  776. if (offset === void 0) { offset = 0; }
  777. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  778. };
  779. /**
  780. * Creates a new Color4 from the passed integers ( < 256 ).
  781. */
  782. Color4.FromInts = function (r, g, b, a) {
  783. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  784. };
  785. Color4.CheckColors4 = function (colors, count) {
  786. // Check if color3 was used
  787. if (colors.length === count * 3) {
  788. var colors4 = [];
  789. for (var index = 0; index < colors.length; index += 3) {
  790. var newIndex = (index / 3) * 4;
  791. colors4[newIndex] = colors[index];
  792. colors4[newIndex + 1] = colors[index + 1];
  793. colors4[newIndex + 2] = colors[index + 2];
  794. colors4[newIndex + 3] = 1.0;
  795. }
  796. return colors4;
  797. }
  798. return colors;
  799. };
  800. return Color4;
  801. }());
  802. BABYLON.Color4 = Color4;
  803. var Vector2 = /** @class */ (function () {
  804. /**
  805. * Creates a new Vector2 from the passed x and y coordinates.
  806. */
  807. function Vector2(x, y) {
  808. this.x = x;
  809. this.y = y;
  810. }
  811. /**
  812. * Returns a string with the Vector2 coordinates.
  813. */
  814. Vector2.prototype.toString = function () {
  815. return "{X: " + this.x + " Y:" + this.y + "}";
  816. };
  817. /**
  818. * Returns the string "Vector2"
  819. */
  820. Vector2.prototype.getClassName = function () {
  821. return "Vector2";
  822. };
  823. /**
  824. * Returns the Vector2 hash code as a number.
  825. */
  826. Vector2.prototype.getHashCode = function () {
  827. var hash = this.x || 0;
  828. hash = (hash * 397) ^ (this.y || 0);
  829. return hash;
  830. };
  831. // Operators
  832. /**
  833. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  834. * Returns the Vector2.
  835. */
  836. Vector2.prototype.toArray = function (array, index) {
  837. if (index === void 0) { index = 0; }
  838. array[index] = this.x;
  839. array[index + 1] = this.y;
  840. return this;
  841. };
  842. /**
  843. * Returns a new array with 2 elements : the Vector2 coordinates.
  844. */
  845. Vector2.prototype.asArray = function () {
  846. var result = new Array();
  847. this.toArray(result, 0);
  848. return result;
  849. };
  850. /**
  851. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  852. * Returns the updated Vector2.
  853. */
  854. Vector2.prototype.copyFrom = function (source) {
  855. this.x = source.x;
  856. this.y = source.y;
  857. return this;
  858. };
  859. /**
  860. * Sets the Vector2 coordinates with the passed floats.
  861. * Returns the updated Vector2.
  862. */
  863. Vector2.prototype.copyFromFloats = function (x, y) {
  864. this.x = x;
  865. this.y = y;
  866. return this;
  867. };
  868. /**
  869. * Sets the Vector2 coordinates with the passed floats.
  870. * Returns the updated Vector2.
  871. */
  872. Vector2.prototype.set = function (x, y) {
  873. return this.copyFromFloats(x, y);
  874. };
  875. /**
  876. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  877. */
  878. Vector2.prototype.add = function (otherVector) {
  879. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  880. };
  881. /**
  882. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  883. * Returns the Vector2.
  884. */
  885. Vector2.prototype.addToRef = function (otherVector, result) {
  886. result.x = this.x + otherVector.x;
  887. result.y = this.y + otherVector.y;
  888. return this;
  889. };
  890. /**
  891. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  892. * Returns the updated Vector2.
  893. */
  894. Vector2.prototype.addInPlace = function (otherVector) {
  895. this.x += otherVector.x;
  896. this.y += otherVector.y;
  897. return this;
  898. };
  899. /**
  900. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  901. */
  902. Vector2.prototype.addVector3 = function (otherVector) {
  903. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  904. };
  905. /**
  906. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  907. */
  908. Vector2.prototype.subtract = function (otherVector) {
  909. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  910. };
  911. /**
  912. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  913. * Returns the Vector2.
  914. */
  915. Vector2.prototype.subtractToRef = function (otherVector, result) {
  916. result.x = this.x - otherVector.x;
  917. result.y = this.y - otherVector.y;
  918. return this;
  919. };
  920. /**
  921. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  922. * Returns the updated Vector2.
  923. */
  924. Vector2.prototype.subtractInPlace = function (otherVector) {
  925. this.x -= otherVector.x;
  926. this.y -= otherVector.y;
  927. return this;
  928. };
  929. /**
  930. * Multiplies in place the current Vector2 coordinates by the passed ones.
  931. * Returns the updated Vector2.
  932. */
  933. Vector2.prototype.multiplyInPlace = function (otherVector) {
  934. this.x *= otherVector.x;
  935. this.y *= otherVector.y;
  936. return this;
  937. };
  938. /**
  939. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  940. */
  941. Vector2.prototype.multiply = function (otherVector) {
  942. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  943. };
  944. /**
  945. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  946. * Returns the Vector2.
  947. */
  948. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  949. result.x = this.x * otherVector.x;
  950. result.y = this.y * otherVector.y;
  951. return this;
  952. };
  953. /**
  954. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  955. */
  956. Vector2.prototype.multiplyByFloats = function (x, y) {
  957. return new Vector2(this.x * x, this.y * y);
  958. };
  959. /**
  960. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  961. */
  962. Vector2.prototype.divide = function (otherVector) {
  963. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  964. };
  965. /**
  966. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  967. * Returns the Vector2.
  968. */
  969. Vector2.prototype.divideToRef = function (otherVector, result) {
  970. result.x = this.x / otherVector.x;
  971. result.y = this.y / otherVector.y;
  972. return this;
  973. };
  974. /**
  975. * Returns a new Vector2 with current Vector2 negated coordinates.
  976. */
  977. Vector2.prototype.negate = function () {
  978. return new Vector2(-this.x, -this.y);
  979. };
  980. /**
  981. * Multiply the Vector2 coordinates by scale.
  982. * Returns the updated Vector2.
  983. */
  984. Vector2.prototype.scaleInPlace = function (scale) {
  985. this.x *= scale;
  986. this.y *= scale;
  987. return this;
  988. };
  989. /**
  990. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  991. */
  992. Vector2.prototype.scale = function (scale) {
  993. return new Vector2(this.x * scale, this.y * scale);
  994. };
  995. /**
  996. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  997. */
  998. Vector2.prototype.equals = function (otherVector) {
  999. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1000. };
  1001. /**
  1002. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1003. */
  1004. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1005. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1006. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1007. };
  1008. // Properties
  1009. /**
  1010. * Returns the vector length (float).
  1011. */
  1012. Vector2.prototype.length = function () {
  1013. return Math.sqrt(this.x * this.x + this.y * this.y);
  1014. };
  1015. /**
  1016. * Returns the vector squared length (float);
  1017. */
  1018. Vector2.prototype.lengthSquared = function () {
  1019. return (this.x * this.x + this.y * this.y);
  1020. };
  1021. // Methods
  1022. /**
  1023. * Normalize the vector.
  1024. * Returns the updated Vector2.
  1025. */
  1026. Vector2.prototype.normalize = function () {
  1027. var len = this.length();
  1028. if (len === 0)
  1029. return this;
  1030. var num = 1.0 / len;
  1031. this.x *= num;
  1032. this.y *= num;
  1033. return this;
  1034. };
  1035. /**
  1036. * Returns a new Vector2 copied from the Vector2.
  1037. */
  1038. Vector2.prototype.clone = function () {
  1039. return new Vector2(this.x, this.y);
  1040. };
  1041. // Statics
  1042. /**
  1043. * Returns a new Vector2(0, 0)
  1044. */
  1045. Vector2.Zero = function () {
  1046. return new Vector2(0, 0);
  1047. };
  1048. /**
  1049. * Returns a new Vector2(1, 1)
  1050. */
  1051. Vector2.One = function () {
  1052. return new Vector2(1, 1);
  1053. };
  1054. /**
  1055. * Returns a new Vector2 set from the passed index element of the passed array.
  1056. */
  1057. Vector2.FromArray = function (array, offset) {
  1058. if (offset === void 0) { offset = 0; }
  1059. return new Vector2(array[offset], array[offset + 1]);
  1060. };
  1061. /**
  1062. * Sets "result" from the passed index element of the passed array.
  1063. */
  1064. Vector2.FromArrayToRef = function (array, offset, result) {
  1065. result.x = array[offset];
  1066. result.y = array[offset + 1];
  1067. };
  1068. /**
  1069. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1070. */
  1071. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1072. var squared = amount * amount;
  1073. var cubed = amount * squared;
  1074. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1075. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1076. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1077. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1078. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1079. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1080. return new Vector2(x, y);
  1081. };
  1082. /**
  1083. * 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".
  1084. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1085. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1086. */
  1087. Vector2.Clamp = function (value, min, max) {
  1088. var x = value.x;
  1089. x = (x > max.x) ? max.x : x;
  1090. x = (x < min.x) ? min.x : x;
  1091. var y = value.y;
  1092. y = (y > max.y) ? max.y : y;
  1093. y = (y < min.y) ? min.y : y;
  1094. return new Vector2(x, y);
  1095. };
  1096. /**
  1097. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1098. */
  1099. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1100. var squared = amount * amount;
  1101. var cubed = amount * squared;
  1102. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1103. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1104. var part3 = (cubed - (2.0 * squared)) + amount;
  1105. var part4 = cubed - squared;
  1106. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1107. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1108. return new Vector2(x, y);
  1109. };
  1110. /**
  1111. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1112. */
  1113. Vector2.Lerp = function (start, end, amount) {
  1114. var x = start.x + ((end.x - start.x) * amount);
  1115. var y = start.y + ((end.y - start.y) * amount);
  1116. return new Vector2(x, y);
  1117. };
  1118. /**
  1119. * Returns the dot product (float) of the vector "left" and the vector "right".
  1120. */
  1121. Vector2.Dot = function (left, right) {
  1122. return left.x * right.x + left.y * right.y;
  1123. };
  1124. /**
  1125. * Returns a new Vector2 equal to the normalized passed vector.
  1126. */
  1127. Vector2.Normalize = function (vector) {
  1128. var newVector = vector.clone();
  1129. newVector.normalize();
  1130. return newVector;
  1131. };
  1132. /**
  1133. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1134. */
  1135. Vector2.Minimize = function (left, right) {
  1136. var x = (left.x < right.x) ? left.x : right.x;
  1137. var y = (left.y < right.y) ? left.y : right.y;
  1138. return new Vector2(x, y);
  1139. };
  1140. /**
  1141. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1142. */
  1143. Vector2.Maximize = function (left, right) {
  1144. var x = (left.x > right.x) ? left.x : right.x;
  1145. var y = (left.y > right.y) ? left.y : right.y;
  1146. return new Vector2(x, y);
  1147. };
  1148. /**
  1149. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1150. */
  1151. Vector2.Transform = function (vector, transformation) {
  1152. var r = Vector2.Zero();
  1153. Vector2.TransformToRef(vector, transformation, r);
  1154. return r;
  1155. };
  1156. /**
  1157. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1158. */
  1159. Vector2.TransformToRef = function (vector, transformation, result) {
  1160. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1161. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1162. result.x = x;
  1163. result.y = y;
  1164. };
  1165. /**
  1166. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1167. */
  1168. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1169. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1170. var sign = a < 0 ? -1 : 1;
  1171. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1172. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1173. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1174. };
  1175. /**
  1176. * Returns the distance (float) between the vectors "value1" and "value2".
  1177. */
  1178. Vector2.Distance = function (value1, value2) {
  1179. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1180. };
  1181. /**
  1182. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1183. */
  1184. Vector2.DistanceSquared = function (value1, value2) {
  1185. var x = value1.x - value2.x;
  1186. var y = value1.y - value2.y;
  1187. return (x * x) + (y * y);
  1188. };
  1189. /**
  1190. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1191. */
  1192. Vector2.Center = function (value1, value2) {
  1193. var center = value1.add(value2);
  1194. center.scaleInPlace(0.5);
  1195. return center;
  1196. };
  1197. /**
  1198. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1199. */
  1200. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1201. var l2 = Vector2.DistanceSquared(segA, segB);
  1202. if (l2 === 0.0) {
  1203. return Vector2.Distance(p, segA);
  1204. }
  1205. var v = segB.subtract(segA);
  1206. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1207. var proj = segA.add(v.multiplyByFloats(t, t));
  1208. return Vector2.Distance(p, proj);
  1209. };
  1210. return Vector2;
  1211. }());
  1212. BABYLON.Vector2 = Vector2;
  1213. var Vector3 = /** @class */ (function () {
  1214. /**
  1215. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1216. * A Vector3 is the main object used in 3D geometry.
  1217. * It can represent etiher the coordinates of a point the space, either a direction.
  1218. */
  1219. function Vector3(x, y, z) {
  1220. this.x = x;
  1221. this.y = y;
  1222. this.z = z;
  1223. }
  1224. /**
  1225. * Returns a string with the Vector3 coordinates.
  1226. */
  1227. Vector3.prototype.toString = function () {
  1228. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1229. };
  1230. /**
  1231. * Returns the string "Vector3"
  1232. */
  1233. Vector3.prototype.getClassName = function () {
  1234. return "Vector3";
  1235. };
  1236. /**
  1237. * Returns the Vector hash code.
  1238. */
  1239. Vector3.prototype.getHashCode = function () {
  1240. var hash = this.x || 0;
  1241. hash = (hash * 397) ^ (this.y || 0);
  1242. hash = (hash * 397) ^ (this.z || 0);
  1243. return hash;
  1244. };
  1245. // Operators
  1246. /**
  1247. * Returns a new array with three elements : the coordinates the Vector3.
  1248. */
  1249. Vector3.prototype.asArray = function () {
  1250. var result = [];
  1251. this.toArray(result, 0);
  1252. return result;
  1253. };
  1254. /**
  1255. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1256. * Returns the Vector3.
  1257. */
  1258. Vector3.prototype.toArray = function (array, index) {
  1259. if (index === void 0) { index = 0; }
  1260. array[index] = this.x;
  1261. array[index + 1] = this.y;
  1262. array[index + 2] = this.z;
  1263. return this;
  1264. };
  1265. /**
  1266. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1267. */
  1268. Vector3.prototype.toQuaternion = function () {
  1269. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1270. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1271. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1272. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1273. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1274. var cosy = Math.cos(this.y * 0.5);
  1275. var siny = Math.sin(this.y * 0.5);
  1276. result.x = coszMinusx * siny;
  1277. result.y = -sinzMinusx * siny;
  1278. result.z = sinxPlusz * cosy;
  1279. result.w = cosxPlusz * cosy;
  1280. return result;
  1281. };
  1282. /**
  1283. * Adds the passed vector to the current Vector3.
  1284. * Returns the updated Vector3.
  1285. */
  1286. Vector3.prototype.addInPlace = function (otherVector) {
  1287. this.x += otherVector.x;
  1288. this.y += otherVector.y;
  1289. this.z += otherVector.z;
  1290. return this;
  1291. };
  1292. /**
  1293. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1294. */
  1295. Vector3.prototype.add = function (otherVector) {
  1296. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1297. };
  1298. /**
  1299. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1300. * Returns the current Vector3.
  1301. */
  1302. Vector3.prototype.addToRef = function (otherVector, result) {
  1303. result.x = this.x + otherVector.x;
  1304. result.y = this.y + otherVector.y;
  1305. result.z = this.z + otherVector.z;
  1306. return this;
  1307. };
  1308. /**
  1309. * Subtract the passed vector from the current Vector3.
  1310. * Returns the updated Vector3.
  1311. */
  1312. Vector3.prototype.subtractInPlace = function (otherVector) {
  1313. this.x -= otherVector.x;
  1314. this.y -= otherVector.y;
  1315. this.z -= otherVector.z;
  1316. return this;
  1317. };
  1318. /**
  1319. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1320. */
  1321. Vector3.prototype.subtract = function (otherVector) {
  1322. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1323. };
  1324. /**
  1325. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1326. * Returns the current Vector3.
  1327. */
  1328. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1329. result.x = this.x - otherVector.x;
  1330. result.y = this.y - otherVector.y;
  1331. result.z = this.z - otherVector.z;
  1332. return this;
  1333. };
  1334. /**
  1335. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1336. */
  1337. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1338. return new Vector3(this.x - x, this.y - y, this.z - z);
  1339. };
  1340. /**
  1341. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1342. * Returns the current Vector3.
  1343. */
  1344. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1345. result.x = this.x - x;
  1346. result.y = this.y - y;
  1347. result.z = this.z - z;
  1348. return this;
  1349. };
  1350. /**
  1351. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1352. */
  1353. Vector3.prototype.negate = function () {
  1354. return new Vector3(-this.x, -this.y, -this.z);
  1355. };
  1356. /**
  1357. * Multiplies the Vector3 coordinates by the float "scale".
  1358. * Returns the updated Vector3.
  1359. */
  1360. Vector3.prototype.scaleInPlace = function (scale) {
  1361. this.x *= scale;
  1362. this.y *= scale;
  1363. this.z *= scale;
  1364. return this;
  1365. };
  1366. /**
  1367. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1368. */
  1369. Vector3.prototype.scale = function (scale) {
  1370. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1371. };
  1372. /**
  1373. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1374. * Returns the current Vector3.
  1375. */
  1376. Vector3.prototype.scaleToRef = function (scale, result) {
  1377. result.x = this.x * scale;
  1378. result.y = this.y * scale;
  1379. result.z = this.z * scale;
  1380. return this;
  1381. };
  1382. /**
  1383. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1384. */
  1385. Vector3.prototype.equals = function (otherVector) {
  1386. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1387. };
  1388. /**
  1389. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1390. */
  1391. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1392. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1393. 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);
  1394. };
  1395. /**
  1396. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1397. */
  1398. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1399. return this.x === x && this.y === y && this.z === z;
  1400. };
  1401. /**
  1402. * Muliplies the current Vector3 coordinates by the passed ones.
  1403. * Returns the updated Vector3.
  1404. */
  1405. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1406. this.x *= otherVector.x;
  1407. this.y *= otherVector.y;
  1408. this.z *= otherVector.z;
  1409. return this;
  1410. };
  1411. /**
  1412. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1413. */
  1414. Vector3.prototype.multiply = function (otherVector) {
  1415. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1416. };
  1417. /**
  1418. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1419. * Returns the current Vector3.
  1420. */
  1421. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1422. result.x = this.x * otherVector.x;
  1423. result.y = this.y * otherVector.y;
  1424. result.z = this.z * otherVector.z;
  1425. return this;
  1426. };
  1427. /**
  1428. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1429. */
  1430. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1431. return new Vector3(this.x * x, this.y * y, this.z * z);
  1432. };
  1433. /**
  1434. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1435. */
  1436. Vector3.prototype.divide = function (otherVector) {
  1437. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1438. };
  1439. /**
  1440. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1441. * Returns the current Vector3.
  1442. */
  1443. Vector3.prototype.divideToRef = function (otherVector, result) {
  1444. result.x = this.x / otherVector.x;
  1445. result.y = this.y / otherVector.y;
  1446. result.z = this.z / otherVector.z;
  1447. return this;
  1448. };
  1449. /**
  1450. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1451. * Returns the updated Vector3.
  1452. */
  1453. Vector3.prototype.MinimizeInPlace = function (other) {
  1454. if (other.x < this.x)
  1455. this.x = other.x;
  1456. if (other.y < this.y)
  1457. this.y = other.y;
  1458. if (other.z < this.z)
  1459. this.z = other.z;
  1460. return this;
  1461. };
  1462. /**
  1463. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1464. * Returns the updated Vector3.
  1465. */
  1466. Vector3.prototype.MaximizeInPlace = function (other) {
  1467. if (other.x > this.x)
  1468. this.x = other.x;
  1469. if (other.y > this.y)
  1470. this.y = other.y;
  1471. if (other.z > this.z)
  1472. this.z = other.z;
  1473. return this;
  1474. };
  1475. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1476. /**
  1477. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1478. */
  1479. get: function () {
  1480. var absX = Math.abs(this.x);
  1481. var absY = Math.abs(this.y);
  1482. if (absX !== absY) {
  1483. return true;
  1484. }
  1485. var absZ = Math.abs(this.z);
  1486. if (absX !== absZ) {
  1487. return true;
  1488. }
  1489. if (absY !== absZ) {
  1490. return true;
  1491. }
  1492. return false;
  1493. },
  1494. enumerable: true,
  1495. configurable: true
  1496. });
  1497. // Properties
  1498. /**
  1499. * Returns the length of the Vector3 (float).
  1500. */
  1501. Vector3.prototype.length = function () {
  1502. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1503. };
  1504. /**
  1505. * Returns the squared length of the Vector3 (float).
  1506. */
  1507. Vector3.prototype.lengthSquared = function () {
  1508. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1509. };
  1510. // Methods
  1511. /**
  1512. * Normalize the current Vector3.
  1513. * Returns the updated Vector3.
  1514. */
  1515. Vector3.prototype.normalize = function () {
  1516. var len = this.length();
  1517. if (len === 0 || len === 1.0)
  1518. return this;
  1519. var num = 1.0 / len;
  1520. this.x *= num;
  1521. this.y *= num;
  1522. this.z *= num;
  1523. return this;
  1524. };
  1525. /**
  1526. * Returns a new Vector3 copied from the current Vector3.
  1527. */
  1528. Vector3.prototype.clone = function () {
  1529. return new Vector3(this.x, this.y, this.z);
  1530. };
  1531. /**
  1532. * Copies the passed vector coordinates to the current Vector3 ones.
  1533. * Returns the updated Vector3.
  1534. */
  1535. Vector3.prototype.copyFrom = function (source) {
  1536. this.x = source.x;
  1537. this.y = source.y;
  1538. this.z = source.z;
  1539. return this;
  1540. };
  1541. /**
  1542. * Copies the passed floats to the current Vector3 coordinates.
  1543. * Returns the updated Vector3.
  1544. */
  1545. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1546. this.x = x;
  1547. this.y = y;
  1548. this.z = z;
  1549. return this;
  1550. };
  1551. /**
  1552. * Copies the passed floats to the current Vector3 coordinates.
  1553. * Returns the updated Vector3.
  1554. */
  1555. Vector3.prototype.set = function (x, y, z) {
  1556. return this.copyFromFloats(x, y, z);
  1557. };
  1558. // Statics
  1559. /**
  1560. *
  1561. */
  1562. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1563. var d0 = Vector3.Dot(vector0, axis) - size;
  1564. var d1 = Vector3.Dot(vector1, axis) - size;
  1565. var s = d0 / (d0 - d1);
  1566. return s;
  1567. };
  1568. /**
  1569. * Returns a new Vector3 set from the index "offset" of the passed array.
  1570. */
  1571. Vector3.FromArray = function (array, offset) {
  1572. if (!offset) {
  1573. offset = 0;
  1574. }
  1575. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1576. };
  1577. /**
  1578. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1579. * This function is deprecated. Use FromArray instead.
  1580. */
  1581. Vector3.FromFloatArray = function (array, offset) {
  1582. return Vector3.FromArray(array, offset);
  1583. };
  1584. /**
  1585. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1586. */
  1587. Vector3.FromArrayToRef = function (array, offset, result) {
  1588. result.x = array[offset];
  1589. result.y = array[offset + 1];
  1590. result.z = array[offset + 2];
  1591. };
  1592. /**
  1593. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1594. * This function is deprecated. Use FromArrayToRef instead.
  1595. */
  1596. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1597. return Vector3.FromArrayToRef(array, offset, result);
  1598. };
  1599. /**
  1600. * Sets the passed vector "result" with the passed floats.
  1601. */
  1602. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1603. result.x = x;
  1604. result.y = y;
  1605. result.z = z;
  1606. };
  1607. /**
  1608. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1609. */
  1610. Vector3.Zero = function () {
  1611. return new Vector3(0.0, 0.0, 0.0);
  1612. };
  1613. /**
  1614. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1615. */
  1616. Vector3.One = function () {
  1617. return new Vector3(1.0, 1.0, 1.0);
  1618. };
  1619. /**
  1620. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1621. */
  1622. Vector3.Up = function () {
  1623. return new Vector3(0.0, 1.0, 0.0);
  1624. };
  1625. /**
  1626. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1627. */
  1628. Vector3.Forward = function () {
  1629. return new Vector3(0.0, 0.0, 1.0);
  1630. };
  1631. /**
  1632. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1633. */
  1634. Vector3.Right = function () {
  1635. return new Vector3(1.0, 0.0, 0.0);
  1636. };
  1637. /**
  1638. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1639. */
  1640. Vector3.Left = function () {
  1641. return new Vector3(-1.0, 0.0, 0.0);
  1642. };
  1643. /**
  1644. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1645. * This method computes tranformed coordinates only, not transformed direction vectors.
  1646. */
  1647. Vector3.TransformCoordinates = function (vector, transformation) {
  1648. var result = Vector3.Zero();
  1649. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1650. return result;
  1651. };
  1652. /**
  1653. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1654. * This method computes tranformed coordinates only, not transformed direction vectors.
  1655. */
  1656. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1657. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1658. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1659. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1660. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1661. result.x = x / w;
  1662. result.y = y / w;
  1663. result.z = z / w;
  1664. };
  1665. /**
  1666. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1667. * This method computes tranformed coordinates only, not transformed direction vectors.
  1668. */
  1669. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1670. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1671. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1672. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1673. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1674. result.x = rx / rw;
  1675. result.y = ry / rw;
  1676. result.z = rz / rw;
  1677. };
  1678. /**
  1679. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1680. * This methods computes transformed normalized direction vectors only.
  1681. */
  1682. Vector3.TransformNormal = function (vector, transformation) {
  1683. var result = Vector3.Zero();
  1684. Vector3.TransformNormalToRef(vector, transformation, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1689. * This methods computes transformed normalized direction vectors only.
  1690. */
  1691. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1692. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1693. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1694. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1695. result.x = x;
  1696. result.y = y;
  1697. result.z = z;
  1698. };
  1699. /**
  1700. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1701. * This methods computes transformed normalized direction vectors only.
  1702. */
  1703. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1704. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1705. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1706. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1707. };
  1708. /**
  1709. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1710. */
  1711. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1712. var squared = amount * amount;
  1713. var cubed = amount * squared;
  1714. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1715. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1716. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1717. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1718. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1719. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1720. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1721. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1722. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1723. return new Vector3(x, y, z);
  1724. };
  1725. /**
  1726. * 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".
  1727. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1728. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1729. */
  1730. Vector3.Clamp = function (value, min, max) {
  1731. var x = value.x;
  1732. x = (x > max.x) ? max.x : x;
  1733. x = (x < min.x) ? min.x : x;
  1734. var y = value.y;
  1735. y = (y > max.y) ? max.y : y;
  1736. y = (y < min.y) ? min.y : y;
  1737. var z = value.z;
  1738. z = (z > max.z) ? max.z : z;
  1739. z = (z < min.z) ? min.z : z;
  1740. return new Vector3(x, y, z);
  1741. };
  1742. /**
  1743. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1744. */
  1745. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1746. var squared = amount * amount;
  1747. var cubed = amount * squared;
  1748. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1749. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1750. var part3 = (cubed - (2.0 * squared)) + amount;
  1751. var part4 = cubed - squared;
  1752. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1753. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1754. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1755. return new Vector3(x, y, z);
  1756. };
  1757. /**
  1758. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1759. */
  1760. Vector3.Lerp = function (start, end, amount) {
  1761. var result = new Vector3(0, 0, 0);
  1762. Vector3.LerpToRef(start, end, amount, result);
  1763. return result;
  1764. };
  1765. /**
  1766. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1767. */
  1768. Vector3.LerpToRef = function (start, end, amount, result) {
  1769. result.x = start.x + ((end.x - start.x) * amount);
  1770. result.y = start.y + ((end.y - start.y) * amount);
  1771. result.z = start.z + ((end.z - start.z) * amount);
  1772. };
  1773. /**
  1774. * Returns the dot product (float) between the vectors "left" and "right".
  1775. */
  1776. Vector3.Dot = function (left, right) {
  1777. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1778. };
  1779. /**
  1780. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1781. * The cross product is then orthogonal to both "left" and "right".
  1782. */
  1783. Vector3.Cross = function (left, right) {
  1784. var result = Vector3.Zero();
  1785. Vector3.CrossToRef(left, right, result);
  1786. return result;
  1787. };
  1788. /**
  1789. * Sets the passed vector "result" with the cross product of "left" and "right".
  1790. * The cross product is then orthogonal to both "left" and "right".
  1791. */
  1792. Vector3.CrossToRef = function (left, right, result) {
  1793. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1794. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1795. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1796. result.copyFrom(MathTmp.Vector3[0]);
  1797. };
  1798. /**
  1799. * Returns a new Vector3 as the normalization of the passed vector.
  1800. */
  1801. Vector3.Normalize = function (vector) {
  1802. var result = Vector3.Zero();
  1803. Vector3.NormalizeToRef(vector, result);
  1804. return result;
  1805. };
  1806. /**
  1807. * Sets the passed vector "result" with the normalization of the passed first vector.
  1808. */
  1809. Vector3.NormalizeToRef = function (vector, result) {
  1810. result.copyFrom(vector);
  1811. result.normalize();
  1812. };
  1813. Vector3.Project = function (vector, world, transform, viewport) {
  1814. var cw = viewport.width;
  1815. var ch = viewport.height;
  1816. var cx = viewport.x;
  1817. var cy = viewport.y;
  1818. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1819. 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);
  1820. var matrix = MathTmp.Matrix[0];
  1821. world.multiplyToRef(transform, matrix);
  1822. matrix.multiplyToRef(viewportMatrix, matrix);
  1823. return Vector3.TransformCoordinates(vector, matrix);
  1824. };
  1825. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1826. var matrix = MathTmp.Matrix[0];
  1827. world.multiplyToRef(transform, matrix);
  1828. matrix.invert();
  1829. source.x = source.x / viewportWidth * 2 - 1;
  1830. source.y = -(source.y / viewportHeight * 2 - 1);
  1831. var vector = Vector3.TransformCoordinates(source, matrix);
  1832. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1833. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1834. vector = vector.scale(1.0 / num);
  1835. }
  1836. return vector;
  1837. };
  1838. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1839. var matrix = MathTmp.Matrix[0];
  1840. world.multiplyToRef(view, matrix);
  1841. matrix.multiplyToRef(projection, matrix);
  1842. matrix.invert();
  1843. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1844. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1845. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1846. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1847. vector = vector.scale(1.0 / num);
  1848. }
  1849. return vector;
  1850. };
  1851. Vector3.Minimize = function (left, right) {
  1852. var min = left.clone();
  1853. min.MinimizeInPlace(right);
  1854. return min;
  1855. };
  1856. Vector3.Maximize = function (left, right) {
  1857. var max = left.clone();
  1858. max.MaximizeInPlace(right);
  1859. return max;
  1860. };
  1861. /**
  1862. * Returns the distance (float) between the vectors "value1" and "value2".
  1863. */
  1864. Vector3.Distance = function (value1, value2) {
  1865. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1866. };
  1867. /**
  1868. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1869. */
  1870. Vector3.DistanceSquared = function (value1, value2) {
  1871. var x = value1.x - value2.x;
  1872. var y = value1.y - value2.y;
  1873. var z = value1.z - value2.z;
  1874. return (x * x) + (y * y) + (z * z);
  1875. };
  1876. /**
  1877. * Returns a new Vector3 located at the center between "value1" and "value2".
  1878. */
  1879. Vector3.Center = function (value1, value2) {
  1880. var center = value1.add(value2);
  1881. center.scaleInPlace(0.5);
  1882. return center;
  1883. };
  1884. /**
  1885. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1886. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1887. * to something in order to rotate it from its local system to the given target system.
  1888. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1889. * Returns a new Vector3.
  1890. */
  1891. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1892. var rotation = Vector3.Zero();
  1893. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1894. return rotation;
  1895. };
  1896. /**
  1897. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1898. */
  1899. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1900. var quat = MathTmp.Quaternion[0];
  1901. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1902. quat.toEulerAnglesToRef(ref);
  1903. };
  1904. return Vector3;
  1905. }());
  1906. BABYLON.Vector3 = Vector3;
  1907. //Vector4 class created for EulerAngle class conversion to Quaternion
  1908. var Vector4 = /** @class */ (function () {
  1909. /**
  1910. * Creates a Vector4 object from the passed floats.
  1911. */
  1912. function Vector4(x, y, z, w) {
  1913. this.x = x;
  1914. this.y = y;
  1915. this.z = z;
  1916. this.w = w;
  1917. }
  1918. /**
  1919. * Returns the string with the Vector4 coordinates.
  1920. */
  1921. Vector4.prototype.toString = function () {
  1922. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1923. };
  1924. /**
  1925. * Returns the string "Vector4".
  1926. */
  1927. Vector4.prototype.getClassName = function () {
  1928. return "Vector4";
  1929. };
  1930. /**
  1931. * Returns the Vector4 hash code.
  1932. */
  1933. Vector4.prototype.getHashCode = function () {
  1934. var hash = this.x || 0;
  1935. hash = (hash * 397) ^ (this.y || 0);
  1936. hash = (hash * 397) ^ (this.z || 0);
  1937. hash = (hash * 397) ^ (this.w || 0);
  1938. return hash;
  1939. };
  1940. // Operators
  1941. /**
  1942. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1943. */
  1944. Vector4.prototype.asArray = function () {
  1945. var result = new Array();
  1946. this.toArray(result, 0);
  1947. return result;
  1948. };
  1949. /**
  1950. * Populates the passed array from the passed index with the Vector4 coordinates.
  1951. * Returns the Vector4.
  1952. */
  1953. Vector4.prototype.toArray = function (array, index) {
  1954. if (index === undefined) {
  1955. index = 0;
  1956. }
  1957. array[index] = this.x;
  1958. array[index + 1] = this.y;
  1959. array[index + 2] = this.z;
  1960. array[index + 3] = this.w;
  1961. return this;
  1962. };
  1963. /**
  1964. * Adds the passed vector to the current Vector4.
  1965. * Returns the updated Vector4.
  1966. */
  1967. Vector4.prototype.addInPlace = function (otherVector) {
  1968. this.x += otherVector.x;
  1969. this.y += otherVector.y;
  1970. this.z += otherVector.z;
  1971. this.w += otherVector.w;
  1972. return this;
  1973. };
  1974. /**
  1975. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1976. */
  1977. Vector4.prototype.add = function (otherVector) {
  1978. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1979. };
  1980. /**
  1981. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1982. * Returns the current Vector4.
  1983. */
  1984. Vector4.prototype.addToRef = function (otherVector, result) {
  1985. result.x = this.x + otherVector.x;
  1986. result.y = this.y + otherVector.y;
  1987. result.z = this.z + otherVector.z;
  1988. result.w = this.w + otherVector.w;
  1989. return this;
  1990. };
  1991. /**
  1992. * Subtract in place the passed vector from the current Vector4.
  1993. * Returns the updated Vector4.
  1994. */
  1995. Vector4.prototype.subtractInPlace = function (otherVector) {
  1996. this.x -= otherVector.x;
  1997. this.y -= otherVector.y;
  1998. this.z -= otherVector.z;
  1999. this.w -= otherVector.w;
  2000. return this;
  2001. };
  2002. /**
  2003. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2004. */
  2005. Vector4.prototype.subtract = function (otherVector) {
  2006. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2007. };
  2008. /**
  2009. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2010. * Returns the current Vector4.
  2011. */
  2012. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2013. result.x = this.x - otherVector.x;
  2014. result.y = this.y - otherVector.y;
  2015. result.z = this.z - otherVector.z;
  2016. result.w = this.w - otherVector.w;
  2017. return this;
  2018. };
  2019. /**
  2020. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2021. */
  2022. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2023. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2024. };
  2025. /**
  2026. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2027. * Returns the current Vector4.
  2028. */
  2029. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2030. result.x = this.x - x;
  2031. result.y = this.y - y;
  2032. result.z = this.z - z;
  2033. result.w = this.w - w;
  2034. return this;
  2035. };
  2036. /**
  2037. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2038. */
  2039. Vector4.prototype.negate = function () {
  2040. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2041. };
  2042. /**
  2043. * Multiplies the current Vector4 coordinates by scale (float).
  2044. * Returns the updated Vector4.
  2045. */
  2046. Vector4.prototype.scaleInPlace = function (scale) {
  2047. this.x *= scale;
  2048. this.y *= scale;
  2049. this.z *= scale;
  2050. this.w *= scale;
  2051. return this;
  2052. };
  2053. /**
  2054. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2055. */
  2056. Vector4.prototype.scale = function (scale) {
  2057. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2058. };
  2059. /**
  2060. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2061. * Returns the current Vector4.
  2062. */
  2063. Vector4.prototype.scaleToRef = function (scale, result) {
  2064. result.x = this.x * scale;
  2065. result.y = this.y * scale;
  2066. result.z = this.z * scale;
  2067. result.w = this.w * scale;
  2068. return this;
  2069. };
  2070. /**
  2071. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2072. */
  2073. Vector4.prototype.equals = function (otherVector) {
  2074. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2075. };
  2076. /**
  2077. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2078. */
  2079. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2080. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2081. return otherVector
  2082. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2083. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2084. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2085. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2086. };
  2087. /**
  2088. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2089. */
  2090. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2091. return this.x === x && this.y === y && this.z === z && this.w === w;
  2092. };
  2093. /**
  2094. * Multiplies in place the current Vector4 by the passed one.
  2095. * Returns the updated Vector4.
  2096. */
  2097. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2098. this.x *= otherVector.x;
  2099. this.y *= otherVector.y;
  2100. this.z *= otherVector.z;
  2101. this.w *= otherVector.w;
  2102. return this;
  2103. };
  2104. /**
  2105. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2106. */
  2107. Vector4.prototype.multiply = function (otherVector) {
  2108. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2109. };
  2110. /**
  2111. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2112. * Returns the current Vector4.
  2113. */
  2114. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2115. result.x = this.x * otherVector.x;
  2116. result.y = this.y * otherVector.y;
  2117. result.z = this.z * otherVector.z;
  2118. result.w = this.w * otherVector.w;
  2119. return this;
  2120. };
  2121. /**
  2122. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2123. */
  2124. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2125. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2126. };
  2127. /**
  2128. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2129. */
  2130. Vector4.prototype.divide = function (otherVector) {
  2131. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2132. };
  2133. /**
  2134. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2135. * Returns the current Vector4.
  2136. */
  2137. Vector4.prototype.divideToRef = function (otherVector, result) {
  2138. result.x = this.x / otherVector.x;
  2139. result.y = this.y / otherVector.y;
  2140. result.z = this.z / otherVector.z;
  2141. result.w = this.w / otherVector.w;
  2142. return this;
  2143. };
  2144. /**
  2145. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2146. */
  2147. Vector4.prototype.MinimizeInPlace = function (other) {
  2148. if (other.x < this.x)
  2149. this.x = other.x;
  2150. if (other.y < this.y)
  2151. this.y = other.y;
  2152. if (other.z < this.z)
  2153. this.z = other.z;
  2154. if (other.w < this.w)
  2155. this.w = other.w;
  2156. return this;
  2157. };
  2158. /**
  2159. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2160. */
  2161. Vector4.prototype.MaximizeInPlace = function (other) {
  2162. if (other.x > this.x)
  2163. this.x = other.x;
  2164. if (other.y > this.y)
  2165. this.y = other.y;
  2166. if (other.z > this.z)
  2167. this.z = other.z;
  2168. if (other.w > this.w)
  2169. this.w = other.w;
  2170. return this;
  2171. };
  2172. // Properties
  2173. /**
  2174. * Returns the Vector4 length (float).
  2175. */
  2176. Vector4.prototype.length = function () {
  2177. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2178. };
  2179. /**
  2180. * Returns the Vector4 squared length (float).
  2181. */
  2182. Vector4.prototype.lengthSquared = function () {
  2183. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2184. };
  2185. // Methods
  2186. /**
  2187. * Normalizes in place the Vector4.
  2188. * Returns the updated Vector4.
  2189. */
  2190. Vector4.prototype.normalize = function () {
  2191. var len = this.length();
  2192. if (len === 0)
  2193. return this;
  2194. var num = 1.0 / len;
  2195. this.x *= num;
  2196. this.y *= num;
  2197. this.z *= num;
  2198. this.w *= num;
  2199. return this;
  2200. };
  2201. /**
  2202. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2203. */
  2204. Vector4.prototype.toVector3 = function () {
  2205. return new Vector3(this.x, this.y, this.z);
  2206. };
  2207. /**
  2208. * Returns a new Vector4 copied from the current one.
  2209. */
  2210. Vector4.prototype.clone = function () {
  2211. return new Vector4(this.x, this.y, this.z, this.w);
  2212. };
  2213. /**
  2214. * Updates the current Vector4 with the passed one coordinates.
  2215. * Returns the updated Vector4.
  2216. */
  2217. Vector4.prototype.copyFrom = function (source) {
  2218. this.x = source.x;
  2219. this.y = source.y;
  2220. this.z = source.z;
  2221. this.w = source.w;
  2222. return this;
  2223. };
  2224. /**
  2225. * Updates the current Vector4 coordinates with the passed floats.
  2226. * Returns the updated Vector4.
  2227. */
  2228. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2229. this.x = x;
  2230. this.y = y;
  2231. this.z = z;
  2232. this.w = w;
  2233. return this;
  2234. };
  2235. /**
  2236. * Updates the current Vector4 coordinates with the passed floats.
  2237. * Returns the updated Vector4.
  2238. */
  2239. Vector4.prototype.set = function (x, y, z, w) {
  2240. return this.copyFromFloats(x, y, z, w);
  2241. };
  2242. // Statics
  2243. /**
  2244. * Returns a new Vector4 set from the starting index of the passed array.
  2245. */
  2246. Vector4.FromArray = function (array, offset) {
  2247. if (!offset) {
  2248. offset = 0;
  2249. }
  2250. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2251. };
  2252. /**
  2253. * Updates the passed vector "result" from the starting index of the passed array.
  2254. */
  2255. Vector4.FromArrayToRef = function (array, offset, result) {
  2256. result.x = array[offset];
  2257. result.y = array[offset + 1];
  2258. result.z = array[offset + 2];
  2259. result.w = array[offset + 3];
  2260. };
  2261. /**
  2262. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2263. */
  2264. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2265. Vector4.FromArrayToRef(array, offset, result);
  2266. };
  2267. /**
  2268. * Updates the passed vector "result" coordinates from the passed floats.
  2269. */
  2270. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2271. result.x = x;
  2272. result.y = y;
  2273. result.z = z;
  2274. result.w = w;
  2275. };
  2276. /**
  2277. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2278. */
  2279. Vector4.Zero = function () {
  2280. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2281. };
  2282. /**
  2283. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2284. */
  2285. Vector4.One = function () {
  2286. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2287. };
  2288. /**
  2289. * Returns a new normalized Vector4 from the passed one.
  2290. */
  2291. Vector4.Normalize = function (vector) {
  2292. var result = Vector4.Zero();
  2293. Vector4.NormalizeToRef(vector, result);
  2294. return result;
  2295. };
  2296. /**
  2297. * Updates the passed vector "result" from the normalization of the passed one.
  2298. */
  2299. Vector4.NormalizeToRef = function (vector, result) {
  2300. result.copyFrom(vector);
  2301. result.normalize();
  2302. };
  2303. Vector4.Minimize = function (left, right) {
  2304. var min = left.clone();
  2305. min.MinimizeInPlace(right);
  2306. return min;
  2307. };
  2308. Vector4.Maximize = function (left, right) {
  2309. var max = left.clone();
  2310. max.MaximizeInPlace(right);
  2311. return max;
  2312. };
  2313. /**
  2314. * Returns the distance (float) between the vectors "value1" and "value2".
  2315. */
  2316. Vector4.Distance = function (value1, value2) {
  2317. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2318. };
  2319. /**
  2320. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2321. */
  2322. Vector4.DistanceSquared = function (value1, value2) {
  2323. var x = value1.x - value2.x;
  2324. var y = value1.y - value2.y;
  2325. var z = value1.z - value2.z;
  2326. var w = value1.w - value2.w;
  2327. return (x * x) + (y * y) + (z * z) + (w * w);
  2328. };
  2329. /**
  2330. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2331. */
  2332. Vector4.Center = function (value1, value2) {
  2333. var center = value1.add(value2);
  2334. center.scaleInPlace(0.5);
  2335. return center;
  2336. };
  2337. /**
  2338. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2339. * This methods computes transformed normalized direction vectors only.
  2340. */
  2341. Vector4.TransformNormal = function (vector, transformation) {
  2342. var result = Vector4.Zero();
  2343. Vector4.TransformNormalToRef(vector, transformation, result);
  2344. return result;
  2345. };
  2346. /**
  2347. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2348. * This methods computes transformed normalized direction vectors only.
  2349. */
  2350. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2351. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2352. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2353. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2354. result.x = x;
  2355. result.y = y;
  2356. result.z = z;
  2357. result.w = vector.w;
  2358. };
  2359. /**
  2360. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2361. * This methods computes transformed normalized direction vectors only.
  2362. */
  2363. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2364. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2365. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2366. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2367. result.w = w;
  2368. };
  2369. return Vector4;
  2370. }());
  2371. BABYLON.Vector4 = Vector4;
  2372. var Size = /** @class */ (function () {
  2373. /**
  2374. * Creates a Size object from the passed width and height (floats).
  2375. */
  2376. function Size(width, height) {
  2377. this.width = width;
  2378. this.height = height;
  2379. }
  2380. // Returns a string with the Size width and height.
  2381. Size.prototype.toString = function () {
  2382. return "{W: " + this.width + ", H: " + this.height + "}";
  2383. };
  2384. /**
  2385. * Returns the string "Size"
  2386. */
  2387. Size.prototype.getClassName = function () {
  2388. return "Size";
  2389. };
  2390. /**
  2391. * Returns the Size hash code.
  2392. */
  2393. Size.prototype.getHashCode = function () {
  2394. var hash = this.width || 0;
  2395. hash = (hash * 397) ^ (this.height || 0);
  2396. return hash;
  2397. };
  2398. /**
  2399. * Updates the current size from the passed one.
  2400. * Returns the updated Size.
  2401. */
  2402. Size.prototype.copyFrom = function (src) {
  2403. this.width = src.width;
  2404. this.height = src.height;
  2405. };
  2406. /**
  2407. * Updates in place the current Size from the passed floats.
  2408. * Returns the updated Size.
  2409. */
  2410. Size.prototype.copyFromFloats = function (width, height) {
  2411. this.width = width;
  2412. this.height = height;
  2413. return this;
  2414. };
  2415. /**
  2416. * Updates in place the current Size from the passed floats.
  2417. * Returns the updated Size.
  2418. */
  2419. Size.prototype.set = function (width, height) {
  2420. return this.copyFromFloats(width, height);
  2421. };
  2422. /**
  2423. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2424. */
  2425. Size.prototype.multiplyByFloats = function (w, h) {
  2426. return new Size(this.width * w, this.height * h);
  2427. };
  2428. /**
  2429. * Returns a new Size copied from the passed one.
  2430. */
  2431. Size.prototype.clone = function () {
  2432. return new Size(this.width, this.height);
  2433. };
  2434. /**
  2435. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2436. */
  2437. Size.prototype.equals = function (other) {
  2438. if (!other) {
  2439. return false;
  2440. }
  2441. return (this.width === other.width) && (this.height === other.height);
  2442. };
  2443. Object.defineProperty(Size.prototype, "surface", {
  2444. /**
  2445. * Returns the surface of the Size : width * height (float).
  2446. */
  2447. get: function () {
  2448. return this.width * this.height;
  2449. },
  2450. enumerable: true,
  2451. configurable: true
  2452. });
  2453. /**
  2454. * Returns a new Size set to (0.0, 0.0)
  2455. */
  2456. Size.Zero = function () {
  2457. return new Size(0.0, 0.0);
  2458. };
  2459. /**
  2460. * Returns a new Size set as the addition result of the current Size and the passed one.
  2461. */
  2462. Size.prototype.add = function (otherSize) {
  2463. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2464. return r;
  2465. };
  2466. /**
  2467. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2468. */
  2469. Size.prototype.subtract = function (otherSize) {
  2470. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2471. return r;
  2472. };
  2473. /**
  2474. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2475. */
  2476. Size.Lerp = function (start, end, amount) {
  2477. var w = start.width + ((end.width - start.width) * amount);
  2478. var h = start.height + ((end.height - start.height) * amount);
  2479. return new Size(w, h);
  2480. };
  2481. return Size;
  2482. }());
  2483. BABYLON.Size = Size;
  2484. var Quaternion = /** @class */ (function () {
  2485. /**
  2486. * Creates a new Quaternion from the passed floats.
  2487. */
  2488. function Quaternion(x, y, z, w) {
  2489. if (x === void 0) { x = 0.0; }
  2490. if (y === void 0) { y = 0.0; }
  2491. if (z === void 0) { z = 0.0; }
  2492. if (w === void 0) { w = 1.0; }
  2493. this.x = x;
  2494. this.y = y;
  2495. this.z = z;
  2496. this.w = w;
  2497. }
  2498. /**
  2499. * Returns a string with the Quaternion coordinates.
  2500. */
  2501. Quaternion.prototype.toString = function () {
  2502. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2503. };
  2504. /**
  2505. * Returns the string "Quaternion".
  2506. */
  2507. Quaternion.prototype.getClassName = function () {
  2508. return "Quaternion";
  2509. };
  2510. /**
  2511. * Returns the Quaternion hash code.
  2512. */
  2513. Quaternion.prototype.getHashCode = function () {
  2514. var hash = this.x || 0;
  2515. hash = (hash * 397) ^ (this.y || 0);
  2516. hash = (hash * 397) ^ (this.z || 0);
  2517. hash = (hash * 397) ^ (this.w || 0);
  2518. return hash;
  2519. };
  2520. /**
  2521. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2522. */
  2523. Quaternion.prototype.asArray = function () {
  2524. return [this.x, this.y, this.z, this.w];
  2525. };
  2526. /**
  2527. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2528. */
  2529. Quaternion.prototype.equals = function (otherQuaternion) {
  2530. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2531. };
  2532. /**
  2533. * Returns a new Quaternion copied from the current one.
  2534. */
  2535. Quaternion.prototype.clone = function () {
  2536. return new Quaternion(this.x, this.y, this.z, this.w);
  2537. };
  2538. /**
  2539. * Updates the current Quaternion from the passed one coordinates.
  2540. * Returns the updated Quaterion.
  2541. */
  2542. Quaternion.prototype.copyFrom = function (other) {
  2543. this.x = other.x;
  2544. this.y = other.y;
  2545. this.z = other.z;
  2546. this.w = other.w;
  2547. return this;
  2548. };
  2549. /**
  2550. * Updates the current Quaternion from the passed float coordinates.
  2551. * Returns the updated Quaterion.
  2552. */
  2553. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2554. this.x = x;
  2555. this.y = y;
  2556. this.z = z;
  2557. this.w = w;
  2558. return this;
  2559. };
  2560. /**
  2561. * Updates the current Quaternion from the passed float coordinates.
  2562. * Returns the updated Quaterion.
  2563. */
  2564. Quaternion.prototype.set = function (x, y, z, w) {
  2565. return this.copyFromFloats(x, y, z, w);
  2566. };
  2567. /**
  2568. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2569. */
  2570. Quaternion.prototype.add = function (other) {
  2571. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2572. };
  2573. /**
  2574. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2575. */
  2576. Quaternion.prototype.subtract = function (other) {
  2577. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2578. };
  2579. /**
  2580. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2581. */
  2582. Quaternion.prototype.scale = function (value) {
  2583. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2584. };
  2585. /**
  2586. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2587. */
  2588. Quaternion.prototype.multiply = function (q1) {
  2589. var result = new Quaternion(0, 0, 0, 1.0);
  2590. this.multiplyToRef(q1, result);
  2591. return result;
  2592. };
  2593. /**
  2594. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2595. * Returns the current Quaternion.
  2596. */
  2597. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2598. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2599. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2600. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2601. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2602. result.copyFromFloats(x, y, z, w);
  2603. return this;
  2604. };
  2605. /**
  2606. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2607. * Returns the updated Quaternion.
  2608. */
  2609. Quaternion.prototype.multiplyInPlace = function (q1) {
  2610. this.multiplyToRef(q1, this);
  2611. return this;
  2612. };
  2613. /**
  2614. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2615. * Returns the current Quaternion.
  2616. */
  2617. Quaternion.prototype.conjugateToRef = function (ref) {
  2618. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2619. return this;
  2620. };
  2621. /**
  2622. * Conjugates in place the current Quaternion.
  2623. * Returns the updated Quaternion.
  2624. */
  2625. Quaternion.prototype.conjugateInPlace = function () {
  2626. this.x *= -1;
  2627. this.y *= -1;
  2628. this.z *= -1;
  2629. return this;
  2630. };
  2631. /**
  2632. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2633. */
  2634. Quaternion.prototype.conjugate = function () {
  2635. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2636. return result;
  2637. };
  2638. /**
  2639. * Returns the Quaternion length (float).
  2640. */
  2641. Quaternion.prototype.length = function () {
  2642. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2643. };
  2644. /**
  2645. * Normalize in place the current Quaternion.
  2646. * Returns the updated Quaternion.
  2647. */
  2648. Quaternion.prototype.normalize = function () {
  2649. var length = 1.0 / this.length();
  2650. this.x *= length;
  2651. this.y *= length;
  2652. this.z *= length;
  2653. this.w *= length;
  2654. return this;
  2655. };
  2656. /**
  2657. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2658. */
  2659. Quaternion.prototype.toEulerAngles = function (order) {
  2660. if (order === void 0) { order = "YZX"; }
  2661. var result = Vector3.Zero();
  2662. this.toEulerAnglesToRef(result, order);
  2663. return result;
  2664. };
  2665. /**
  2666. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2667. * Returns the current Quaternion.
  2668. */
  2669. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2670. if (order === void 0) { order = "YZX"; }
  2671. var qz = this.z;
  2672. var qx = this.x;
  2673. var qy = this.y;
  2674. var qw = this.w;
  2675. var sqw = qw * qw;
  2676. var sqz = qz * qz;
  2677. var sqx = qx * qx;
  2678. var sqy = qy * qy;
  2679. var zAxisY = qy * qz - qx * qw;
  2680. var limit = .4999999;
  2681. if (zAxisY < -limit) {
  2682. result.y = 2 * Math.atan2(qy, qw);
  2683. result.x = Math.PI / 2;
  2684. result.z = 0;
  2685. }
  2686. else if (zAxisY > limit) {
  2687. result.y = 2 * Math.atan2(qy, qw);
  2688. result.x = -Math.PI / 2;
  2689. result.z = 0;
  2690. }
  2691. else {
  2692. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2693. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2694. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2695. }
  2696. return this;
  2697. };
  2698. /**
  2699. * Updates the passed rotation matrix with the current Quaternion values.
  2700. * Returns the current Quaternion.
  2701. */
  2702. Quaternion.prototype.toRotationMatrix = function (result) {
  2703. var xx = this.x * this.x;
  2704. var yy = this.y * this.y;
  2705. var zz = this.z * this.z;
  2706. var xy = this.x * this.y;
  2707. var zw = this.z * this.w;
  2708. var zx = this.z * this.x;
  2709. var yw = this.y * this.w;
  2710. var yz = this.y * this.z;
  2711. var xw = this.x * this.w;
  2712. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2713. result.m[1] = 2.0 * (xy + zw);
  2714. result.m[2] = 2.0 * (zx - yw);
  2715. result.m[3] = 0;
  2716. result.m[4] = 2.0 * (xy - zw);
  2717. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2718. result.m[6] = 2.0 * (yz + xw);
  2719. result.m[7] = 0;
  2720. result.m[8] = 2.0 * (zx + yw);
  2721. result.m[9] = 2.0 * (yz - xw);
  2722. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2723. result.m[11] = 0;
  2724. result.m[12] = 0;
  2725. result.m[13] = 0;
  2726. result.m[14] = 0;
  2727. result.m[15] = 1.0;
  2728. result._markAsUpdated();
  2729. return this;
  2730. };
  2731. /**
  2732. * Updates the current Quaternion from the passed rotation matrix values.
  2733. * Returns the updated Quaternion.
  2734. */
  2735. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2736. Quaternion.FromRotationMatrixToRef(matrix, this);
  2737. return this;
  2738. };
  2739. // Statics
  2740. /**
  2741. * Returns a new Quaternion set from the passed rotation matrix values.
  2742. */
  2743. Quaternion.FromRotationMatrix = function (matrix) {
  2744. var result = new Quaternion();
  2745. Quaternion.FromRotationMatrixToRef(matrix, result);
  2746. return result;
  2747. };
  2748. /**
  2749. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2750. */
  2751. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2752. var data = matrix.m;
  2753. var m11 = data[0], m12 = data[4], m13 = data[8];
  2754. var m21 = data[1], m22 = data[5], m23 = data[9];
  2755. var m31 = data[2], m32 = data[6], m33 = data[10];
  2756. var trace = m11 + m22 + m33;
  2757. var s;
  2758. if (trace > 0) {
  2759. s = 0.5 / Math.sqrt(trace + 1.0);
  2760. result.w = 0.25 / s;
  2761. result.x = (m32 - m23) * s;
  2762. result.y = (m13 - m31) * s;
  2763. result.z = (m21 - m12) * s;
  2764. }
  2765. else if (m11 > m22 && m11 > m33) {
  2766. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2767. result.w = (m32 - m23) / s;
  2768. result.x = 0.25 * s;
  2769. result.y = (m12 + m21) / s;
  2770. result.z = (m13 + m31) / s;
  2771. }
  2772. else if (m22 > m33) {
  2773. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2774. result.w = (m13 - m31) / s;
  2775. result.x = (m12 + m21) / s;
  2776. result.y = 0.25 * s;
  2777. result.z = (m23 + m32) / s;
  2778. }
  2779. else {
  2780. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2781. result.w = (m21 - m12) / s;
  2782. result.x = (m13 + m31) / s;
  2783. result.y = (m23 + m32) / s;
  2784. result.z = 0.25 * s;
  2785. }
  2786. };
  2787. /**
  2788. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2789. */
  2790. Quaternion.Zero = function () {
  2791. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2792. };
  2793. /**
  2794. * Returns a new Quaternion as the inverted current Quaternion.
  2795. */
  2796. Quaternion.Inverse = function (q) {
  2797. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2798. };
  2799. /**
  2800. * Returns the identity Quaternion.
  2801. */
  2802. Quaternion.Identity = function () {
  2803. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2804. };
  2805. Quaternion.IsIdentity = function (quaternion) {
  2806. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2807. };
  2808. /**
  2809. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2810. */
  2811. Quaternion.RotationAxis = function (axis, angle) {
  2812. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2813. };
  2814. /**
  2815. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2816. */
  2817. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2818. var sin = Math.sin(angle / 2);
  2819. axis.normalize();
  2820. result.w = Math.cos(angle / 2);
  2821. result.x = axis.x * sin;
  2822. result.y = axis.y * sin;
  2823. result.z = axis.z * sin;
  2824. return result;
  2825. };
  2826. /**
  2827. * Retuns a new Quaternion set from the starting index of the passed array.
  2828. */
  2829. Quaternion.FromArray = function (array, offset) {
  2830. if (!offset) {
  2831. offset = 0;
  2832. }
  2833. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2834. };
  2835. /**
  2836. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2837. */
  2838. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2839. var q = new Quaternion();
  2840. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2841. return q;
  2842. };
  2843. /**
  2844. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2845. */
  2846. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2847. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2848. var halfRoll = roll * 0.5;
  2849. var halfPitch = pitch * 0.5;
  2850. var halfYaw = yaw * 0.5;
  2851. var sinRoll = Math.sin(halfRoll);
  2852. var cosRoll = Math.cos(halfRoll);
  2853. var sinPitch = Math.sin(halfPitch);
  2854. var cosPitch = Math.cos(halfPitch);
  2855. var sinYaw = Math.sin(halfYaw);
  2856. var cosYaw = Math.cos(halfYaw);
  2857. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2858. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2859. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2860. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2861. };
  2862. /**
  2863. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2864. */
  2865. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2866. var result = new Quaternion();
  2867. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2868. return result;
  2869. };
  2870. /**
  2871. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2872. */
  2873. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2874. // Produces a quaternion from Euler angles in the z-x-z orientation
  2875. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2876. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2877. var halfBeta = beta * 0.5;
  2878. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2879. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2880. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2881. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2882. };
  2883. /**
  2884. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2885. * cf to Vector3.RotationFromAxis() documentation.
  2886. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2887. */
  2888. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2889. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2890. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2891. return quat;
  2892. };
  2893. /**
  2894. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2895. * cf to Vector3.RotationFromAxis() documentation.
  2896. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2897. */
  2898. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2899. var rotMat = MathTmp.Matrix[0];
  2900. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2901. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2902. };
  2903. Quaternion.Slerp = function (left, right, amount) {
  2904. var result = Quaternion.Identity();
  2905. Quaternion.SlerpToRef(left, right, amount, result);
  2906. return result;
  2907. };
  2908. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2909. var num2;
  2910. var num3;
  2911. var num = amount;
  2912. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2913. var flag = false;
  2914. if (num4 < 0) {
  2915. flag = true;
  2916. num4 = -num4;
  2917. }
  2918. if (num4 > 0.999999) {
  2919. num3 = 1 - num;
  2920. num2 = flag ? -num : num;
  2921. }
  2922. else {
  2923. var num5 = Math.acos(num4);
  2924. var num6 = (1.0 / Math.sin(num5));
  2925. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2926. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2927. }
  2928. result.x = (num3 * left.x) + (num2 * right.x);
  2929. result.y = (num3 * left.y) + (num2 * right.y);
  2930. result.z = (num3 * left.z) + (num2 * right.z);
  2931. result.w = (num3 * left.w) + (num2 * right.w);
  2932. };
  2933. /**
  2934. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2935. */
  2936. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2937. var squared = amount * amount;
  2938. var cubed = amount * squared;
  2939. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2940. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2941. var part3 = (cubed - (2.0 * squared)) + amount;
  2942. var part4 = cubed - squared;
  2943. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2944. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2945. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2946. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2947. return new Quaternion(x, y, z, w);
  2948. };
  2949. return Quaternion;
  2950. }());
  2951. BABYLON.Quaternion = Quaternion;
  2952. var Matrix = /** @class */ (function () {
  2953. function Matrix() {
  2954. this._isIdentity = false;
  2955. this._isIdentityDirty = true;
  2956. this.m = new Float32Array(16);
  2957. this._markAsUpdated();
  2958. }
  2959. Matrix.prototype._markAsUpdated = function () {
  2960. this.updateFlag = Matrix._updateFlagSeed++;
  2961. this._isIdentityDirty = true;
  2962. };
  2963. // Properties
  2964. /**
  2965. * Boolean : True is the matrix is the identity matrix
  2966. */
  2967. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2968. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2969. if (this._isIdentityDirty) {
  2970. this._isIdentityDirty = false;
  2971. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2972. this._isIdentity = false;
  2973. }
  2974. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2975. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2976. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2977. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2978. this._isIdentity = false;
  2979. }
  2980. else {
  2981. this._isIdentity = true;
  2982. }
  2983. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2984. this._isIdentity = false;
  2985. }
  2986. }
  2987. return this._isIdentity;
  2988. };
  2989. /**
  2990. * Returns the matrix determinant (float).
  2991. */
  2992. Matrix.prototype.determinant = function () {
  2993. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2994. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2995. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2996. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2997. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2998. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2999. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3000. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3001. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3002. };
  3003. // Methods
  3004. /**
  3005. * Returns the matrix underlying array.
  3006. */
  3007. Matrix.prototype.toArray = function () {
  3008. return this.m;
  3009. };
  3010. /**
  3011. * Returns the matrix underlying array.
  3012. */
  3013. Matrix.prototype.asArray = function () {
  3014. return this.toArray();
  3015. };
  3016. /**
  3017. * Inverts in place the Matrix.
  3018. * Returns the Matrix inverted.
  3019. */
  3020. Matrix.prototype.invert = function () {
  3021. this.invertToRef(this);
  3022. return this;
  3023. };
  3024. /**
  3025. * Sets all the matrix elements to zero.
  3026. * Returns the Matrix.
  3027. */
  3028. Matrix.prototype.reset = function () {
  3029. for (var index = 0; index < 16; index++) {
  3030. this.m[index] = 0.0;
  3031. }
  3032. this._markAsUpdated();
  3033. return this;
  3034. };
  3035. /**
  3036. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3037. */
  3038. Matrix.prototype.add = function (other) {
  3039. var result = new Matrix();
  3040. this.addToRef(other, result);
  3041. return result;
  3042. };
  3043. /**
  3044. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3045. * Returns the Matrix.
  3046. */
  3047. Matrix.prototype.addToRef = function (other, result) {
  3048. for (var index = 0; index < 16; index++) {
  3049. result.m[index] = this.m[index] + other.m[index];
  3050. }
  3051. result._markAsUpdated();
  3052. return this;
  3053. };
  3054. /**
  3055. * Adds in place the passed matrix to the current Matrix.
  3056. * Returns the updated Matrix.
  3057. */
  3058. Matrix.prototype.addToSelf = function (other) {
  3059. for (var index = 0; index < 16; index++) {
  3060. this.m[index] += other.m[index];
  3061. }
  3062. this._markAsUpdated();
  3063. return this;
  3064. };
  3065. /**
  3066. * Sets the passed matrix with the current inverted Matrix.
  3067. * Returns the unmodified current Matrix.
  3068. */
  3069. Matrix.prototype.invertToRef = function (other) {
  3070. var l1 = this.m[0];
  3071. var l2 = this.m[1];
  3072. var l3 = this.m[2];
  3073. var l4 = this.m[3];
  3074. var l5 = this.m[4];
  3075. var l6 = this.m[5];
  3076. var l7 = this.m[6];
  3077. var l8 = this.m[7];
  3078. var l9 = this.m[8];
  3079. var l10 = this.m[9];
  3080. var l11 = this.m[10];
  3081. var l12 = this.m[11];
  3082. var l13 = this.m[12];
  3083. var l14 = this.m[13];
  3084. var l15 = this.m[14];
  3085. var l16 = this.m[15];
  3086. var l17 = (l11 * l16) - (l12 * l15);
  3087. var l18 = (l10 * l16) - (l12 * l14);
  3088. var l19 = (l10 * l15) - (l11 * l14);
  3089. var l20 = (l9 * l16) - (l12 * l13);
  3090. var l21 = (l9 * l15) - (l11 * l13);
  3091. var l22 = (l9 * l14) - (l10 * l13);
  3092. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3093. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3094. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3095. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3096. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3097. var l28 = (l7 * l16) - (l8 * l15);
  3098. var l29 = (l6 * l16) - (l8 * l14);
  3099. var l30 = (l6 * l15) - (l7 * l14);
  3100. var l31 = (l5 * l16) - (l8 * l13);
  3101. var l32 = (l5 * l15) - (l7 * l13);
  3102. var l33 = (l5 * l14) - (l6 * l13);
  3103. var l34 = (l7 * l12) - (l8 * l11);
  3104. var l35 = (l6 * l12) - (l8 * l10);
  3105. var l36 = (l6 * l11) - (l7 * l10);
  3106. var l37 = (l5 * l12) - (l8 * l9);
  3107. var l38 = (l5 * l11) - (l7 * l9);
  3108. var l39 = (l5 * l10) - (l6 * l9);
  3109. other.m[0] = l23 * l27;
  3110. other.m[4] = l24 * l27;
  3111. other.m[8] = l25 * l27;
  3112. other.m[12] = l26 * l27;
  3113. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3114. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3115. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3116. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3117. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3118. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3119. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3120. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3121. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3122. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3123. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3124. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3125. other._markAsUpdated();
  3126. return this;
  3127. };
  3128. /**
  3129. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3130. * Returns the updated Matrix.
  3131. */
  3132. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3133. this.m[12] = x;
  3134. this.m[13] = y;
  3135. this.m[14] = z;
  3136. this._markAsUpdated();
  3137. return this;
  3138. };
  3139. /**
  3140. * Inserts the translation vector in the current Matrix.
  3141. * Returns the updated Matrix.
  3142. */
  3143. Matrix.prototype.setTranslation = function (vector3) {
  3144. this.m[12] = vector3.x;
  3145. this.m[13] = vector3.y;
  3146. this.m[14] = vector3.z;
  3147. this._markAsUpdated();
  3148. return this;
  3149. };
  3150. /**
  3151. * Returns a new Vector3 as the extracted translation from the Matrix.
  3152. */
  3153. Matrix.prototype.getTranslation = function () {
  3154. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3155. };
  3156. /**
  3157. * Fill a Vector3 with the extracted translation from the Matrix.
  3158. */
  3159. Matrix.prototype.getTranslationToRef = function (result) {
  3160. result.x = this.m[12];
  3161. result.y = this.m[13];
  3162. result.z = this.m[14];
  3163. return this;
  3164. };
  3165. /**
  3166. * Remove rotation and scaling part from the Matrix.
  3167. * Returns the updated Matrix.
  3168. */
  3169. Matrix.prototype.removeRotationAndScaling = function () {
  3170. this.setRowFromFloats(0, 1, 0, 0, 0);
  3171. this.setRowFromFloats(1, 0, 1, 0, 0);
  3172. this.setRowFromFloats(2, 0, 0, 1, 0);
  3173. return this;
  3174. };
  3175. /**
  3176. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3177. */
  3178. Matrix.prototype.multiply = function (other) {
  3179. var result = new Matrix();
  3180. this.multiplyToRef(other, result);
  3181. return result;
  3182. };
  3183. /**
  3184. * Updates the current Matrix from the passed one values.
  3185. * Returns the updated Matrix.
  3186. */
  3187. Matrix.prototype.copyFrom = function (other) {
  3188. for (var index = 0; index < 16; index++) {
  3189. this.m[index] = other.m[index];
  3190. }
  3191. this._markAsUpdated();
  3192. return this;
  3193. };
  3194. /**
  3195. * Populates the passed array from the starting index with the Matrix values.
  3196. * Returns the Matrix.
  3197. */
  3198. Matrix.prototype.copyToArray = function (array, offset) {
  3199. if (offset === void 0) { offset = 0; }
  3200. for (var index = 0; index < 16; index++) {
  3201. array[offset + index] = this.m[index];
  3202. }
  3203. return this;
  3204. };
  3205. /**
  3206. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3207. */
  3208. Matrix.prototype.multiplyToRef = function (other, result) {
  3209. this.multiplyToArray(other, result.m, 0);
  3210. result._markAsUpdated();
  3211. return this;
  3212. };
  3213. /**
  3214. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3215. */
  3216. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3217. var tm0 = this.m[0];
  3218. var tm1 = this.m[1];
  3219. var tm2 = this.m[2];
  3220. var tm3 = this.m[3];
  3221. var tm4 = this.m[4];
  3222. var tm5 = this.m[5];
  3223. var tm6 = this.m[6];
  3224. var tm7 = this.m[7];
  3225. var tm8 = this.m[8];
  3226. var tm9 = this.m[9];
  3227. var tm10 = this.m[10];
  3228. var tm11 = this.m[11];
  3229. var tm12 = this.m[12];
  3230. var tm13 = this.m[13];
  3231. var tm14 = this.m[14];
  3232. var tm15 = this.m[15];
  3233. var om0 = other.m[0];
  3234. var om1 = other.m[1];
  3235. var om2 = other.m[2];
  3236. var om3 = other.m[3];
  3237. var om4 = other.m[4];
  3238. var om5 = other.m[5];
  3239. var om6 = other.m[6];
  3240. var om7 = other.m[7];
  3241. var om8 = other.m[8];
  3242. var om9 = other.m[9];
  3243. var om10 = other.m[10];
  3244. var om11 = other.m[11];
  3245. var om12 = other.m[12];
  3246. var om13 = other.m[13];
  3247. var om14 = other.m[14];
  3248. var om15 = other.m[15];
  3249. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3250. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3251. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3252. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3253. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3254. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3255. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3256. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3257. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3258. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3259. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3260. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3261. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3262. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3263. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3264. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3265. return this;
  3266. };
  3267. /**
  3268. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3269. */
  3270. Matrix.prototype.equals = function (value) {
  3271. return value &&
  3272. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3273. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3274. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3275. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3276. };
  3277. /**
  3278. * Returns a new Matrix from the current Matrix.
  3279. */
  3280. Matrix.prototype.clone = function () {
  3281. 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]);
  3282. };
  3283. /**
  3284. * Returns the string "Matrix"
  3285. */
  3286. Matrix.prototype.getClassName = function () {
  3287. return "Matrix";
  3288. };
  3289. /**
  3290. * Returns the Matrix hash code.
  3291. */
  3292. Matrix.prototype.getHashCode = function () {
  3293. var hash = this.m[0] || 0;
  3294. for (var i = 1; i < 16; i++) {
  3295. hash = (hash * 397) ^ (this.m[i] || 0);
  3296. }
  3297. return hash;
  3298. };
  3299. /**
  3300. * Decomposes the current Matrix into :
  3301. * - a scale vector3 passed as a reference to update,
  3302. * - a rotation quaternion passed as a reference to update,
  3303. * - a translation vector3 passed as a reference to update.
  3304. * Returns the boolean `true`.
  3305. */
  3306. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3307. translation.x = this.m[12];
  3308. translation.y = this.m[13];
  3309. translation.z = this.m[14];
  3310. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3311. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3312. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3313. if (this.determinant() <= 0) {
  3314. scale.y *= -1;
  3315. }
  3316. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3317. rotation.x = 0;
  3318. rotation.y = 0;
  3319. rotation.z = 0;
  3320. rotation.w = 1;
  3321. return false;
  3322. }
  3323. 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]);
  3324. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3325. return true;
  3326. };
  3327. /**
  3328. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3329. */
  3330. Matrix.prototype.getRotationMatrix = function () {
  3331. var result = Matrix.Identity();
  3332. this.getRotationMatrixToRef(result);
  3333. return result;
  3334. };
  3335. /**
  3336. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3337. * Returns the current Matrix.
  3338. */
  3339. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3340. var m = this.m;
  3341. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3342. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3343. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3344. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3345. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3346. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3347. 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);
  3348. return this;
  3349. };
  3350. // Statics
  3351. /**
  3352. * Returns a new Matrix set from the starting index of the passed array.
  3353. */
  3354. Matrix.FromArray = function (array, offset) {
  3355. var result = new Matrix();
  3356. if (!offset) {
  3357. offset = 0;
  3358. }
  3359. Matrix.FromArrayToRef(array, offset, result);
  3360. return result;
  3361. };
  3362. /**
  3363. * Sets the passed "result" matrix from the starting index of the passed array.
  3364. */
  3365. Matrix.FromArrayToRef = function (array, offset, result) {
  3366. for (var index = 0; index < 16; index++) {
  3367. result.m[index] = array[index + offset];
  3368. }
  3369. result._markAsUpdated();
  3370. };
  3371. /**
  3372. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3373. */
  3374. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3375. for (var index = 0; index < 16; index++) {
  3376. result.m[index] = array[index + offset] * scale;
  3377. }
  3378. result._markAsUpdated();
  3379. };
  3380. /**
  3381. * Sets the passed matrix "result" with the 16 passed floats.
  3382. */
  3383. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3384. result.m[0] = initialM11;
  3385. result.m[1] = initialM12;
  3386. result.m[2] = initialM13;
  3387. result.m[3] = initialM14;
  3388. result.m[4] = initialM21;
  3389. result.m[5] = initialM22;
  3390. result.m[6] = initialM23;
  3391. result.m[7] = initialM24;
  3392. result.m[8] = initialM31;
  3393. result.m[9] = initialM32;
  3394. result.m[10] = initialM33;
  3395. result.m[11] = initialM34;
  3396. result.m[12] = initialM41;
  3397. result.m[13] = initialM42;
  3398. result.m[14] = initialM43;
  3399. result.m[15] = initialM44;
  3400. result._markAsUpdated();
  3401. };
  3402. /**
  3403. * Returns the index-th row of the current matrix as a new Vector4.
  3404. */
  3405. Matrix.prototype.getRow = function (index) {
  3406. if (index < 0 || index > 3) {
  3407. return null;
  3408. }
  3409. var i = index * 4;
  3410. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3411. };
  3412. /**
  3413. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3414. * Returns the updated Matrix.
  3415. */
  3416. Matrix.prototype.setRow = function (index, row) {
  3417. if (index < 0 || index > 3) {
  3418. return this;
  3419. }
  3420. var i = index * 4;
  3421. this.m[i + 0] = row.x;
  3422. this.m[i + 1] = row.y;
  3423. this.m[i + 2] = row.z;
  3424. this.m[i + 3] = row.w;
  3425. this._markAsUpdated();
  3426. return this;
  3427. };
  3428. /**
  3429. * Compute the transpose of the matrix.
  3430. * Returns a new Matrix.
  3431. */
  3432. Matrix.prototype.transpose = function () {
  3433. return Matrix.Transpose(this);
  3434. };
  3435. /**
  3436. * Compute the transpose of the matrix.
  3437. * Returns the current matrix.
  3438. */
  3439. Matrix.prototype.transposeToRef = function (result) {
  3440. Matrix.TransposeToRef(this, result);
  3441. return this;
  3442. };
  3443. /**
  3444. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3445. * Returns the updated Matrix.
  3446. */
  3447. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3448. if (index < 0 || index > 3) {
  3449. return this;
  3450. }
  3451. var i = index * 4;
  3452. this.m[i + 0] = x;
  3453. this.m[i + 1] = y;
  3454. this.m[i + 2] = z;
  3455. this.m[i + 3] = w;
  3456. this._markAsUpdated();
  3457. return this;
  3458. };
  3459. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3460. /**
  3461. * Static identity matrix to be used as readonly matrix
  3462. * Must not be updated.
  3463. */
  3464. get: function () {
  3465. return Matrix._identityReadOnly;
  3466. },
  3467. enumerable: true,
  3468. configurable: true
  3469. });
  3470. /**
  3471. * Returns a new Matrix set from the 16 passed floats.
  3472. */
  3473. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3474. var result = new Matrix();
  3475. result.m[0] = initialM11;
  3476. result.m[1] = initialM12;
  3477. result.m[2] = initialM13;
  3478. result.m[3] = initialM14;
  3479. result.m[4] = initialM21;
  3480. result.m[5] = initialM22;
  3481. result.m[6] = initialM23;
  3482. result.m[7] = initialM24;
  3483. result.m[8] = initialM31;
  3484. result.m[9] = initialM32;
  3485. result.m[10] = initialM33;
  3486. result.m[11] = initialM34;
  3487. result.m[12] = initialM41;
  3488. result.m[13] = initialM42;
  3489. result.m[14] = initialM43;
  3490. result.m[15] = initialM44;
  3491. return result;
  3492. };
  3493. /**
  3494. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3495. */
  3496. Matrix.Compose = function (scale, rotation, translation) {
  3497. var result = Matrix.Identity();
  3498. Matrix.ComposeToRef(scale, rotation, translation, result);
  3499. return result;
  3500. };
  3501. /**
  3502. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3503. */
  3504. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3505. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3506. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3507. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3508. result.setTranslation(translation);
  3509. };
  3510. /**
  3511. * Returns a new indentity Matrix.
  3512. */
  3513. Matrix.Identity = function () {
  3514. 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);
  3515. };
  3516. /**
  3517. * Sets the passed "result" as an identity matrix.
  3518. */
  3519. Matrix.IdentityToRef = function (result) {
  3520. 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);
  3521. };
  3522. /**
  3523. * Returns a new zero Matrix.
  3524. */
  3525. Matrix.Zero = function () {
  3526. 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);
  3527. };
  3528. /**
  3529. * Returns a new rotation matrix for "angle" radians around the X axis.
  3530. */
  3531. Matrix.RotationX = function (angle) {
  3532. var result = new Matrix();
  3533. Matrix.RotationXToRef(angle, result);
  3534. return result;
  3535. };
  3536. /**
  3537. * Returns a new Matrix as the passed inverted one.
  3538. */
  3539. Matrix.Invert = function (source) {
  3540. var result = new Matrix();
  3541. source.invertToRef(result);
  3542. return result;
  3543. };
  3544. /**
  3545. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3546. */
  3547. Matrix.RotationXToRef = function (angle, result) {
  3548. var s = Math.sin(angle);
  3549. var c = Math.cos(angle);
  3550. result.m[0] = 1.0;
  3551. result.m[15] = 1.0;
  3552. result.m[5] = c;
  3553. result.m[10] = c;
  3554. result.m[9] = -s;
  3555. result.m[6] = s;
  3556. result.m[1] = 0.0;
  3557. result.m[2] = 0.0;
  3558. result.m[3] = 0.0;
  3559. result.m[4] = 0.0;
  3560. result.m[7] = 0.0;
  3561. result.m[8] = 0.0;
  3562. result.m[11] = 0.0;
  3563. result.m[12] = 0.0;
  3564. result.m[13] = 0.0;
  3565. result.m[14] = 0.0;
  3566. result._markAsUpdated();
  3567. };
  3568. /**
  3569. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3570. */
  3571. Matrix.RotationY = function (angle) {
  3572. var result = new Matrix();
  3573. Matrix.RotationYToRef(angle, result);
  3574. return result;
  3575. };
  3576. /**
  3577. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3578. */
  3579. Matrix.RotationYToRef = function (angle, result) {
  3580. var s = Math.sin(angle);
  3581. var c = Math.cos(angle);
  3582. result.m[5] = 1.0;
  3583. result.m[15] = 1.0;
  3584. result.m[0] = c;
  3585. result.m[2] = -s;
  3586. result.m[8] = s;
  3587. result.m[10] = c;
  3588. result.m[1] = 0.0;
  3589. result.m[3] = 0.0;
  3590. result.m[4] = 0.0;
  3591. result.m[6] = 0.0;
  3592. result.m[7] = 0.0;
  3593. result.m[9] = 0.0;
  3594. result.m[11] = 0.0;
  3595. result.m[12] = 0.0;
  3596. result.m[13] = 0.0;
  3597. result.m[14] = 0.0;
  3598. result._markAsUpdated();
  3599. };
  3600. /**
  3601. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3602. */
  3603. Matrix.RotationZ = function (angle) {
  3604. var result = new Matrix();
  3605. Matrix.RotationZToRef(angle, result);
  3606. return result;
  3607. };
  3608. /**
  3609. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3610. */
  3611. Matrix.RotationZToRef = function (angle, result) {
  3612. var s = Math.sin(angle);
  3613. var c = Math.cos(angle);
  3614. result.m[10] = 1.0;
  3615. result.m[15] = 1.0;
  3616. result.m[0] = c;
  3617. result.m[1] = s;
  3618. result.m[4] = -s;
  3619. result.m[5] = c;
  3620. result.m[2] = 0.0;
  3621. result.m[3] = 0.0;
  3622. result.m[6] = 0.0;
  3623. result.m[7] = 0.0;
  3624. result.m[8] = 0.0;
  3625. result.m[9] = 0.0;
  3626. result.m[11] = 0.0;
  3627. result.m[12] = 0.0;
  3628. result.m[13] = 0.0;
  3629. result.m[14] = 0.0;
  3630. result._markAsUpdated();
  3631. };
  3632. /**
  3633. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3634. */
  3635. Matrix.RotationAxis = function (axis, angle) {
  3636. var result = Matrix.Zero();
  3637. Matrix.RotationAxisToRef(axis, angle, result);
  3638. return result;
  3639. };
  3640. /**
  3641. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3642. */
  3643. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3644. var s = Math.sin(-angle);
  3645. var c = Math.cos(-angle);
  3646. var c1 = 1 - c;
  3647. axis.normalize();
  3648. result.m[0] = (axis.x * axis.x) * c1 + c;
  3649. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3650. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3651. result.m[3] = 0.0;
  3652. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3653. result.m[5] = (axis.y * axis.y) * c1 + c;
  3654. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3655. result.m[7] = 0.0;
  3656. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3657. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3658. result.m[10] = (axis.z * axis.z) * c1 + c;
  3659. result.m[11] = 0.0;
  3660. result.m[15] = 1.0;
  3661. result._markAsUpdated();
  3662. };
  3663. /**
  3664. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3665. */
  3666. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3667. var result = new Matrix();
  3668. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3669. return result;
  3670. };
  3671. /**
  3672. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3673. */
  3674. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3675. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3676. this._tempQuaternion.toRotationMatrix(result);
  3677. };
  3678. /**
  3679. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3680. */
  3681. Matrix.Scaling = function (x, y, z) {
  3682. var result = Matrix.Zero();
  3683. Matrix.ScalingToRef(x, y, z, result);
  3684. return result;
  3685. };
  3686. /**
  3687. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3688. */
  3689. Matrix.ScalingToRef = function (x, y, z, result) {
  3690. result.m[0] = x;
  3691. result.m[1] = 0.0;
  3692. result.m[2] = 0.0;
  3693. result.m[3] = 0.0;
  3694. result.m[4] = 0.0;
  3695. result.m[5] = y;
  3696. result.m[6] = 0.0;
  3697. result.m[7] = 0.0;
  3698. result.m[8] = 0.0;
  3699. result.m[9] = 0.0;
  3700. result.m[10] = z;
  3701. result.m[11] = 0.0;
  3702. result.m[12] = 0.0;
  3703. result.m[13] = 0.0;
  3704. result.m[14] = 0.0;
  3705. result.m[15] = 1.0;
  3706. result._markAsUpdated();
  3707. };
  3708. /**
  3709. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3710. */
  3711. Matrix.Translation = function (x, y, z) {
  3712. var result = Matrix.Identity();
  3713. Matrix.TranslationToRef(x, y, z, result);
  3714. return result;
  3715. };
  3716. /**
  3717. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3718. */
  3719. Matrix.TranslationToRef = function (x, y, z, result) {
  3720. 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);
  3721. };
  3722. /**
  3723. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3724. */
  3725. Matrix.Lerp = function (startValue, endValue, gradient) {
  3726. var result = Matrix.Zero();
  3727. for (var index = 0; index < 16; index++) {
  3728. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3729. }
  3730. result._markAsUpdated();
  3731. return result;
  3732. };
  3733. /**
  3734. * Returns a new Matrix whose values are computed by :
  3735. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3736. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3737. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3738. */
  3739. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3740. var startScale = new Vector3(0, 0, 0);
  3741. var startRotation = new Quaternion();
  3742. var startTranslation = new Vector3(0, 0, 0);
  3743. startValue.decompose(startScale, startRotation, startTranslation);
  3744. var endScale = new Vector3(0, 0, 0);
  3745. var endRotation = new Quaternion();
  3746. var endTranslation = new Vector3(0, 0, 0);
  3747. endValue.decompose(endScale, endRotation, endTranslation);
  3748. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3749. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3750. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3751. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3752. };
  3753. /**
  3754. * 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".
  3755. * This methods works for a Left-Handed system.
  3756. */
  3757. Matrix.LookAtLH = function (eye, target, up) {
  3758. var result = Matrix.Zero();
  3759. Matrix.LookAtLHToRef(eye, target, up, result);
  3760. return result;
  3761. };
  3762. /**
  3763. * 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".
  3764. * This methods works for a Left-Handed system.
  3765. */
  3766. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3767. // Z axis
  3768. target.subtractToRef(eye, this._zAxis);
  3769. this._zAxis.normalize();
  3770. // X axis
  3771. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3772. if (this._xAxis.lengthSquared() === 0) {
  3773. this._xAxis.x = 1.0;
  3774. }
  3775. else {
  3776. this._xAxis.normalize();
  3777. }
  3778. // Y axis
  3779. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3780. this._yAxis.normalize();
  3781. // Eye angles
  3782. var ex = -Vector3.Dot(this._xAxis, eye);
  3783. var ey = -Vector3.Dot(this._yAxis, eye);
  3784. var ez = -Vector3.Dot(this._zAxis, eye);
  3785. 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);
  3786. };
  3787. /**
  3788. * 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".
  3789. * This methods works for a Right-Handed system.
  3790. */
  3791. Matrix.LookAtRH = function (eye, target, up) {
  3792. var result = Matrix.Zero();
  3793. Matrix.LookAtRHToRef(eye, target, up, result);
  3794. return result;
  3795. };
  3796. /**
  3797. * 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".
  3798. * This methods works for a Left-Handed system.
  3799. */
  3800. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3801. // Z axis
  3802. eye.subtractToRef(target, this._zAxis);
  3803. this._zAxis.normalize();
  3804. // X axis
  3805. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3806. if (this._xAxis.lengthSquared() === 0) {
  3807. this._xAxis.x = 1.0;
  3808. }
  3809. else {
  3810. this._xAxis.normalize();
  3811. }
  3812. // Y axis
  3813. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3814. this._yAxis.normalize();
  3815. // Eye angles
  3816. var ex = -Vector3.Dot(this._xAxis, eye);
  3817. var ey = -Vector3.Dot(this._yAxis, eye);
  3818. var ez = -Vector3.Dot(this._zAxis, eye);
  3819. 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);
  3820. };
  3821. /**
  3822. * 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.
  3823. */
  3824. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3825. var matrix = Matrix.Zero();
  3826. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3827. return matrix;
  3828. };
  3829. /**
  3830. * 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.
  3831. */
  3832. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3833. var n = znear;
  3834. var f = zfar;
  3835. var a = 2.0 / width;
  3836. var b = 2.0 / height;
  3837. var c = 2.0 / (f - n);
  3838. var d = -(f + n) / (f - n);
  3839. BABYLON.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);
  3840. };
  3841. /**
  3842. * 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.
  3843. */
  3844. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3845. var matrix = Matrix.Zero();
  3846. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3847. return matrix;
  3848. };
  3849. /**
  3850. * 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.
  3851. */
  3852. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3853. var n = znear;
  3854. var f = zfar;
  3855. var a = 2.0 / (right - left);
  3856. var b = 2.0 / (top - bottom);
  3857. var c = 2.0 / (f - n);
  3858. var d = -(f + n) / (f - n);
  3859. var i0 = (left + right) / (left - right);
  3860. var i1 = (top + bottom) / (bottom - top);
  3861. BABYLON.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);
  3862. };
  3863. /**
  3864. * 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.
  3865. */
  3866. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3867. var matrix = Matrix.Zero();
  3868. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3869. return matrix;
  3870. };
  3871. /**
  3872. * 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.
  3873. */
  3874. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3875. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3876. result.m[10] *= -1.0;
  3877. };
  3878. /**
  3879. * 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.
  3880. */
  3881. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3882. var matrix = Matrix.Zero();
  3883. var n = znear;
  3884. var f = zfar;
  3885. var a = 2.0 * n / width;
  3886. var b = 2.0 * n / height;
  3887. var c = (f + n) / (f - n);
  3888. var d = -2.0 * f * n / (f - n);
  3889. BABYLON.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);
  3890. return matrix;
  3891. };
  3892. /**
  3893. * 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.
  3894. */
  3895. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3896. var matrix = Matrix.Zero();
  3897. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3898. return matrix;
  3899. };
  3900. /**
  3901. * 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.
  3902. */
  3903. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3904. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3905. var n = znear;
  3906. var f = zfar;
  3907. var t = 1.0 / (Math.tan(fov * 0.5));
  3908. var a = isVerticalFovFixed ? (t / aspect) : t;
  3909. var b = isVerticalFovFixed ? t : (t * aspect);
  3910. var c = (f + n) / (f - n);
  3911. var d = -2.0 * f * n / (f - n);
  3912. BABYLON.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);
  3913. };
  3914. /**
  3915. * 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.
  3916. */
  3917. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3918. var matrix = Matrix.Zero();
  3919. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3920. return matrix;
  3921. };
  3922. /**
  3923. * 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.
  3924. */
  3925. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3926. //alternatively this could be expressed as:
  3927. // m = PerspectiveFovLHToRef
  3928. // m[10] *= -1.0;
  3929. // m[11] *= -1.0;
  3930. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3931. var n = znear;
  3932. var f = zfar;
  3933. var t = 1.0 / (Math.tan(fov * 0.5));
  3934. var a = isVerticalFovFixed ? (t / aspect) : t;
  3935. var b = isVerticalFovFixed ? t : (t * aspect);
  3936. var c = -(f + n) / (f - n);
  3937. var d = -2 * f * n / (f - n);
  3938. BABYLON.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);
  3939. };
  3940. /**
  3941. * 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.
  3942. */
  3943. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3944. if (rightHanded === void 0) { rightHanded = false; }
  3945. var rightHandedFactor = rightHanded ? -1 : 1;
  3946. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3947. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3948. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3949. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3950. var xScale = 2.0 / (leftTan + rightTan);
  3951. var yScale = 2.0 / (upTan + downTan);
  3952. result.m[0] = xScale;
  3953. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3954. result.m[5] = yScale;
  3955. result.m[6] = result.m[7] = 0.0;
  3956. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3957. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3958. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3959. result.m[10] = -zfar / (znear - zfar);
  3960. result.m[11] = 1.0 * rightHandedFactor;
  3961. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3962. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3963. // result.m[14] = (znear * zfar) / (znear - zfar);
  3964. result._markAsUpdated();
  3965. };
  3966. /**
  3967. * Returns the final transformation matrix : world * view * projection * viewport
  3968. */
  3969. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3970. var cw = viewport.width;
  3971. var ch = viewport.height;
  3972. var cx = viewport.x;
  3973. var cy = viewport.y;
  3974. 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);
  3975. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3976. };
  3977. /**
  3978. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3979. */
  3980. Matrix.GetAsMatrix2x2 = function (matrix) {
  3981. return new Float32Array([
  3982. matrix.m[0], matrix.m[1],
  3983. matrix.m[4], matrix.m[5]
  3984. ]);
  3985. };
  3986. /**
  3987. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3988. */
  3989. Matrix.GetAsMatrix3x3 = function (matrix) {
  3990. return new Float32Array([
  3991. matrix.m[0], matrix.m[1], matrix.m[2],
  3992. matrix.m[4], matrix.m[5], matrix.m[6],
  3993. matrix.m[8], matrix.m[9], matrix.m[10]
  3994. ]);
  3995. };
  3996. /**
  3997. * Compute the transpose of the passed Matrix.
  3998. * Returns a new Matrix.
  3999. */
  4000. Matrix.Transpose = function (matrix) {
  4001. var result = new Matrix();
  4002. Matrix.TransposeToRef(matrix, result);
  4003. return result;
  4004. };
  4005. /**
  4006. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4007. */
  4008. Matrix.TransposeToRef = function (matrix, result) {
  4009. result.m[0] = matrix.m[0];
  4010. result.m[1] = matrix.m[4];
  4011. result.m[2] = matrix.m[8];
  4012. result.m[3] = matrix.m[12];
  4013. result.m[4] = matrix.m[1];
  4014. result.m[5] = matrix.m[5];
  4015. result.m[6] = matrix.m[9];
  4016. result.m[7] = matrix.m[13];
  4017. result.m[8] = matrix.m[2];
  4018. result.m[9] = matrix.m[6];
  4019. result.m[10] = matrix.m[10];
  4020. result.m[11] = matrix.m[14];
  4021. result.m[12] = matrix.m[3];
  4022. result.m[13] = matrix.m[7];
  4023. result.m[14] = matrix.m[11];
  4024. result.m[15] = matrix.m[15];
  4025. };
  4026. /**
  4027. * Returns a new Matrix as the reflection matrix across the passed plane.
  4028. */
  4029. Matrix.Reflection = function (plane) {
  4030. var matrix = new Matrix();
  4031. Matrix.ReflectionToRef(plane, matrix);
  4032. return matrix;
  4033. };
  4034. /**
  4035. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4036. */
  4037. Matrix.ReflectionToRef = function (plane, result) {
  4038. plane.normalize();
  4039. var x = plane.normal.x;
  4040. var y = plane.normal.y;
  4041. var z = plane.normal.z;
  4042. var temp = -2 * x;
  4043. var temp2 = -2 * y;
  4044. var temp3 = -2 * z;
  4045. result.m[0] = (temp * x) + 1;
  4046. result.m[1] = temp2 * x;
  4047. result.m[2] = temp3 * x;
  4048. result.m[3] = 0.0;
  4049. result.m[4] = temp * y;
  4050. result.m[5] = (temp2 * y) + 1;
  4051. result.m[6] = temp3 * y;
  4052. result.m[7] = 0.0;
  4053. result.m[8] = temp * z;
  4054. result.m[9] = temp2 * z;
  4055. result.m[10] = (temp3 * z) + 1;
  4056. result.m[11] = 0.0;
  4057. result.m[12] = temp * plane.d;
  4058. result.m[13] = temp2 * plane.d;
  4059. result.m[14] = temp3 * plane.d;
  4060. result.m[15] = 1.0;
  4061. result._markAsUpdated();
  4062. };
  4063. /**
  4064. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4065. */
  4066. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4067. result.m[0] = xaxis.x;
  4068. result.m[1] = xaxis.y;
  4069. result.m[2] = xaxis.z;
  4070. result.m[3] = 0.0;
  4071. result.m[4] = yaxis.x;
  4072. result.m[5] = yaxis.y;
  4073. result.m[6] = yaxis.z;
  4074. result.m[7] = 0.0;
  4075. result.m[8] = zaxis.x;
  4076. result.m[9] = zaxis.y;
  4077. result.m[10] = zaxis.z;
  4078. result.m[11] = 0.0;
  4079. result.m[12] = 0.0;
  4080. result.m[13] = 0.0;
  4081. result.m[14] = 0.0;
  4082. result.m[15] = 1.0;
  4083. result._markAsUpdated();
  4084. };
  4085. /**
  4086. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4087. */
  4088. Matrix.FromQuaternionToRef = function (quat, result) {
  4089. var xx = quat.x * quat.x;
  4090. var yy = quat.y * quat.y;
  4091. var zz = quat.z * quat.z;
  4092. var xy = quat.x * quat.y;
  4093. var zw = quat.z * quat.w;
  4094. var zx = quat.z * quat.x;
  4095. var yw = quat.y * quat.w;
  4096. var yz = quat.y * quat.z;
  4097. var xw = quat.x * quat.w;
  4098. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4099. result.m[1] = 2.0 * (xy + zw);
  4100. result.m[2] = 2.0 * (zx - yw);
  4101. result.m[3] = 0.0;
  4102. result.m[4] = 2.0 * (xy - zw);
  4103. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4104. result.m[6] = 2.0 * (yz + xw);
  4105. result.m[7] = 0.0;
  4106. result.m[8] = 2.0 * (zx + yw);
  4107. result.m[9] = 2.0 * (yz - xw);
  4108. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4109. result.m[11] = 0.0;
  4110. result.m[12] = 0.0;
  4111. result.m[13] = 0.0;
  4112. result.m[14] = 0.0;
  4113. result.m[15] = 1.0;
  4114. result._markAsUpdated();
  4115. };
  4116. Matrix._tempQuaternion = new Quaternion();
  4117. Matrix._xAxis = Vector3.Zero();
  4118. Matrix._yAxis = Vector3.Zero();
  4119. Matrix._zAxis = Vector3.Zero();
  4120. Matrix._updateFlagSeed = 0;
  4121. Matrix._identityReadOnly = Matrix.Identity();
  4122. return Matrix;
  4123. }());
  4124. BABYLON.Matrix = Matrix;
  4125. var Plane = /** @class */ (function () {
  4126. /**
  4127. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4128. */
  4129. function Plane(a, b, c, d) {
  4130. this.normal = new Vector3(a, b, c);
  4131. this.d = d;
  4132. }
  4133. /**
  4134. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4135. */
  4136. Plane.prototype.asArray = function () {
  4137. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4138. };
  4139. // Methods
  4140. /**
  4141. * Returns a new plane copied from the current Plane.
  4142. */
  4143. Plane.prototype.clone = function () {
  4144. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4145. };
  4146. /**
  4147. * Returns the string "Plane".
  4148. */
  4149. Plane.prototype.getClassName = function () {
  4150. return "Plane";
  4151. };
  4152. /**
  4153. * Returns the Plane hash code.
  4154. */
  4155. Plane.prototype.getHashCode = function () {
  4156. var hash = this.normal.getHashCode();
  4157. hash = (hash * 397) ^ (this.d || 0);
  4158. return hash;
  4159. };
  4160. /**
  4161. * Normalize the current Plane in place.
  4162. * Returns the updated Plane.
  4163. */
  4164. Plane.prototype.normalize = function () {
  4165. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4166. var magnitude = 0.0;
  4167. if (norm !== 0) {
  4168. magnitude = 1.0 / norm;
  4169. }
  4170. this.normal.x *= magnitude;
  4171. this.normal.y *= magnitude;
  4172. this.normal.z *= magnitude;
  4173. this.d *= magnitude;
  4174. return this;
  4175. };
  4176. /**
  4177. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4178. */
  4179. Plane.prototype.transform = function (transformation) {
  4180. var transposedMatrix = Matrix.Transpose(transformation);
  4181. var x = this.normal.x;
  4182. var y = this.normal.y;
  4183. var z = this.normal.z;
  4184. var d = this.d;
  4185. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4186. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4187. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4188. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4189. return new Plane(normalX, normalY, normalZ, finalD);
  4190. };
  4191. /**
  4192. * Returns the dot product (float) of the point coordinates and the plane normal.
  4193. */
  4194. Plane.prototype.dotCoordinate = function (point) {
  4195. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4196. };
  4197. /**
  4198. * Updates the current Plane from the plane defined by the three passed points.
  4199. * Returns the updated Plane.
  4200. */
  4201. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4202. var x1 = point2.x - point1.x;
  4203. var y1 = point2.y - point1.y;
  4204. var z1 = point2.z - point1.z;
  4205. var x2 = point3.x - point1.x;
  4206. var y2 = point3.y - point1.y;
  4207. var z2 = point3.z - point1.z;
  4208. var yz = (y1 * z2) - (z1 * y2);
  4209. var xz = (z1 * x2) - (x1 * z2);
  4210. var xy = (x1 * y2) - (y1 * x2);
  4211. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4212. var invPyth;
  4213. if (pyth !== 0) {
  4214. invPyth = 1.0 / pyth;
  4215. }
  4216. else {
  4217. invPyth = 0.0;
  4218. }
  4219. this.normal.x = yz * invPyth;
  4220. this.normal.y = xz * invPyth;
  4221. this.normal.z = xy * invPyth;
  4222. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4223. return this;
  4224. };
  4225. /**
  4226. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4227. */
  4228. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4229. var dot = Vector3.Dot(this.normal, direction);
  4230. return (dot <= epsilon);
  4231. };
  4232. /**
  4233. * Returns the signed distance (float) from the passed point to the Plane.
  4234. */
  4235. Plane.prototype.signedDistanceTo = function (point) {
  4236. return Vector3.Dot(point, this.normal) + this.d;
  4237. };
  4238. // Statics
  4239. /**
  4240. * Returns a new Plane from the passed array.
  4241. */
  4242. Plane.FromArray = function (array) {
  4243. return new Plane(array[0], array[1], array[2], array[3]);
  4244. };
  4245. /**
  4246. * Returns a new Plane defined by the three passed points.
  4247. */
  4248. Plane.FromPoints = function (point1, point2, point3) {
  4249. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4250. result.copyFromPoints(point1, point2, point3);
  4251. return result;
  4252. };
  4253. /**
  4254. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4255. * Note : the vector "normal" is updated because normalized.
  4256. */
  4257. Plane.FromPositionAndNormal = function (origin, normal) {
  4258. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4259. normal.normalize();
  4260. result.normal = normal;
  4261. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4262. return result;
  4263. };
  4264. /**
  4265. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4266. */
  4267. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4268. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4269. return Vector3.Dot(point, normal) + d;
  4270. };
  4271. return Plane;
  4272. }());
  4273. BABYLON.Plane = Plane;
  4274. var Viewport = /** @class */ (function () {
  4275. /**
  4276. * Creates a Viewport object located at (x, y) and sized (width, height).
  4277. */
  4278. function Viewport(x, y, width, height) {
  4279. this.x = x;
  4280. this.y = y;
  4281. this.width = width;
  4282. this.height = height;
  4283. }
  4284. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4285. if (renderWidthOrEngine.getRenderWidth) {
  4286. var engine = renderWidthOrEngine;
  4287. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4288. }
  4289. var renderWidth = renderWidthOrEngine;
  4290. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4291. };
  4292. /**
  4293. * Returns a new Viewport copied from the current one.
  4294. */
  4295. Viewport.prototype.clone = function () {
  4296. return new Viewport(this.x, this.y, this.width, this.height);
  4297. };
  4298. return Viewport;
  4299. }());
  4300. BABYLON.Viewport = Viewport;
  4301. var Frustum = /** @class */ (function () {
  4302. function Frustum() {
  4303. }
  4304. /**
  4305. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4306. */
  4307. Frustum.GetPlanes = function (transform) {
  4308. var frustumPlanes = [];
  4309. for (var index = 0; index < 6; index++) {
  4310. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4311. }
  4312. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4313. return frustumPlanes;
  4314. };
  4315. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4316. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4317. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4318. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4319. frustumPlane.d = transform.m[15] + transform.m[14];
  4320. frustumPlane.normalize();
  4321. };
  4322. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4323. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4324. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4325. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4326. frustumPlane.d = transform.m[15] - transform.m[14];
  4327. frustumPlane.normalize();
  4328. };
  4329. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4330. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4331. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4332. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4333. frustumPlane.d = transform.m[15] + transform.m[12];
  4334. frustumPlane.normalize();
  4335. };
  4336. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4337. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4338. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4339. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4340. frustumPlane.d = transform.m[15] - transform.m[12];
  4341. frustumPlane.normalize();
  4342. };
  4343. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4344. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4345. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4346. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4347. frustumPlane.d = transform.m[15] - transform.m[13];
  4348. frustumPlane.normalize();
  4349. };
  4350. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4351. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4352. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4353. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4354. frustumPlane.d = transform.m[15] + transform.m[13];
  4355. frustumPlane.normalize();
  4356. };
  4357. /**
  4358. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4359. */
  4360. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4361. // Near
  4362. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4363. // Far
  4364. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4365. // Left
  4366. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4367. // Right
  4368. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4369. // Top
  4370. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4371. // Bottom
  4372. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4373. };
  4374. return Frustum;
  4375. }());
  4376. BABYLON.Frustum = Frustum;
  4377. var Space;
  4378. (function (Space) {
  4379. Space[Space["LOCAL"] = 0] = "LOCAL";
  4380. Space[Space["WORLD"] = 1] = "WORLD";
  4381. Space[Space["BONE"] = 2] = "BONE";
  4382. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4383. var Axis = /** @class */ (function () {
  4384. function Axis() {
  4385. }
  4386. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4387. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4388. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4389. return Axis;
  4390. }());
  4391. BABYLON.Axis = Axis;
  4392. ;
  4393. var BezierCurve = /** @class */ (function () {
  4394. function BezierCurve() {
  4395. }
  4396. /**
  4397. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4398. */
  4399. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4400. // Extract X (which is equal to time here)
  4401. var f0 = 1 - 3 * x2 + 3 * x1;
  4402. var f1 = 3 * x2 - 6 * x1;
  4403. var f2 = 3 * x1;
  4404. var refinedT = t;
  4405. for (var i = 0; i < 5; i++) {
  4406. var refinedT2 = refinedT * refinedT;
  4407. var refinedT3 = refinedT2 * refinedT;
  4408. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4409. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4410. refinedT -= (x - t) * slope;
  4411. refinedT = Math.min(1, Math.max(0, refinedT));
  4412. }
  4413. // Resolve cubic bezier for the given x
  4414. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4415. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4416. Math.pow(refinedT, 3);
  4417. };
  4418. return BezierCurve;
  4419. }());
  4420. BABYLON.BezierCurve = BezierCurve;
  4421. var Orientation;
  4422. (function (Orientation) {
  4423. Orientation[Orientation["CW"] = 0] = "CW";
  4424. Orientation[Orientation["CCW"] = 1] = "CCW";
  4425. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4426. var Angle = /** @class */ (function () {
  4427. /**
  4428. * Creates an Angle object of "radians" radians (float).
  4429. */
  4430. function Angle(radians) {
  4431. var _this = this;
  4432. /**
  4433. * Returns the Angle value in degrees (float).
  4434. */
  4435. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4436. /**
  4437. * Returns the Angle value in radians (float).
  4438. */
  4439. this.radians = function () { return _this._radians; };
  4440. this._radians = radians;
  4441. if (this._radians < 0.0)
  4442. this._radians += (2.0 * Math.PI);
  4443. }
  4444. /**
  4445. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4446. */
  4447. Angle.BetweenTwoPoints = function (a, b) {
  4448. var delta = b.subtract(a);
  4449. var theta = Math.atan2(delta.y, delta.x);
  4450. return new Angle(theta);
  4451. };
  4452. /**
  4453. * Returns a new Angle object from the passed float in radians.
  4454. */
  4455. Angle.FromRadians = function (radians) {
  4456. return new Angle(radians);
  4457. };
  4458. /**
  4459. * Returns a new Angle object from the passed float in degrees.
  4460. */
  4461. Angle.FromDegrees = function (degrees) {
  4462. return new Angle(degrees * Math.PI / 180.0);
  4463. };
  4464. return Angle;
  4465. }());
  4466. BABYLON.Angle = Angle;
  4467. var Arc2 = /** @class */ (function () {
  4468. /**
  4469. * Creates an Arc object from the three passed points : start, middle and end.
  4470. */
  4471. function Arc2(startPoint, midPoint, endPoint) {
  4472. this.startPoint = startPoint;
  4473. this.midPoint = midPoint;
  4474. this.endPoint = endPoint;
  4475. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4476. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4477. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4478. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4479. 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);
  4480. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4481. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4482. var a1 = this.startAngle.degrees();
  4483. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4484. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4485. // angles correction
  4486. if (a2 - a1 > +180.0)
  4487. a2 -= 360.0;
  4488. if (a2 - a1 < -180.0)
  4489. a2 += 360.0;
  4490. if (a3 - a2 > +180.0)
  4491. a3 -= 360.0;
  4492. if (a3 - a2 < -180.0)
  4493. a3 += 360.0;
  4494. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4495. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4496. }
  4497. return Arc2;
  4498. }());
  4499. BABYLON.Arc2 = Arc2;
  4500. var Path2 = /** @class */ (function () {
  4501. /**
  4502. * Creates a Path2 object from the starting 2D coordinates x and y.
  4503. */
  4504. function Path2(x, y) {
  4505. this._points = new Array();
  4506. this._length = 0.0;
  4507. this.closed = false;
  4508. this._points.push(new Vector2(x, y));
  4509. }
  4510. /**
  4511. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4512. * Returns the updated Path2.
  4513. */
  4514. Path2.prototype.addLineTo = function (x, y) {
  4515. if (closed) {
  4516. //Tools.Error("cannot add lines to closed paths");
  4517. return this;
  4518. }
  4519. var newPoint = new Vector2(x, y);
  4520. var previousPoint = this._points[this._points.length - 1];
  4521. this._points.push(newPoint);
  4522. this._length += newPoint.subtract(previousPoint).length();
  4523. return this;
  4524. };
  4525. /**
  4526. * 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.
  4527. * Returns the updated Path2.
  4528. */
  4529. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4530. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4531. if (closed) {
  4532. //Tools.Error("cannot add arcs to closed paths");
  4533. return this;
  4534. }
  4535. var startPoint = this._points[this._points.length - 1];
  4536. var midPoint = new Vector2(midX, midY);
  4537. var endPoint = new Vector2(endX, endY);
  4538. var arc = new Arc2(startPoint, midPoint, endPoint);
  4539. var increment = arc.angle.radians() / numberOfSegments;
  4540. if (arc.orientation === Orientation.CW)
  4541. increment *= -1;
  4542. var currentAngle = arc.startAngle.radians() + increment;
  4543. for (var i = 0; i < numberOfSegments; i++) {
  4544. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4545. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4546. this.addLineTo(x, y);
  4547. currentAngle += increment;
  4548. }
  4549. return this;
  4550. };
  4551. /**
  4552. * Closes the Path2.
  4553. * Returns the Path2.
  4554. */
  4555. Path2.prototype.close = function () {
  4556. this.closed = true;
  4557. return this;
  4558. };
  4559. /**
  4560. * Returns the Path2 total length (float).
  4561. */
  4562. Path2.prototype.length = function () {
  4563. var result = this._length;
  4564. if (!this.closed) {
  4565. var lastPoint = this._points[this._points.length - 1];
  4566. var firstPoint = this._points[0];
  4567. result += (firstPoint.subtract(lastPoint).length());
  4568. }
  4569. return result;
  4570. };
  4571. /**
  4572. * Returns the Path2 internal array of points.
  4573. */
  4574. Path2.prototype.getPoints = function () {
  4575. return this._points;
  4576. };
  4577. /**
  4578. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4579. */
  4580. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4581. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4582. //Tools.Error("normalized length position should be between 0 and 1.");
  4583. return Vector2.Zero();
  4584. }
  4585. var lengthPosition = normalizedLengthPosition * this.length();
  4586. var previousOffset = 0;
  4587. for (var i = 0; i < this._points.length; i++) {
  4588. var j = (i + 1) % this._points.length;
  4589. var a = this._points[i];
  4590. var b = this._points[j];
  4591. var bToA = b.subtract(a);
  4592. var nextOffset = (bToA.length() + previousOffset);
  4593. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4594. var dir = bToA.normalize();
  4595. var localOffset = lengthPosition - previousOffset;
  4596. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4597. }
  4598. previousOffset = nextOffset;
  4599. }
  4600. //Tools.Error("internal error");
  4601. return Vector2.Zero();
  4602. };
  4603. /**
  4604. * Returns a new Path2 starting at the coordinates (x, y).
  4605. */
  4606. Path2.StartingAt = function (x, y) {
  4607. return new Path2(x, y);
  4608. };
  4609. return Path2;
  4610. }());
  4611. BABYLON.Path2 = Path2;
  4612. var Path3D = /** @class */ (function () {
  4613. /**
  4614. * new Path3D(path, normal, raw)
  4615. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4616. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4617. * path : an array of Vector3, the curve axis of the Path3D
  4618. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4619. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4620. */
  4621. function Path3D(path, firstNormal, raw) {
  4622. if (firstNormal === void 0) { firstNormal = null; }
  4623. this.path = path;
  4624. this._curve = new Array();
  4625. this._distances = new Array();
  4626. this._tangents = new Array();
  4627. this._normals = new Array();
  4628. this._binormals = new Array();
  4629. for (var p = 0; p < path.length; p++) {
  4630. this._curve[p] = path[p].clone(); // hard copy
  4631. }
  4632. this._raw = raw || false;
  4633. this._compute(firstNormal);
  4634. }
  4635. /**
  4636. * Returns the Path3D array of successive Vector3 designing its curve.
  4637. */
  4638. Path3D.prototype.getCurve = function () {
  4639. return this._curve;
  4640. };
  4641. /**
  4642. * Returns an array populated with tangent vectors on each Path3D curve point.
  4643. */
  4644. Path3D.prototype.getTangents = function () {
  4645. return this._tangents;
  4646. };
  4647. /**
  4648. * Returns an array populated with normal vectors on each Path3D curve point.
  4649. */
  4650. Path3D.prototype.getNormals = function () {
  4651. return this._normals;
  4652. };
  4653. /**
  4654. * Returns an array populated with binormal vectors on each Path3D curve point.
  4655. */
  4656. Path3D.prototype.getBinormals = function () {
  4657. return this._binormals;
  4658. };
  4659. /**
  4660. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4661. */
  4662. Path3D.prototype.getDistances = function () {
  4663. return this._distances;
  4664. };
  4665. /**
  4666. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4667. * Returns the same object updated.
  4668. */
  4669. Path3D.prototype.update = function (path, firstNormal) {
  4670. if (firstNormal === void 0) { firstNormal = null; }
  4671. for (var p = 0; p < path.length; p++) {
  4672. this._curve[p].x = path[p].x;
  4673. this._curve[p].y = path[p].y;
  4674. this._curve[p].z = path[p].z;
  4675. }
  4676. this._compute(firstNormal);
  4677. return this;
  4678. };
  4679. // private function compute() : computes tangents, normals and binormals
  4680. Path3D.prototype._compute = function (firstNormal) {
  4681. var l = this._curve.length;
  4682. // first and last tangents
  4683. this._tangents[0] = this._getFirstNonNullVector(0);
  4684. if (!this._raw) {
  4685. this._tangents[0].normalize();
  4686. }
  4687. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4688. if (!this._raw) {
  4689. this._tangents[l - 1].normalize();
  4690. }
  4691. // normals and binormals at first point : arbitrary vector with _normalVector()
  4692. var tg0 = this._tangents[0];
  4693. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4694. this._normals[0] = pp0;
  4695. if (!this._raw) {
  4696. this._normals[0].normalize();
  4697. }
  4698. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4699. if (!this._raw) {
  4700. this._binormals[0].normalize();
  4701. }
  4702. this._distances[0] = 0.0;
  4703. // normals and binormals : next points
  4704. var prev; // previous vector (segment)
  4705. var cur; // current vector (segment)
  4706. var curTang; // current tangent
  4707. // previous normal
  4708. var prevBinor; // previous binormal
  4709. for (var i = 1; i < l; i++) {
  4710. // tangents
  4711. prev = this._getLastNonNullVector(i);
  4712. if (i < l - 1) {
  4713. cur = this._getFirstNonNullVector(i);
  4714. this._tangents[i] = prev.add(cur);
  4715. this._tangents[i].normalize();
  4716. }
  4717. this._distances[i] = this._distances[i - 1] + prev.length();
  4718. // normals and binormals
  4719. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4720. curTang = this._tangents[i];
  4721. prevBinor = this._binormals[i - 1];
  4722. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4723. if (!this._raw) {
  4724. this._normals[i].normalize();
  4725. }
  4726. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4727. if (!this._raw) {
  4728. this._binormals[i].normalize();
  4729. }
  4730. }
  4731. };
  4732. // private function getFirstNonNullVector(index)
  4733. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4734. Path3D.prototype._getFirstNonNullVector = function (index) {
  4735. var i = 1;
  4736. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4737. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4738. i++;
  4739. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4740. }
  4741. return nNVector;
  4742. };
  4743. // private function getLastNonNullVector(index)
  4744. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4745. Path3D.prototype._getLastNonNullVector = function (index) {
  4746. var i = 1;
  4747. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4748. while (nLVector.length() === 0 && index > i + 1) {
  4749. i++;
  4750. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4751. }
  4752. return nLVector;
  4753. };
  4754. // private function normalVector(v0, vt, va) :
  4755. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4756. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4757. Path3D.prototype._normalVector = function (v0, vt, va) {
  4758. var normal0;
  4759. var tgl = vt.length();
  4760. if (tgl === 0.0) {
  4761. tgl = 1.0;
  4762. }
  4763. if (va === undefined || va === null) {
  4764. var point;
  4765. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4766. point = new Vector3(0.0, -1.0, 0.0);
  4767. }
  4768. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4769. point = new Vector3(1.0, 0.0, 0.0);
  4770. }
  4771. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4772. point = new Vector3(0.0, 0.0, 1.0);
  4773. }
  4774. else {
  4775. point = Vector3.Zero();
  4776. }
  4777. normal0 = Vector3.Cross(vt, point);
  4778. }
  4779. else {
  4780. normal0 = Vector3.Cross(vt, va);
  4781. Vector3.CrossToRef(normal0, vt, normal0);
  4782. }
  4783. normal0.normalize();
  4784. return normal0;
  4785. };
  4786. return Path3D;
  4787. }());
  4788. BABYLON.Path3D = Path3D;
  4789. var Curve3 = /** @class */ (function () {
  4790. /**
  4791. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4792. * A Curve3 is designed from a series of successive Vector3.
  4793. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4794. */
  4795. function Curve3(points) {
  4796. this._length = 0.0;
  4797. this._points = points;
  4798. this._length = this._computeLength(points);
  4799. }
  4800. /**
  4801. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4802. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4803. * @param v1 (Vector3) the control point
  4804. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4805. * @param nbPoints (integer) the wanted number of points in the curve
  4806. */
  4807. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4808. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4809. var bez = new Array();
  4810. var equation = function (t, val0, val1, val2) {
  4811. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4812. return res;
  4813. };
  4814. for (var i = 0; i <= nbPoints; i++) {
  4815. 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)));
  4816. }
  4817. return new Curve3(bez);
  4818. };
  4819. /**
  4820. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4821. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4822. * @param v1 (Vector3) the first control point
  4823. * @param v2 (Vector3) the second control point
  4824. * @param v3 (Vector3) the end point of the Cubic Bezier
  4825. * @param nbPoints (integer) the wanted number of points in the curve
  4826. */
  4827. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4828. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4829. var bez = new Array();
  4830. var equation = function (t, val0, val1, val2, val3) {
  4831. 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;
  4832. return res;
  4833. };
  4834. for (var i = 0; i <= nbPoints; i++) {
  4835. 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)));
  4836. }
  4837. return new Curve3(bez);
  4838. };
  4839. /**
  4840. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4841. * @param p1 (Vector3) the origin point of the Hermite Spline
  4842. * @param t1 (Vector3) the tangent vector at the origin point
  4843. * @param p2 (Vector3) the end point of the Hermite Spline
  4844. * @param t2 (Vector3) the tangent vector at the end point
  4845. * @param nbPoints (integer) the wanted number of points in the curve
  4846. */
  4847. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4848. var hermite = new Array();
  4849. var step = 1.0 / nbPoints;
  4850. for (var i = 0; i <= nbPoints; i++) {
  4851. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4852. }
  4853. return new Curve3(hermite);
  4854. };
  4855. /**
  4856. * Returns a Curve3 object along a CatmullRom Spline curve :
  4857. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4858. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4859. */
  4860. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4861. var totalPoints = new Array();
  4862. totalPoints.push(points[0].clone());
  4863. Array.prototype.push.apply(totalPoints, points);
  4864. totalPoints.push(points[points.length - 1].clone());
  4865. var catmullRom = new Array();
  4866. var step = 1.0 / nbPoints;
  4867. var amount = 0.0;
  4868. for (var i = 0; i < totalPoints.length - 3; i++) {
  4869. amount = 0;
  4870. for (var c = 0; c < nbPoints; c++) {
  4871. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4872. amount += step;
  4873. }
  4874. }
  4875. i--;
  4876. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4877. return new Curve3(catmullRom);
  4878. };
  4879. /**
  4880. * Returns the Curve3 stored array of successive Vector3
  4881. */
  4882. Curve3.prototype.getPoints = function () {
  4883. return this._points;
  4884. };
  4885. /**
  4886. * Returns the computed length (float) of the curve.
  4887. */
  4888. Curve3.prototype.length = function () {
  4889. return this._length;
  4890. };
  4891. /**
  4892. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4893. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4894. * curveA and curveB keep unchanged.
  4895. */
  4896. Curve3.prototype.continue = function (curve) {
  4897. var lastPoint = this._points[this._points.length - 1];
  4898. var continuedPoints = this._points.slice();
  4899. var curvePoints = curve.getPoints();
  4900. for (var i = 1; i < curvePoints.length; i++) {
  4901. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4902. }
  4903. var continuedCurve = new Curve3(continuedPoints);
  4904. return continuedCurve;
  4905. };
  4906. Curve3.prototype._computeLength = function (path) {
  4907. var l = 0;
  4908. for (var i = 1; i < path.length; i++) {
  4909. l += (path[i].subtract(path[i - 1])).length();
  4910. }
  4911. return l;
  4912. };
  4913. return Curve3;
  4914. }());
  4915. BABYLON.Curve3 = Curve3;
  4916. // Vertex formats
  4917. var PositionNormalVertex = /** @class */ (function () {
  4918. function PositionNormalVertex(position, normal) {
  4919. if (position === void 0) { position = Vector3.Zero(); }
  4920. if (normal === void 0) { normal = Vector3.Up(); }
  4921. this.position = position;
  4922. this.normal = normal;
  4923. }
  4924. PositionNormalVertex.prototype.clone = function () {
  4925. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4926. };
  4927. return PositionNormalVertex;
  4928. }());
  4929. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4930. var PositionNormalTextureVertex = /** @class */ (function () {
  4931. function PositionNormalTextureVertex(position, normal, uv) {
  4932. if (position === void 0) { position = Vector3.Zero(); }
  4933. if (normal === void 0) { normal = Vector3.Up(); }
  4934. if (uv === void 0) { uv = Vector2.Zero(); }
  4935. this.position = position;
  4936. this.normal = normal;
  4937. this.uv = uv;
  4938. }
  4939. PositionNormalTextureVertex.prototype.clone = function () {
  4940. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4941. };
  4942. return PositionNormalTextureVertex;
  4943. }());
  4944. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4945. // Temporary pre-allocated objects for engine internal use
  4946. // usage in any internal function :
  4947. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4948. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4949. var Tmp = /** @class */ (function () {
  4950. function Tmp() {
  4951. }
  4952. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4953. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4954. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4955. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4956. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4957. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4958. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4959. Matrix.Zero(), Matrix.Zero(),
  4960. Matrix.Zero(), Matrix.Zero(),
  4961. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4962. return Tmp;
  4963. }());
  4964. BABYLON.Tmp = Tmp;
  4965. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4966. var MathTmp = /** @class */ (function () {
  4967. function MathTmp() {
  4968. }
  4969. MathTmp.Vector3 = [Vector3.Zero()];
  4970. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4971. MathTmp.Quaternion = [Quaternion.Zero()];
  4972. return MathTmp;
  4973. }());
  4974. })(BABYLON || (BABYLON = {}));
  4975. //# sourceMappingURL=babylon.math.js.map
  4976. var BABYLON;
  4977. (function (BABYLON) {
  4978. var Scalar = /** @class */ (function () {
  4979. function Scalar() {
  4980. }
  4981. /**
  4982. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4983. */
  4984. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4985. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4986. var num = a - b;
  4987. return -epsilon <= num && num <= epsilon;
  4988. };
  4989. /**
  4990. * Returns a string : the upper case translation of the number i to hexadecimal.
  4991. */
  4992. Scalar.ToHex = function (i) {
  4993. var str = i.toString(16);
  4994. if (i <= 15) {
  4995. return ("0" + str).toUpperCase();
  4996. }
  4997. return str.toUpperCase();
  4998. };
  4999. /**
  5000. * Returns -1 if value is negative and +1 is value is positive.
  5001. * Returns the value itself if it's equal to zero.
  5002. */
  5003. Scalar.Sign = function (value) {
  5004. value = +value; // convert to a number
  5005. if (value === 0 || isNaN(value))
  5006. return value;
  5007. return value > 0 ? 1 : -1;
  5008. };
  5009. /**
  5010. * Returns the value itself if it's between min and max.
  5011. * Returns min if the value is lower than min.
  5012. * Returns max if the value is greater than max.
  5013. */
  5014. Scalar.Clamp = function (value, min, max) {
  5015. if (min === void 0) { min = 0; }
  5016. if (max === void 0) { max = 1; }
  5017. return Math.min(max, Math.max(min, value));
  5018. };
  5019. /**
  5020. * Returns the log2 of value.
  5021. */
  5022. Scalar.Log2 = function (value) {
  5023. return Math.log(value) * Math.LOG2E;
  5024. };
  5025. /**
  5026. * Loops the value, so that it is never larger than length and never smaller than 0.
  5027. *
  5028. * This is similar to the modulo operator but it works with floating point numbers.
  5029. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5030. * With t = 5 and length = 2.5, the result would be 0.0.
  5031. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5032. */
  5033. Scalar.Repeat = function (value, length) {
  5034. return value - Math.floor(value / length) * length;
  5035. };
  5036. /**
  5037. * Normalize the value between 0.0 and 1.0 using min and max values
  5038. */
  5039. Scalar.Normalize = function (value, min, max) {
  5040. return (value - min) / (max - min);
  5041. };
  5042. /**
  5043. * Denormalize the value from 0.0 and 1.0 using min and max values
  5044. */
  5045. Scalar.Denormalize = function (normalized, min, max) {
  5046. return (normalized * (max - min) + min);
  5047. };
  5048. /**
  5049. * Calculates the shortest difference between two given angles given in degrees.
  5050. */
  5051. Scalar.DeltaAngle = function (current, target) {
  5052. var num = Scalar.Repeat(target - current, 360.0);
  5053. if (num > 180.0) {
  5054. num -= 360.0;
  5055. }
  5056. return num;
  5057. };
  5058. /**
  5059. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5060. *
  5061. * The returned value will move back and forth between 0 and length
  5062. */
  5063. Scalar.PingPong = function (tx, length) {
  5064. var t = Scalar.Repeat(tx, length * 2.0);
  5065. return length - Math.abs(t - length);
  5066. };
  5067. /**
  5068. * Interpolates between min and max with smoothing at the limits.
  5069. *
  5070. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5071. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5072. */
  5073. Scalar.SmoothStep = function (from, to, tx) {
  5074. var t = Scalar.Clamp(tx);
  5075. t = -2.0 * t * t * t + 3.0 * t * t;
  5076. return to * t + from * (1.0 - t);
  5077. };
  5078. /**
  5079. * Moves a value current towards target.
  5080. *
  5081. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5082. * Negative values of maxDelta pushes the value away from target.
  5083. */
  5084. Scalar.MoveTowards = function (current, target, maxDelta) {
  5085. var result = 0;
  5086. if (Math.abs(target - current) <= maxDelta) {
  5087. result = target;
  5088. }
  5089. else {
  5090. result = current + Scalar.Sign(target - current) * maxDelta;
  5091. }
  5092. return result;
  5093. };
  5094. /**
  5095. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5096. *
  5097. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5098. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5099. */
  5100. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5101. var num = Scalar.DeltaAngle(current, target);
  5102. var result = 0;
  5103. if (-maxDelta < num && num < maxDelta) {
  5104. result = target;
  5105. }
  5106. else {
  5107. target = current + num;
  5108. result = Scalar.MoveTowards(current, target, maxDelta);
  5109. }
  5110. return result;
  5111. };
  5112. /**
  5113. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5114. */
  5115. Scalar.Lerp = function (start, end, amount) {
  5116. return start + ((end - start) * amount);
  5117. };
  5118. /**
  5119. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5120. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5121. */
  5122. Scalar.LerpAngle = function (start, end, amount) {
  5123. var num = Scalar.Repeat(end - start, 360.0);
  5124. if (num > 180.0) {
  5125. num -= 360.0;
  5126. }
  5127. return start + num * Scalar.Clamp(amount);
  5128. };
  5129. /**
  5130. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5131. */
  5132. Scalar.InverseLerp = function (a, b, value) {
  5133. var result = 0;
  5134. if (a != b) {
  5135. result = Scalar.Clamp((value - a) / (b - a));
  5136. }
  5137. else {
  5138. result = 0.0;
  5139. }
  5140. return result;
  5141. };
  5142. /**
  5143. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5144. */
  5145. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5146. var squared = amount * amount;
  5147. var cubed = amount * squared;
  5148. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5149. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5150. var part3 = (cubed - (2.0 * squared)) + amount;
  5151. var part4 = cubed - squared;
  5152. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5153. };
  5154. /**
  5155. * Returns a random float number between and min and max values
  5156. */
  5157. Scalar.RandomRange = function (min, max) {
  5158. if (min === max)
  5159. return min;
  5160. return ((Math.random() * (max - min)) + min);
  5161. };
  5162. /**
  5163. * This function returns percentage of a number in a given range.
  5164. *
  5165. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5166. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5167. */
  5168. Scalar.RangeToPercent = function (number, min, max) {
  5169. return ((number - min) / (max - min));
  5170. };
  5171. /**
  5172. * This function returns number that corresponds to the percentage in a given range.
  5173. *
  5174. * PercentToRange(0.34,0,100) will return 34.
  5175. */
  5176. Scalar.PercentToRange = function (percent, min, max) {
  5177. return ((max - min) * percent + min);
  5178. };
  5179. /**
  5180. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5181. * @param angle The angle to normalize in radian.
  5182. * @return The converted angle.
  5183. */
  5184. Scalar.NormalizeRadians = function (angle) {
  5185. // More precise but slower version kept for reference.
  5186. // angle = angle % Tools.TwoPi;
  5187. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5188. //if (angle > Math.PI) {
  5189. // angle -= Tools.TwoPi;
  5190. //}
  5191. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5192. return angle;
  5193. };
  5194. /**
  5195. * Two pi constants convenient for computation.
  5196. */
  5197. Scalar.TwoPi = Math.PI * 2;
  5198. return Scalar;
  5199. }());
  5200. BABYLON.Scalar = Scalar;
  5201. })(BABYLON || (BABYLON = {}));
  5202. //# sourceMappingURL=babylon.math.scalar.js.map
  5203. //# sourceMappingURL=babylon.mixins.js.map
  5204. var BABYLON;
  5205. (function (BABYLON) {
  5206. var __decoratorInitialStore = {};
  5207. var __mergedStore = {};
  5208. var _copySource = function (creationFunction, source, instanciate) {
  5209. var destination = creationFunction();
  5210. // Tags
  5211. if (BABYLON.Tags) {
  5212. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5213. }
  5214. var classStore = getMergedStore(destination);
  5215. // Properties
  5216. for (var property in classStore) {
  5217. var propertyDescriptor = classStore[property];
  5218. var sourceProperty = source[property];
  5219. var propertyType = propertyDescriptor.type;
  5220. if (sourceProperty !== undefined && sourceProperty !== null) {
  5221. switch (propertyType) {
  5222. case 0: // Value
  5223. case 6:// Mesh reference
  5224. destination[property] = sourceProperty;
  5225. break;
  5226. case 1:// Texture
  5227. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5228. break;
  5229. case 2: // Color3
  5230. case 3: // FresnelParameters
  5231. case 4: // Vector2
  5232. case 5: // Vector3
  5233. case 7:// Color Curves
  5234. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5235. break;
  5236. }
  5237. }
  5238. }
  5239. return destination;
  5240. };
  5241. function getDirectStore(target) {
  5242. var classKey = target.getClassName();
  5243. if (!__decoratorInitialStore[classKey]) {
  5244. __decoratorInitialStore[classKey] = {};
  5245. }
  5246. return __decoratorInitialStore[classKey];
  5247. }
  5248. /**
  5249. * Return the list of properties flagged as serializable
  5250. * @param target: host object
  5251. */
  5252. function getMergedStore(target) {
  5253. var classKey = target.getClassName();
  5254. if (__mergedStore[classKey]) {
  5255. return __mergedStore[classKey];
  5256. }
  5257. __mergedStore[classKey] = {};
  5258. var store = __mergedStore[classKey];
  5259. var currentTarget = target;
  5260. var currentKey = classKey;
  5261. while (currentKey) {
  5262. var initialStore = __decoratorInitialStore[currentKey];
  5263. for (var property in initialStore) {
  5264. store[property] = initialStore[property];
  5265. }
  5266. var parent_1 = void 0;
  5267. var done = false;
  5268. do {
  5269. parent_1 = Object.getPrototypeOf(currentTarget);
  5270. if (!parent_1.getClassName) {
  5271. done = true;
  5272. break;
  5273. }
  5274. if (parent_1.getClassName() !== currentKey) {
  5275. break;
  5276. }
  5277. currentTarget = parent_1;
  5278. } while (parent_1);
  5279. if (done) {
  5280. break;
  5281. }
  5282. currentKey = parent_1.getClassName();
  5283. currentTarget = parent_1;
  5284. }
  5285. return store;
  5286. }
  5287. function generateSerializableMember(type, sourceName) {
  5288. return function (target, propertyKey) {
  5289. var classStore = getDirectStore(target);
  5290. if (!classStore[propertyKey]) {
  5291. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5292. }
  5293. };
  5294. }
  5295. function generateExpandMember(setCallback, targetKey) {
  5296. if (targetKey === void 0) { targetKey = null; }
  5297. return function (target, propertyKey) {
  5298. var key = targetKey || ("_" + propertyKey);
  5299. Object.defineProperty(target, propertyKey, {
  5300. get: function () {
  5301. return this[key];
  5302. },
  5303. set: function (value) {
  5304. if (this[key] === value) {
  5305. return;
  5306. }
  5307. this[key] = value;
  5308. target[setCallback].apply(this);
  5309. },
  5310. enumerable: true,
  5311. configurable: true
  5312. });
  5313. };
  5314. }
  5315. function expandToProperty(callback, targetKey) {
  5316. if (targetKey === void 0) { targetKey = null; }
  5317. return generateExpandMember(callback, targetKey);
  5318. }
  5319. BABYLON.expandToProperty = expandToProperty;
  5320. function serialize(sourceName) {
  5321. return generateSerializableMember(0, sourceName); // value member
  5322. }
  5323. BABYLON.serialize = serialize;
  5324. function serializeAsTexture(sourceName) {
  5325. return generateSerializableMember(1, sourceName); // texture member
  5326. }
  5327. BABYLON.serializeAsTexture = serializeAsTexture;
  5328. function serializeAsColor3(sourceName) {
  5329. return generateSerializableMember(2, sourceName); // color3 member
  5330. }
  5331. BABYLON.serializeAsColor3 = serializeAsColor3;
  5332. function serializeAsFresnelParameters(sourceName) {
  5333. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5334. }
  5335. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5336. function serializeAsVector2(sourceName) {
  5337. return generateSerializableMember(4, sourceName); // vector2 member
  5338. }
  5339. BABYLON.serializeAsVector2 = serializeAsVector2;
  5340. function serializeAsVector3(sourceName) {
  5341. return generateSerializableMember(5, sourceName); // vector3 member
  5342. }
  5343. BABYLON.serializeAsVector3 = serializeAsVector3;
  5344. function serializeAsMeshReference(sourceName) {
  5345. return generateSerializableMember(6, sourceName); // mesh reference member
  5346. }
  5347. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5348. function serializeAsColorCurves(sourceName) {
  5349. return generateSerializableMember(7, sourceName); // color curves
  5350. }
  5351. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5352. function serializeAsColor4(sourceName) {
  5353. return generateSerializableMember(8, sourceName); // color 4
  5354. }
  5355. BABYLON.serializeAsColor4 = serializeAsColor4;
  5356. function serializeAsImageProcessingConfiguration(sourceName) {
  5357. return generateSerializableMember(9, sourceName); // image processing
  5358. }
  5359. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5360. var SerializationHelper = /** @class */ (function () {
  5361. function SerializationHelper() {
  5362. }
  5363. SerializationHelper.Serialize = function (entity, serializationObject) {
  5364. if (!serializationObject) {
  5365. serializationObject = {};
  5366. }
  5367. // Tags
  5368. if (BABYLON.Tags) {
  5369. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5370. }
  5371. var serializedProperties = getMergedStore(entity);
  5372. // Properties
  5373. for (var property in serializedProperties) {
  5374. var propertyDescriptor = serializedProperties[property];
  5375. var targetPropertyName = propertyDescriptor.sourceName || property;
  5376. var propertyType = propertyDescriptor.type;
  5377. var sourceProperty = entity[property];
  5378. if (sourceProperty !== undefined && sourceProperty !== null) {
  5379. switch (propertyType) {
  5380. case 0:// Value
  5381. serializationObject[targetPropertyName] = sourceProperty;
  5382. break;
  5383. case 1:// Texture
  5384. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5385. break;
  5386. case 2:// Color3
  5387. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5388. break;
  5389. case 3:// FresnelParameters
  5390. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5391. break;
  5392. case 4:// Vector2
  5393. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5394. break;
  5395. case 5:// Vector3
  5396. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5397. break;
  5398. case 6:// Mesh reference
  5399. serializationObject[targetPropertyName] = sourceProperty.id;
  5400. break;
  5401. case 7:// Color Curves
  5402. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5403. break;
  5404. case 8:// Color 4
  5405. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5406. break;
  5407. case 9:// Image Processing
  5408. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5409. break;
  5410. }
  5411. }
  5412. }
  5413. return serializationObject;
  5414. };
  5415. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5416. if (rootUrl === void 0) { rootUrl = null; }
  5417. var destination = creationFunction();
  5418. if (!rootUrl) {
  5419. rootUrl = "";
  5420. }
  5421. // Tags
  5422. if (BABYLON.Tags) {
  5423. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5424. }
  5425. var classStore = getMergedStore(destination);
  5426. // Properties
  5427. for (var property in classStore) {
  5428. var propertyDescriptor = classStore[property];
  5429. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5430. var propertyType = propertyDescriptor.type;
  5431. if (sourceProperty !== undefined && sourceProperty !== null) {
  5432. var dest = destination;
  5433. switch (propertyType) {
  5434. case 0:// Value
  5435. dest[property] = sourceProperty;
  5436. break;
  5437. case 1:// Texture
  5438. if (scene) {
  5439. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5440. }
  5441. break;
  5442. case 2:// Color3
  5443. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5444. break;
  5445. case 3:// FresnelParameters
  5446. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5447. break;
  5448. case 4:// Vector2
  5449. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5450. break;
  5451. case 5:// Vector3
  5452. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5453. break;
  5454. case 6:// Mesh reference
  5455. if (scene) {
  5456. dest[property] = scene.getLastMeshByID(sourceProperty);
  5457. }
  5458. break;
  5459. case 7:// Color Curves
  5460. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5461. break;
  5462. case 8:// Color 4
  5463. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5464. break;
  5465. case 9:// Image Processing
  5466. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5467. break;
  5468. }
  5469. }
  5470. }
  5471. return destination;
  5472. };
  5473. SerializationHelper.Clone = function (creationFunction, source) {
  5474. return _copySource(creationFunction, source, false);
  5475. };
  5476. SerializationHelper.Instanciate = function (creationFunction, source) {
  5477. return _copySource(creationFunction, source, true);
  5478. };
  5479. return SerializationHelper;
  5480. }());
  5481. BABYLON.SerializationHelper = SerializationHelper;
  5482. })(BABYLON || (BABYLON = {}));
  5483. //# sourceMappingURL=babylon.decorators.js.map
  5484. var BABYLON;
  5485. (function (BABYLON) {
  5486. /**
  5487. * A class serves as a medium between the observable and its observers
  5488. */
  5489. var EventState = /** @class */ (function () {
  5490. /**
  5491. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5492. */
  5493. function EventState(mask, skipNextObservers, target, currentTarget) {
  5494. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5495. this.initalize(mask, skipNextObservers, target, currentTarget);
  5496. }
  5497. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5498. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5499. this.mask = mask;
  5500. this.skipNextObservers = skipNextObservers;
  5501. this.target = target;
  5502. this.currentTarget = currentTarget;
  5503. return this;
  5504. };
  5505. return EventState;
  5506. }());
  5507. BABYLON.EventState = EventState;
  5508. /**
  5509. * Represent an Observer registered to a given Observable object.
  5510. */
  5511. var Observer = /** @class */ (function () {
  5512. function Observer(callback, mask, scope) {
  5513. if (scope === void 0) { scope = null; }
  5514. this.callback = callback;
  5515. this.mask = mask;
  5516. this.scope = scope;
  5517. }
  5518. return Observer;
  5519. }());
  5520. BABYLON.Observer = Observer;
  5521. /**
  5522. * Represent a list of observers registered to multiple Observables object.
  5523. */
  5524. var MultiObserver = /** @class */ (function () {
  5525. function MultiObserver() {
  5526. }
  5527. MultiObserver.prototype.dispose = function () {
  5528. if (this._observers && this._observables) {
  5529. for (var index = 0; index < this._observers.length; index++) {
  5530. this._observables[index].remove(this._observers[index]);
  5531. }
  5532. }
  5533. this._observers = null;
  5534. this._observables = null;
  5535. };
  5536. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5537. if (mask === void 0) { mask = -1; }
  5538. if (scope === void 0) { scope = null; }
  5539. var result = new MultiObserver();
  5540. result._observers = new Array();
  5541. result._observables = observables;
  5542. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5543. var observable = observables_1[_i];
  5544. var observer = observable.add(callback, mask, false, scope);
  5545. if (observer) {
  5546. result._observers.push(observer);
  5547. }
  5548. }
  5549. return result;
  5550. };
  5551. return MultiObserver;
  5552. }());
  5553. BABYLON.MultiObserver = MultiObserver;
  5554. /**
  5555. * The Observable class is a simple implementation of the Observable pattern.
  5556. * 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.
  5557. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5558. * 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).
  5559. * 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.
  5560. */
  5561. var Observable = /** @class */ (function () {
  5562. function Observable(onObserverAdded) {
  5563. this._observers = new Array();
  5564. this._eventState = new EventState(0);
  5565. if (onObserverAdded) {
  5566. this._onObserverAdded = onObserverAdded;
  5567. }
  5568. }
  5569. /**
  5570. * Create a new Observer with the specified callback
  5571. * @param callback the callback that will be executed for that Observer
  5572. * @param mask the mask used to filter observers
  5573. * @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.
  5574. * @param scope optional scope for the callback to be called from
  5575. */
  5576. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5577. if (mask === void 0) { mask = -1; }
  5578. if (insertFirst === void 0) { insertFirst = false; }
  5579. if (scope === void 0) { scope = null; }
  5580. if (!callback) {
  5581. return null;
  5582. }
  5583. var observer = new Observer(callback, mask, scope);
  5584. if (insertFirst) {
  5585. this._observers.unshift(observer);
  5586. }
  5587. else {
  5588. this._observers.push(observer);
  5589. }
  5590. if (this._onObserverAdded) {
  5591. this._onObserverAdded(observer);
  5592. }
  5593. return observer;
  5594. };
  5595. /**
  5596. * Remove an Observer from the Observable object
  5597. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5598. */
  5599. Observable.prototype.remove = function (observer) {
  5600. if (!observer) {
  5601. return false;
  5602. }
  5603. var index = this._observers.indexOf(observer);
  5604. if (index !== -1) {
  5605. this._observers.splice(index, 1);
  5606. return true;
  5607. }
  5608. return false;
  5609. };
  5610. /**
  5611. * Remove a callback from the Observable object
  5612. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5613. */
  5614. Observable.prototype.removeCallback = function (callback) {
  5615. for (var index = 0; index < this._observers.length; index++) {
  5616. if (this._observers[index].callback === callback) {
  5617. this._observers.splice(index, 1);
  5618. return true;
  5619. }
  5620. }
  5621. return false;
  5622. };
  5623. /**
  5624. * Notify all Observers by calling their respective callback with the given data
  5625. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5626. * @param eventData
  5627. * @param mask
  5628. */
  5629. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5630. if (mask === void 0) { mask = -1; }
  5631. if (!this._observers.length) {
  5632. return true;
  5633. }
  5634. var state = this._eventState;
  5635. state.mask = mask;
  5636. state.target = target;
  5637. state.currentTarget = currentTarget;
  5638. state.skipNextObservers = false;
  5639. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5640. var obs = _a[_i];
  5641. if (obs.mask & mask) {
  5642. if (obs.scope) {
  5643. obs.callback.apply(obs.scope, [eventData, state]);
  5644. }
  5645. else {
  5646. obs.callback(eventData, state);
  5647. }
  5648. }
  5649. if (state.skipNextObservers) {
  5650. return false;
  5651. }
  5652. }
  5653. return true;
  5654. };
  5655. /**
  5656. * Notify a specific observer
  5657. * @param eventData
  5658. * @param mask
  5659. */
  5660. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5661. if (mask === void 0) { mask = -1; }
  5662. var state = this._eventState;
  5663. state.mask = mask;
  5664. state.skipNextObservers = false;
  5665. observer.callback(eventData, state);
  5666. };
  5667. /**
  5668. * return true is the Observable has at least one Observer registered
  5669. */
  5670. Observable.prototype.hasObservers = function () {
  5671. return this._observers.length > 0;
  5672. };
  5673. /**
  5674. * Clear the list of observers
  5675. */
  5676. Observable.prototype.clear = function () {
  5677. this._observers = new Array();
  5678. this._onObserverAdded = null;
  5679. };
  5680. /**
  5681. * Clone the current observable
  5682. */
  5683. Observable.prototype.clone = function () {
  5684. var result = new Observable();
  5685. result._observers = this._observers.slice(0);
  5686. return result;
  5687. };
  5688. /**
  5689. * Does this observable handles observer registered with a given mask
  5690. * @param {number} trigger - the mask to be tested
  5691. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5692. **/
  5693. Observable.prototype.hasSpecificMask = function (mask) {
  5694. if (mask === void 0) { mask = -1; }
  5695. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5696. var obs = _a[_i];
  5697. if (obs.mask & mask || obs.mask === mask) {
  5698. return true;
  5699. }
  5700. }
  5701. return false;
  5702. };
  5703. return Observable;
  5704. }());
  5705. BABYLON.Observable = Observable;
  5706. })(BABYLON || (BABYLON = {}));
  5707. //# sourceMappingURL=babylon.observable.js.map
  5708. var BABYLON;
  5709. (function (BABYLON) {
  5710. var SmartArray = /** @class */ (function () {
  5711. function SmartArray(capacity) {
  5712. this.length = 0;
  5713. this.data = new Array(capacity);
  5714. this._id = SmartArray._GlobalId++;
  5715. }
  5716. SmartArray.prototype.push = function (value) {
  5717. this.data[this.length++] = value;
  5718. if (this.length > this.data.length) {
  5719. this.data.length *= 2;
  5720. }
  5721. };
  5722. SmartArray.prototype.forEach = function (func) {
  5723. for (var index = 0; index < this.length; index++) {
  5724. func(this.data[index]);
  5725. }
  5726. };
  5727. SmartArray.prototype.sort = function (compareFn) {
  5728. this.data.sort(compareFn);
  5729. };
  5730. SmartArray.prototype.reset = function () {
  5731. this.length = 0;
  5732. };
  5733. SmartArray.prototype.dispose = function () {
  5734. this.reset();
  5735. if (this.data) {
  5736. this.data.length = 0;
  5737. this.data = [];
  5738. }
  5739. };
  5740. SmartArray.prototype.concat = function (array) {
  5741. if (array.length === 0) {
  5742. return;
  5743. }
  5744. if (this.length + array.length > this.data.length) {
  5745. this.data.length = (this.length + array.length) * 2;
  5746. }
  5747. for (var index = 0; index < array.length; index++) {
  5748. this.data[this.length++] = (array.data || array)[index];
  5749. }
  5750. };
  5751. SmartArray.prototype.indexOf = function (value) {
  5752. var position = this.data.indexOf(value);
  5753. if (position >= this.length) {
  5754. return -1;
  5755. }
  5756. return position;
  5757. };
  5758. SmartArray.prototype.contains = function (value) {
  5759. return this.data.indexOf(value) !== -1;
  5760. };
  5761. // Statics
  5762. SmartArray._GlobalId = 0;
  5763. return SmartArray;
  5764. }());
  5765. BABYLON.SmartArray = SmartArray;
  5766. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  5767. __extends(SmartArrayNoDuplicate, _super);
  5768. function SmartArrayNoDuplicate() {
  5769. var _this = _super !== null && _super.apply(this, arguments) || this;
  5770. _this._duplicateId = 0;
  5771. return _this;
  5772. }
  5773. SmartArrayNoDuplicate.prototype.push = function (value) {
  5774. _super.prototype.push.call(this, value);
  5775. if (!value.__smartArrayFlags) {
  5776. value.__smartArrayFlags = {};
  5777. }
  5778. value.__smartArrayFlags[this._id] = this._duplicateId;
  5779. };
  5780. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  5781. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5782. return false;
  5783. }
  5784. this.push(value);
  5785. return true;
  5786. };
  5787. SmartArrayNoDuplicate.prototype.reset = function () {
  5788. _super.prototype.reset.call(this);
  5789. this._duplicateId++;
  5790. };
  5791. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  5792. if (array.length === 0) {
  5793. return;
  5794. }
  5795. if (this.length + array.length > this.data.length) {
  5796. this.data.length = (this.length + array.length) * 2;
  5797. }
  5798. for (var index = 0; index < array.length; index++) {
  5799. var item = (array.data || array)[index];
  5800. this.pushNoDuplicate(item);
  5801. }
  5802. };
  5803. return SmartArrayNoDuplicate;
  5804. }(SmartArray));
  5805. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  5806. })(BABYLON || (BABYLON = {}));
  5807. //# sourceMappingURL=babylon.smartArray.js.map
  5808. var BABYLON;
  5809. (function (BABYLON) {
  5810. // Screenshots
  5811. var screenshotCanvas;
  5812. var cloneValue = function (source, destinationObject) {
  5813. if (!source)
  5814. return null;
  5815. if (source instanceof BABYLON.Mesh) {
  5816. return null;
  5817. }
  5818. if (source instanceof BABYLON.SubMesh) {
  5819. return source.clone(destinationObject);
  5820. }
  5821. else if (source.clone) {
  5822. return source.clone();
  5823. }
  5824. return null;
  5825. };
  5826. var Tools = /** @class */ (function () {
  5827. function Tools() {
  5828. }
  5829. ;
  5830. /**
  5831. * Interpolates between a and b via alpha
  5832. * @param a The lower value (returned when alpha = 0)
  5833. * @param b The upper value (returned when alpha = 1)
  5834. * @param alpha The interpolation-factor
  5835. * @return The mixed value
  5836. */
  5837. Tools.Mix = function (a, b, alpha) {
  5838. return a * (1 - alpha) + b * alpha;
  5839. };
  5840. Tools.Instantiate = function (className) {
  5841. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5842. return Tools.RegisteredExternalClasses[className];
  5843. }
  5844. var arr = className.split(".");
  5845. var fn = (window || this);
  5846. for (var i = 0, len = arr.length; i < len; i++) {
  5847. fn = fn[arr[i]];
  5848. }
  5849. if (typeof fn !== "function") {
  5850. return null;
  5851. }
  5852. return fn;
  5853. };
  5854. Tools.SetImmediate = function (action) {
  5855. if (window.setImmediate) {
  5856. window.setImmediate(action);
  5857. }
  5858. else {
  5859. setTimeout(action, 1);
  5860. }
  5861. };
  5862. Tools.IsExponentOfTwo = function (value) {
  5863. var count = 1;
  5864. do {
  5865. count *= 2;
  5866. } while (count < value);
  5867. return count === value;
  5868. };
  5869. /**
  5870. * Find the next highest power of two.
  5871. * @param x Number to start search from.
  5872. * @return Next highest power of two.
  5873. */
  5874. Tools.CeilingPOT = function (x) {
  5875. x--;
  5876. x |= x >> 1;
  5877. x |= x >> 2;
  5878. x |= x >> 4;
  5879. x |= x >> 8;
  5880. x |= x >> 16;
  5881. x++;
  5882. return x;
  5883. };
  5884. /**
  5885. * Find the next lowest power of two.
  5886. * @param x Number to start search from.
  5887. * @return Next lowest power of two.
  5888. */
  5889. Tools.FloorPOT = function (x) {
  5890. x = x | (x >> 1);
  5891. x = x | (x >> 2);
  5892. x = x | (x >> 4);
  5893. x = x | (x >> 8);
  5894. x = x | (x >> 16);
  5895. return x - (x >> 1);
  5896. };
  5897. /**
  5898. * Find the nearest power of two.
  5899. * @param x Number to start search from.
  5900. * @return Next nearest power of two.
  5901. */
  5902. Tools.NearestPOT = function (x) {
  5903. var c = Tools.CeilingPOT(x);
  5904. var f = Tools.FloorPOT(x);
  5905. return (c - x) > (x - f) ? f : c;
  5906. };
  5907. Tools.GetExponentOfTwo = function (value, max, mode) {
  5908. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5909. var pot;
  5910. switch (mode) {
  5911. case BABYLON.Engine.SCALEMODE_FLOOR:
  5912. pot = Tools.FloorPOT(value);
  5913. break;
  5914. case BABYLON.Engine.SCALEMODE_NEAREST:
  5915. pot = Tools.NearestPOT(value);
  5916. break;
  5917. case BABYLON.Engine.SCALEMODE_CEILING:
  5918. default:
  5919. pot = Tools.CeilingPOT(value);
  5920. break;
  5921. }
  5922. return Math.min(pot, max);
  5923. };
  5924. Tools.GetFilename = function (path) {
  5925. var index = path.lastIndexOf("/");
  5926. if (index < 0)
  5927. return path;
  5928. return path.substring(index + 1);
  5929. };
  5930. Tools.GetFolderPath = function (uri) {
  5931. var index = uri.lastIndexOf("/");
  5932. if (index < 0)
  5933. return "";
  5934. return uri.substring(0, index + 1);
  5935. };
  5936. Tools.GetDOMTextContent = function (element) {
  5937. var result = "";
  5938. var child = element.firstChild;
  5939. while (child) {
  5940. if (child.nodeType === 3) {
  5941. result += child.textContent;
  5942. }
  5943. child = child.nextSibling;
  5944. }
  5945. return result;
  5946. };
  5947. Tools.ToDegrees = function (angle) {
  5948. return angle * 180 / Math.PI;
  5949. };
  5950. Tools.ToRadians = function (angle) {
  5951. return angle * Math.PI / 180;
  5952. };
  5953. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5954. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5955. var output = "";
  5956. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5957. var i = 0;
  5958. var bytes = new Uint8Array(buffer);
  5959. while (i < bytes.length) {
  5960. chr1 = bytes[i++];
  5961. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5962. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5963. enc1 = chr1 >> 2;
  5964. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5965. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5966. enc4 = chr3 & 63;
  5967. if (isNaN(chr2)) {
  5968. enc3 = enc4 = 64;
  5969. }
  5970. else if (isNaN(chr3)) {
  5971. enc4 = 64;
  5972. }
  5973. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5974. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5975. }
  5976. return "data:image/png;base64," + output;
  5977. };
  5978. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5979. if (bias === void 0) { bias = null; }
  5980. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5981. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5982. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5983. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5984. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5985. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5986. }
  5987. if (bias) {
  5988. minimum.x -= minimum.x * bias.x + bias.y;
  5989. minimum.y -= minimum.y * bias.x + bias.y;
  5990. minimum.z -= minimum.z * bias.x + bias.y;
  5991. maximum.x += maximum.x * bias.x + bias.y;
  5992. maximum.y += maximum.y * bias.x + bias.y;
  5993. maximum.z += maximum.z * bias.x + bias.y;
  5994. }
  5995. return {
  5996. minimum: minimum,
  5997. maximum: maximum
  5998. };
  5999. };
  6000. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6001. if (bias === void 0) { bias = null; }
  6002. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6003. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6004. if (!stride) {
  6005. stride = 3;
  6006. }
  6007. for (var index = start; index < start + count; index++) {
  6008. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6009. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6010. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6011. }
  6012. if (bias) {
  6013. minimum.x -= minimum.x * bias.x + bias.y;
  6014. minimum.y -= minimum.y * bias.x + bias.y;
  6015. minimum.z -= minimum.z * bias.x + bias.y;
  6016. maximum.x += maximum.x * bias.x + bias.y;
  6017. maximum.y += maximum.y * bias.x + bias.y;
  6018. maximum.z += maximum.z * bias.x + bias.y;
  6019. }
  6020. return {
  6021. minimum: minimum,
  6022. maximum: maximum
  6023. };
  6024. };
  6025. Tools.Vector2ArrayFeeder = function (array) {
  6026. return function (index) {
  6027. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6028. var length = isFloatArray ? array.length / 2 : array.length;
  6029. if (index >= length) {
  6030. return null;
  6031. }
  6032. if (isFloatArray) {
  6033. var fa = array;
  6034. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6035. }
  6036. var a = array;
  6037. return a[index];
  6038. };
  6039. };
  6040. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6041. if (bias === void 0) { bias = null; }
  6042. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6043. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6044. var i = 0;
  6045. var cur = feeder(i++);
  6046. while (cur) {
  6047. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6048. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6049. cur = feeder(i++);
  6050. }
  6051. if (bias) {
  6052. minimum.x -= minimum.x * bias.x + bias.y;
  6053. minimum.y -= minimum.y * bias.x + bias.y;
  6054. maximum.x += maximum.x * bias.x + bias.y;
  6055. maximum.y += maximum.y * bias.x + bias.y;
  6056. }
  6057. return {
  6058. minimum: minimum,
  6059. maximum: maximum
  6060. };
  6061. };
  6062. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6063. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6064. return null;
  6065. return Array.isArray(obj) ? obj : [obj];
  6066. };
  6067. // Misc.
  6068. Tools.GetPointerPrefix = function () {
  6069. var eventPrefix = "pointer";
  6070. // Check if pointer events are supported
  6071. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6072. eventPrefix = "mouse";
  6073. }
  6074. return eventPrefix;
  6075. };
  6076. /**
  6077. * @param func - the function to be called
  6078. * @param requester - the object that will request the next frame. Falls back to window.
  6079. */
  6080. Tools.QueueNewFrame = function (func, requester) {
  6081. if (!Tools.IsWindowObjectExist()) {
  6082. return setTimeout(func, 16);
  6083. }
  6084. if (!requester) {
  6085. requester = window;
  6086. }
  6087. if (requester.requestAnimationFrame) {
  6088. return requester.requestAnimationFrame(func);
  6089. }
  6090. else if (requester.msRequestAnimationFrame) {
  6091. return requester.msRequestAnimationFrame(func);
  6092. }
  6093. else if (requester.webkitRequestAnimationFrame) {
  6094. return requester.webkitRequestAnimationFrame(func);
  6095. }
  6096. else if (requester.mozRequestAnimationFrame) {
  6097. return requester.mozRequestAnimationFrame(func);
  6098. }
  6099. else if (requester.oRequestAnimationFrame) {
  6100. return requester.oRequestAnimationFrame(func);
  6101. }
  6102. else {
  6103. return window.setTimeout(func, 16);
  6104. }
  6105. };
  6106. Tools.RequestFullscreen = function (element) {
  6107. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6108. if (!requestFunction)
  6109. return;
  6110. requestFunction.call(element);
  6111. };
  6112. Tools.ExitFullscreen = function () {
  6113. if (document.exitFullscreen) {
  6114. document.exitFullscreen();
  6115. }
  6116. else if (document.mozCancelFullScreen) {
  6117. document.mozCancelFullScreen();
  6118. }
  6119. else if (document.webkitCancelFullScreen) {
  6120. document.webkitCancelFullScreen();
  6121. }
  6122. else if (document.msCancelFullScreen) {
  6123. document.msCancelFullScreen();
  6124. }
  6125. };
  6126. Tools.SetCorsBehavior = function (url, img) {
  6127. if (Tools.CorsBehavior) {
  6128. switch (typeof (Tools.CorsBehavior)) {
  6129. case "function":
  6130. var result = Tools.CorsBehavior(url);
  6131. if (result) {
  6132. img.crossOrigin = result;
  6133. }
  6134. break;
  6135. case "string":
  6136. default:
  6137. img.crossOrigin = Tools.CorsBehavior;
  6138. break;
  6139. }
  6140. }
  6141. };
  6142. // External files
  6143. Tools.CleanUrl = function (url) {
  6144. url = url.replace(/#/mg, "%23");
  6145. return url;
  6146. };
  6147. Tools.LoadImage = function (url, onLoad, onError, database) {
  6148. if (url instanceof ArrayBuffer) {
  6149. url = Tools.EncodeArrayBufferTobase64(url);
  6150. }
  6151. url = Tools.CleanUrl(url);
  6152. url = Tools.PreprocessUrl(url);
  6153. var img = new Image();
  6154. if (url.substr(0, 5) !== "data:") {
  6155. Tools.SetCorsBehavior(url, img);
  6156. }
  6157. img.onload = function () {
  6158. onLoad(img);
  6159. };
  6160. img.onerror = function (err) {
  6161. Tools.Error("Error while trying to load image: " + url);
  6162. if (Tools.UseFallbackTexture) {
  6163. img.src = Tools.fallbackTexture;
  6164. onLoad(img);
  6165. }
  6166. else {
  6167. onError("Error while trying to load image: " + url, err);
  6168. }
  6169. };
  6170. var noIndexedDB = function () {
  6171. img.src = url;
  6172. };
  6173. var loadFromIndexedDB = function () {
  6174. if (database) {
  6175. database.loadImageFromDB(url, img);
  6176. }
  6177. };
  6178. //ANY database to do!
  6179. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6180. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6181. }
  6182. else {
  6183. if (url.indexOf("file:") !== 0) {
  6184. noIndexedDB();
  6185. }
  6186. else {
  6187. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6188. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6189. try {
  6190. var blobURL;
  6191. try {
  6192. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6193. }
  6194. catch (ex) {
  6195. // Chrome doesn't support oneTimeOnly parameter
  6196. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6197. }
  6198. img.src = blobURL;
  6199. }
  6200. catch (e) {
  6201. img.src = "";
  6202. }
  6203. }
  6204. else {
  6205. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6206. img.src = Tools.fallbackTexture;
  6207. }
  6208. }
  6209. }
  6210. return img;
  6211. };
  6212. //ANY
  6213. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6214. url = Tools.CleanUrl(url);
  6215. url = Tools.PreprocessUrl(url);
  6216. var request = null;
  6217. var noIndexedDB = function () {
  6218. request = new XMLHttpRequest();
  6219. var loadUrl = Tools.BaseUrl + url;
  6220. request.open('GET', loadUrl, true);
  6221. if (useArrayBuffer) {
  6222. request.responseType = "arraybuffer";
  6223. }
  6224. if (progressCallBack) {
  6225. request.onprogress = progressCallBack;
  6226. }
  6227. request.onreadystatechange = function () {
  6228. var req = request;
  6229. // In case of undefined state in some browsers.
  6230. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6231. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6232. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6233. callback(!useArrayBuffer ? req.responseText : req.response, req.responseURL);
  6234. }
  6235. else {
  6236. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6237. if (onError) {
  6238. onError(req, e);
  6239. }
  6240. else {
  6241. throw e;
  6242. }
  6243. }
  6244. }
  6245. };
  6246. request.send(null);
  6247. };
  6248. var loadFromIndexedDB = function () {
  6249. if (database) {
  6250. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6251. }
  6252. };
  6253. if (url.indexOf("file:") !== -1) {
  6254. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6255. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6256. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6257. }
  6258. else {
  6259. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6260. if (onError) {
  6261. var e = new Error(errorMessage);
  6262. onError(undefined, e);
  6263. }
  6264. else {
  6265. Tools.Error(errorMessage);
  6266. }
  6267. }
  6268. }
  6269. else {
  6270. // Caching all files
  6271. if (database && database.enableSceneOffline) {
  6272. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6273. }
  6274. else {
  6275. noIndexedDB();
  6276. }
  6277. }
  6278. return request;
  6279. };
  6280. /**
  6281. * Load a script (identified by an url). When the url returns, the
  6282. * content of this file is added into a new script element, attached to the DOM (body element)
  6283. */
  6284. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6285. var head = document.getElementsByTagName('head')[0];
  6286. var script = document.createElement('script');
  6287. script.type = 'text/javascript';
  6288. script.src = scriptUrl;
  6289. script.onload = function () {
  6290. if (onSuccess) {
  6291. onSuccess();
  6292. }
  6293. };
  6294. script.onerror = function (e) {
  6295. if (onError) {
  6296. onError("Unable to load script", e);
  6297. }
  6298. };
  6299. head.appendChild(script);
  6300. };
  6301. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6302. var reader = new FileReader();
  6303. reader.onload = function (e) {
  6304. //target doesn't have result from ts 1.3
  6305. callback(e.target['result']);
  6306. };
  6307. reader.onprogress = progressCallback;
  6308. reader.readAsDataURL(fileToLoad);
  6309. };
  6310. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6311. var reader = new FileReader();
  6312. reader.onerror = function (e) {
  6313. Tools.Log("Error while reading file: " + fileToLoad.name);
  6314. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6315. };
  6316. reader.onload = function (e) {
  6317. //target doesn't have result from ts 1.3
  6318. callback(e.target['result']);
  6319. };
  6320. if (progressCallBack) {
  6321. reader.onprogress = progressCallBack;
  6322. }
  6323. if (!useArrayBuffer) {
  6324. // Asynchronous read
  6325. reader.readAsText(fileToLoad);
  6326. }
  6327. else {
  6328. reader.readAsArrayBuffer(fileToLoad);
  6329. }
  6330. };
  6331. //returns a downloadable url to a file content.
  6332. Tools.FileAsURL = function (content) {
  6333. var fileBlob = new Blob([content]);
  6334. var url = window.URL || window.webkitURL;
  6335. var link = url.createObjectURL(fileBlob);
  6336. return link;
  6337. };
  6338. // Misc.
  6339. Tools.Format = function (value, decimals) {
  6340. if (decimals === void 0) { decimals = 2; }
  6341. return value.toFixed(decimals);
  6342. };
  6343. Tools.CheckExtends = function (v, min, max) {
  6344. if (v.x < min.x)
  6345. min.x = v.x;
  6346. if (v.y < min.y)
  6347. min.y = v.y;
  6348. if (v.z < min.z)
  6349. min.z = v.z;
  6350. if (v.x > max.x)
  6351. max.x = v.x;
  6352. if (v.y > max.y)
  6353. max.y = v.y;
  6354. if (v.z > max.z)
  6355. max.z = v.z;
  6356. };
  6357. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6358. for (var prop in source) {
  6359. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6360. continue;
  6361. }
  6362. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6363. continue;
  6364. }
  6365. var sourceValue = source[prop];
  6366. var typeOfSourceValue = typeof sourceValue;
  6367. if (typeOfSourceValue === "function") {
  6368. continue;
  6369. }
  6370. if (typeOfSourceValue === "object") {
  6371. if (sourceValue instanceof Array) {
  6372. destination[prop] = [];
  6373. if (sourceValue.length > 0) {
  6374. if (typeof sourceValue[0] == "object") {
  6375. for (var index = 0; index < sourceValue.length; index++) {
  6376. var clonedValue = cloneValue(sourceValue[index], destination);
  6377. if (destination[prop].indexOf(clonedValue) === -1) {
  6378. destination[prop].push(clonedValue);
  6379. }
  6380. }
  6381. }
  6382. else {
  6383. destination[prop] = sourceValue.slice(0);
  6384. }
  6385. }
  6386. }
  6387. else {
  6388. destination[prop] = cloneValue(sourceValue, destination);
  6389. }
  6390. }
  6391. else {
  6392. destination[prop] = sourceValue;
  6393. }
  6394. }
  6395. };
  6396. Tools.IsEmpty = function (obj) {
  6397. for (var i in obj) {
  6398. if (obj.hasOwnProperty(i)) {
  6399. return false;
  6400. }
  6401. }
  6402. return true;
  6403. };
  6404. Tools.RegisterTopRootEvents = function (events) {
  6405. for (var index = 0; index < events.length; index++) {
  6406. var event = events[index];
  6407. window.addEventListener(event.name, event.handler, false);
  6408. try {
  6409. if (window.parent) {
  6410. window.parent.addEventListener(event.name, event.handler, false);
  6411. }
  6412. }
  6413. catch (e) {
  6414. // Silently fails...
  6415. }
  6416. }
  6417. };
  6418. Tools.UnregisterTopRootEvents = function (events) {
  6419. for (var index = 0; index < events.length; index++) {
  6420. var event = events[index];
  6421. window.removeEventListener(event.name, event.handler);
  6422. try {
  6423. if (window.parent) {
  6424. window.parent.removeEventListener(event.name, event.handler);
  6425. }
  6426. }
  6427. catch (e) {
  6428. // Silently fails...
  6429. }
  6430. }
  6431. };
  6432. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6433. if (mimeType === void 0) { mimeType = "image/png"; }
  6434. // Read the contents of the framebuffer
  6435. var numberOfChannelsByLine = width * 4;
  6436. var halfHeight = height / 2;
  6437. //Reading datas from WebGL
  6438. var data = engine.readPixels(0, 0, width, height);
  6439. //To flip image on Y axis.
  6440. for (var i = 0; i < halfHeight; i++) {
  6441. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6442. var currentCell = j + i * numberOfChannelsByLine;
  6443. var targetLine = height - i - 1;
  6444. var targetCell = j + targetLine * numberOfChannelsByLine;
  6445. var temp = data[currentCell];
  6446. data[currentCell] = data[targetCell];
  6447. data[targetCell] = temp;
  6448. }
  6449. }
  6450. // Create a 2D canvas to store the result
  6451. if (!screenshotCanvas) {
  6452. screenshotCanvas = document.createElement('canvas');
  6453. }
  6454. screenshotCanvas.width = width;
  6455. screenshotCanvas.height = height;
  6456. var context = screenshotCanvas.getContext('2d');
  6457. if (context) {
  6458. // Copy the pixels to a 2D canvas
  6459. var imageData = context.createImageData(width, height);
  6460. var castData = (imageData.data);
  6461. castData.set(data);
  6462. context.putImageData(imageData, 0, 0);
  6463. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6464. }
  6465. };
  6466. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6467. if (mimeType === void 0) { mimeType = "image/png"; }
  6468. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6469. if (successCallback) {
  6470. successCallback(base64Image);
  6471. }
  6472. else {
  6473. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6474. if (("download" in document.createElement("a"))) {
  6475. var a = window.document.createElement("a");
  6476. a.href = base64Image;
  6477. var date = new Date();
  6478. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6479. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6480. window.document.body.appendChild(a);
  6481. a.addEventListener("click", function () {
  6482. if (a.parentElement) {
  6483. a.parentElement.removeChild(a);
  6484. }
  6485. });
  6486. a.click();
  6487. //Or opening a new tab with the image if it is not possible to automatically start download.
  6488. }
  6489. else {
  6490. var newWindow = window.open("");
  6491. var img = newWindow.document.createElement("img");
  6492. img.src = base64Image;
  6493. newWindow.document.body.appendChild(img);
  6494. }
  6495. }
  6496. };
  6497. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6498. if (mimeType === void 0) { mimeType = "image/png"; }
  6499. var width;
  6500. var height;
  6501. // If a precision value is specified
  6502. if (size.precision) {
  6503. width = Math.round(engine.getRenderWidth() * size.precision);
  6504. height = Math.round(width / engine.getAspectRatio(camera));
  6505. }
  6506. else if (size.width && size.height) {
  6507. width = size.width;
  6508. height = size.height;
  6509. }
  6510. else if (size.width && !size.height) {
  6511. width = size.width;
  6512. height = Math.round(width / engine.getAspectRatio(camera));
  6513. }
  6514. else if (size.height && !size.width) {
  6515. height = size.height;
  6516. width = Math.round(height * engine.getAspectRatio(camera));
  6517. }
  6518. else if (!isNaN(size)) {
  6519. height = size;
  6520. width = size;
  6521. }
  6522. else {
  6523. Tools.Error("Invalid 'size' parameter !");
  6524. return;
  6525. }
  6526. if (!screenshotCanvas) {
  6527. screenshotCanvas = document.createElement('canvas');
  6528. }
  6529. screenshotCanvas.width = width;
  6530. screenshotCanvas.height = height;
  6531. var renderContext = screenshotCanvas.getContext("2d");
  6532. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6533. var newWidth = width;
  6534. var newHeight = newWidth / ratio;
  6535. if (newHeight > height) {
  6536. newHeight = height;
  6537. newWidth = newHeight * ratio;
  6538. }
  6539. var offsetX = Math.max(0, width - newWidth) / 2;
  6540. var offsetY = Math.max(0, height - newHeight) / 2;
  6541. var renderingCanvas = engine.getRenderingCanvas();
  6542. if (renderContext && renderingCanvas) {
  6543. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6544. }
  6545. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6546. };
  6547. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6548. if (mimeType === void 0) { mimeType = "image/png"; }
  6549. if (samples === void 0) { samples = 1; }
  6550. var width;
  6551. var height;
  6552. //If a precision value is specified
  6553. if (size.precision) {
  6554. width = Math.round(engine.getRenderWidth() * size.precision);
  6555. height = Math.round(width / engine.getAspectRatio(camera));
  6556. size = { width: width, height: height };
  6557. }
  6558. else if (size.width && size.height) {
  6559. width = size.width;
  6560. height = size.height;
  6561. }
  6562. else if (size.width && !size.height) {
  6563. width = size.width;
  6564. height = Math.round(width / engine.getAspectRatio(camera));
  6565. size = { width: width, height: height };
  6566. }
  6567. else if (size.height && !size.width) {
  6568. height = size.height;
  6569. width = Math.round(height * engine.getAspectRatio(camera));
  6570. size = { width: width, height: height };
  6571. }
  6572. else if (!isNaN(size)) {
  6573. height = size;
  6574. width = size;
  6575. }
  6576. else {
  6577. Tools.Error("Invalid 'size' parameter !");
  6578. return;
  6579. }
  6580. var scene = camera.getScene();
  6581. var previousCamera = null;
  6582. if (scene.activeCamera !== camera) {
  6583. previousCamera = scene.activeCamera;
  6584. scene.activeCamera = camera;
  6585. }
  6586. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6587. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6588. texture.renderList = null;
  6589. texture.samples = samples;
  6590. texture.onAfterRenderObservable.add(function () {
  6591. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6592. });
  6593. scene.incrementRenderId();
  6594. scene.resetCachedMaterial();
  6595. texture.render(true);
  6596. texture.dispose();
  6597. if (previousCamera) {
  6598. scene.activeCamera = previousCamera;
  6599. }
  6600. camera.getProjectionMatrix(true); // Force cache refresh;
  6601. };
  6602. // XHR response validator for local file scenario
  6603. Tools.ValidateXHRData = function (xhr, dataType) {
  6604. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6605. if (dataType === void 0) { dataType = 7; }
  6606. try {
  6607. if (dataType & 1) {
  6608. if (xhr.responseText && xhr.responseText.length > 0) {
  6609. return true;
  6610. }
  6611. else if (dataType === 1) {
  6612. return false;
  6613. }
  6614. }
  6615. if (dataType & 2) {
  6616. // Check header width and height since there is no "TGA" magic number
  6617. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6618. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6619. return true;
  6620. }
  6621. else if (dataType === 2) {
  6622. return false;
  6623. }
  6624. }
  6625. if (dataType & 4) {
  6626. // Check for the "DDS" magic number
  6627. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6628. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6629. return true;
  6630. }
  6631. else {
  6632. return false;
  6633. }
  6634. }
  6635. }
  6636. catch (e) {
  6637. // Global protection
  6638. }
  6639. return false;
  6640. };
  6641. /**
  6642. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6643. * Be aware Math.random() could cause collisions, but:
  6644. * "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"
  6645. */
  6646. Tools.RandomId = function () {
  6647. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6648. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6649. return v.toString(16);
  6650. });
  6651. };
  6652. Object.defineProperty(Tools, "NoneLogLevel", {
  6653. get: function () {
  6654. return Tools._NoneLogLevel;
  6655. },
  6656. enumerable: true,
  6657. configurable: true
  6658. });
  6659. Object.defineProperty(Tools, "MessageLogLevel", {
  6660. get: function () {
  6661. return Tools._MessageLogLevel;
  6662. },
  6663. enumerable: true,
  6664. configurable: true
  6665. });
  6666. Object.defineProperty(Tools, "WarningLogLevel", {
  6667. get: function () {
  6668. return Tools._WarningLogLevel;
  6669. },
  6670. enumerable: true,
  6671. configurable: true
  6672. });
  6673. Object.defineProperty(Tools, "ErrorLogLevel", {
  6674. get: function () {
  6675. return Tools._ErrorLogLevel;
  6676. },
  6677. enumerable: true,
  6678. configurable: true
  6679. });
  6680. Object.defineProperty(Tools, "AllLogLevel", {
  6681. get: function () {
  6682. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6683. },
  6684. enumerable: true,
  6685. configurable: true
  6686. });
  6687. Tools._AddLogEntry = function (entry) {
  6688. Tools._LogCache = entry + Tools._LogCache;
  6689. if (Tools.OnNewCacheEntry) {
  6690. Tools.OnNewCacheEntry(entry);
  6691. }
  6692. };
  6693. Tools._FormatMessage = function (message) {
  6694. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6695. var date = new Date();
  6696. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6697. };
  6698. Tools._LogDisabled = function (message) {
  6699. // nothing to do
  6700. };
  6701. Tools._LogEnabled = function (message) {
  6702. var formattedMessage = Tools._FormatMessage(message);
  6703. console.log("BJS - " + formattedMessage);
  6704. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6705. Tools._AddLogEntry(entry);
  6706. };
  6707. Tools._WarnDisabled = function (message) {
  6708. // nothing to do
  6709. };
  6710. Tools._WarnEnabled = function (message) {
  6711. var formattedMessage = Tools._FormatMessage(message);
  6712. console.warn("BJS - " + formattedMessage);
  6713. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6714. Tools._AddLogEntry(entry);
  6715. };
  6716. Tools._ErrorDisabled = function (message) {
  6717. // nothing to do
  6718. };
  6719. Tools._ErrorEnabled = function (message) {
  6720. Tools.errorsCount++;
  6721. var formattedMessage = Tools._FormatMessage(message);
  6722. console.error("BJS - " + formattedMessage);
  6723. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6724. Tools._AddLogEntry(entry);
  6725. };
  6726. Object.defineProperty(Tools, "LogCache", {
  6727. get: function () {
  6728. return Tools._LogCache;
  6729. },
  6730. enumerable: true,
  6731. configurable: true
  6732. });
  6733. Tools.ClearLogCache = function () {
  6734. Tools._LogCache = "";
  6735. Tools.errorsCount = 0;
  6736. };
  6737. Object.defineProperty(Tools, "LogLevels", {
  6738. set: function (level) {
  6739. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6740. Tools.Log = Tools._LogEnabled;
  6741. }
  6742. else {
  6743. Tools.Log = Tools._LogDisabled;
  6744. }
  6745. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6746. Tools.Warn = Tools._WarnEnabled;
  6747. }
  6748. else {
  6749. Tools.Warn = Tools._WarnDisabled;
  6750. }
  6751. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6752. Tools.Error = Tools._ErrorEnabled;
  6753. }
  6754. else {
  6755. Tools.Error = Tools._ErrorDisabled;
  6756. }
  6757. },
  6758. enumerable: true,
  6759. configurable: true
  6760. });
  6761. Tools.IsWindowObjectExist = function () {
  6762. return (typeof window) !== "undefined";
  6763. };
  6764. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6765. get: function () {
  6766. return Tools._PerformanceNoneLogLevel;
  6767. },
  6768. enumerable: true,
  6769. configurable: true
  6770. });
  6771. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6772. get: function () {
  6773. return Tools._PerformanceUserMarkLogLevel;
  6774. },
  6775. enumerable: true,
  6776. configurable: true
  6777. });
  6778. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6779. get: function () {
  6780. return Tools._PerformanceConsoleLogLevel;
  6781. },
  6782. enumerable: true,
  6783. configurable: true
  6784. });
  6785. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6786. set: function (level) {
  6787. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6788. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6789. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6790. return;
  6791. }
  6792. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6793. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6794. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6795. return;
  6796. }
  6797. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6798. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6799. },
  6800. enumerable: true,
  6801. configurable: true
  6802. });
  6803. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6804. };
  6805. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6806. };
  6807. Tools._StartUserMark = function (counterName, condition) {
  6808. if (condition === void 0) { condition = true; }
  6809. if (!Tools._performance) {
  6810. if (!Tools.IsWindowObjectExist()) {
  6811. return;
  6812. }
  6813. Tools._performance = window.performance;
  6814. }
  6815. if (!condition || !Tools._performance.mark) {
  6816. return;
  6817. }
  6818. Tools._performance.mark(counterName + "-Begin");
  6819. };
  6820. Tools._EndUserMark = function (counterName, condition) {
  6821. if (condition === void 0) { condition = true; }
  6822. if (!condition || !Tools._performance.mark) {
  6823. return;
  6824. }
  6825. Tools._performance.mark(counterName + "-End");
  6826. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6827. };
  6828. Tools._StartPerformanceConsole = function (counterName, condition) {
  6829. if (condition === void 0) { condition = true; }
  6830. if (!condition) {
  6831. return;
  6832. }
  6833. Tools._StartUserMark(counterName, condition);
  6834. if (console.time) {
  6835. console.time(counterName);
  6836. }
  6837. };
  6838. Tools._EndPerformanceConsole = function (counterName, condition) {
  6839. if (condition === void 0) { condition = true; }
  6840. if (!condition) {
  6841. return;
  6842. }
  6843. Tools._EndUserMark(counterName, condition);
  6844. if (console.time) {
  6845. console.timeEnd(counterName);
  6846. }
  6847. };
  6848. Object.defineProperty(Tools, "Now", {
  6849. get: function () {
  6850. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6851. return window.performance.now();
  6852. }
  6853. return new Date().getTime();
  6854. },
  6855. enumerable: true,
  6856. configurable: true
  6857. });
  6858. /**
  6859. * This method will return the name of the class used to create the instance of the given object.
  6860. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6861. * @param object the object to get the class name from
  6862. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6863. */
  6864. Tools.GetClassName = function (object, isType) {
  6865. if (isType === void 0) { isType = false; }
  6866. var name = null;
  6867. if (!isType && object.getClassName) {
  6868. name = object.getClassName();
  6869. }
  6870. else {
  6871. if (object instanceof Object) {
  6872. var classObj = isType ? object : Object.getPrototypeOf(object);
  6873. name = classObj.constructor["__bjsclassName__"];
  6874. }
  6875. if (!name) {
  6876. name = typeof object;
  6877. }
  6878. }
  6879. return name;
  6880. };
  6881. Tools.First = function (array, predicate) {
  6882. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6883. var el = array_1[_i];
  6884. if (predicate(el)) {
  6885. return el;
  6886. }
  6887. }
  6888. return null;
  6889. };
  6890. /**
  6891. * This method will return the name of the full name of the class, including its owning module (if any).
  6892. * 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).
  6893. * @param object the object to get the class name from
  6894. * @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.
  6895. */
  6896. Tools.getFullClassName = function (object, isType) {
  6897. if (isType === void 0) { isType = false; }
  6898. var className = null;
  6899. var moduleName = null;
  6900. if (!isType && object.getClassName) {
  6901. className = object.getClassName();
  6902. }
  6903. else {
  6904. if (object instanceof Object) {
  6905. var classObj = isType ? object : Object.getPrototypeOf(object);
  6906. className = classObj.constructor["__bjsclassName__"];
  6907. moduleName = classObj.constructor["__bjsmoduleName__"];
  6908. }
  6909. if (!className) {
  6910. className = typeof object;
  6911. }
  6912. }
  6913. if (!className) {
  6914. return null;
  6915. }
  6916. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6917. };
  6918. /**
  6919. * 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.
  6920. * @param array
  6921. */
  6922. Tools.arrayOrStringFeeder = function (array) {
  6923. return function (index) {
  6924. if (index >= array.length) {
  6925. return null;
  6926. }
  6927. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6928. if (val && val.getHashCode) {
  6929. val = val.getHashCode();
  6930. }
  6931. if (typeof val === "string") {
  6932. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6933. }
  6934. return val;
  6935. };
  6936. };
  6937. /**
  6938. * Compute the hashCode of a stream of number
  6939. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6940. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6941. * @return the hash code computed
  6942. */
  6943. Tools.hashCodeFromStream = function (feeder) {
  6944. // Based from here: http://stackoverflow.com/a/7616484/802124
  6945. var hash = 0;
  6946. var index = 0;
  6947. var chr = feeder(index++);
  6948. while (chr != null) {
  6949. hash = ((hash << 5) - hash) + chr;
  6950. hash |= 0; // Convert to 32bit integer
  6951. chr = feeder(index++);
  6952. }
  6953. return hash;
  6954. };
  6955. Tools.BaseUrl = "";
  6956. Tools.CorsBehavior = "anonymous";
  6957. Tools.UseFallbackTexture = true;
  6958. /**
  6959. * Use this object to register external classes like custom textures or material
  6960. * to allow the laoders to instantiate them
  6961. */
  6962. Tools.RegisteredExternalClasses = {};
  6963. // Used in case of a texture loading problem
  6964. 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";
  6965. Tools.PreprocessUrl = function (url) {
  6966. return url;
  6967. };
  6968. // Logs
  6969. Tools._NoneLogLevel = 0;
  6970. Tools._MessageLogLevel = 1;
  6971. Tools._WarningLogLevel = 2;
  6972. Tools._ErrorLogLevel = 4;
  6973. Tools._LogCache = "";
  6974. Tools.errorsCount = 0;
  6975. Tools.Log = Tools._LogEnabled;
  6976. Tools.Warn = Tools._WarnEnabled;
  6977. Tools.Error = Tools._ErrorEnabled;
  6978. // Performances
  6979. Tools._PerformanceNoneLogLevel = 0;
  6980. Tools._PerformanceUserMarkLogLevel = 1;
  6981. Tools._PerformanceConsoleLogLevel = 2;
  6982. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6983. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6984. return Tools;
  6985. }());
  6986. BABYLON.Tools = Tools;
  6987. /**
  6988. * This class is used to track a performance counter which is number based.
  6989. * The user has access to many properties which give statistics of different nature
  6990. *
  6991. * The implementer can track two kinds of Performance Counter: time and count
  6992. * 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.
  6993. * 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.
  6994. */
  6995. var PerfCounter = /** @class */ (function () {
  6996. function PerfCounter() {
  6997. this._startMonitoringTime = 0;
  6998. this._min = 0;
  6999. this._max = 0;
  7000. this._average = 0;
  7001. this._lastSecAverage = 0;
  7002. this._current = 0;
  7003. this._totalValueCount = 0;
  7004. this._totalAccumulated = 0;
  7005. this._lastSecAccumulated = 0;
  7006. this._lastSecTime = 0;
  7007. this._lastSecValueCount = 0;
  7008. }
  7009. Object.defineProperty(PerfCounter.prototype, "min", {
  7010. /**
  7011. * Returns the smallest value ever
  7012. */
  7013. get: function () {
  7014. return this._min;
  7015. },
  7016. enumerable: true,
  7017. configurable: true
  7018. });
  7019. Object.defineProperty(PerfCounter.prototype, "max", {
  7020. /**
  7021. * Returns the biggest value ever
  7022. */
  7023. get: function () {
  7024. return this._max;
  7025. },
  7026. enumerable: true,
  7027. configurable: true
  7028. });
  7029. Object.defineProperty(PerfCounter.prototype, "average", {
  7030. /**
  7031. * Returns the average value since the performance counter is running
  7032. */
  7033. get: function () {
  7034. return this._average;
  7035. },
  7036. enumerable: true,
  7037. configurable: true
  7038. });
  7039. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7040. /**
  7041. * Returns the average value of the last second the counter was monitored
  7042. */
  7043. get: function () {
  7044. return this._lastSecAverage;
  7045. },
  7046. enumerable: true,
  7047. configurable: true
  7048. });
  7049. Object.defineProperty(PerfCounter.prototype, "current", {
  7050. /**
  7051. * Returns the current value
  7052. */
  7053. get: function () {
  7054. return this._current;
  7055. },
  7056. enumerable: true,
  7057. configurable: true
  7058. });
  7059. Object.defineProperty(PerfCounter.prototype, "total", {
  7060. get: function () {
  7061. return this._totalAccumulated;
  7062. },
  7063. enumerable: true,
  7064. configurable: true
  7065. });
  7066. Object.defineProperty(PerfCounter.prototype, "count", {
  7067. get: function () {
  7068. return this._totalValueCount;
  7069. },
  7070. enumerable: true,
  7071. configurable: true
  7072. });
  7073. /**
  7074. * Call this method to start monitoring a new frame.
  7075. * 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.
  7076. */
  7077. PerfCounter.prototype.fetchNewFrame = function () {
  7078. this._totalValueCount++;
  7079. this._current = 0;
  7080. this._lastSecValueCount++;
  7081. };
  7082. /**
  7083. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7084. * @param newCount the count value to add to the monitored count
  7085. * @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.
  7086. */
  7087. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7088. if (!PerfCounter.Enabled) {
  7089. return;
  7090. }
  7091. this._current += newCount;
  7092. if (fetchResult) {
  7093. this._fetchResult();
  7094. }
  7095. };
  7096. /**
  7097. * Start monitoring this performance counter
  7098. */
  7099. PerfCounter.prototype.beginMonitoring = function () {
  7100. if (!PerfCounter.Enabled) {
  7101. return;
  7102. }
  7103. this._startMonitoringTime = Tools.Now;
  7104. };
  7105. /**
  7106. * Compute the time lapsed since the previous beginMonitoring() call.
  7107. * @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
  7108. */
  7109. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7110. if (newFrame === void 0) { newFrame = true; }
  7111. if (!PerfCounter.Enabled) {
  7112. return;
  7113. }
  7114. if (newFrame) {
  7115. this.fetchNewFrame();
  7116. }
  7117. var currentTime = Tools.Now;
  7118. this._current = currentTime - this._startMonitoringTime;
  7119. if (newFrame) {
  7120. this._fetchResult();
  7121. }
  7122. };
  7123. PerfCounter.prototype._fetchResult = function () {
  7124. this._totalAccumulated += this._current;
  7125. this._lastSecAccumulated += this._current;
  7126. // Min/Max update
  7127. this._min = Math.min(this._min, this._current);
  7128. this._max = Math.max(this._max, this._current);
  7129. this._average = this._totalAccumulated / this._totalValueCount;
  7130. // Reset last sec?
  7131. var now = Tools.Now;
  7132. if ((now - this._lastSecTime) > 1000) {
  7133. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7134. this._lastSecTime = now;
  7135. this._lastSecAccumulated = 0;
  7136. this._lastSecValueCount = 0;
  7137. }
  7138. };
  7139. PerfCounter.Enabled = true;
  7140. return PerfCounter;
  7141. }());
  7142. BABYLON.PerfCounter = PerfCounter;
  7143. /**
  7144. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7145. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7146. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7147. * @param name The name of the class, case should be preserved
  7148. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7149. */
  7150. function className(name, module) {
  7151. return function (target) {
  7152. target["__bjsclassName__"] = name;
  7153. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7154. };
  7155. }
  7156. BABYLON.className = className;
  7157. /**
  7158. * An implementation of a loop for asynchronous functions.
  7159. */
  7160. var AsyncLoop = /** @class */ (function () {
  7161. /**
  7162. * Constroctor.
  7163. * @param iterations the number of iterations.
  7164. * @param _fn the function to run each iteration
  7165. * @param _successCallback the callback that will be called upon succesful execution
  7166. * @param offset starting offset.
  7167. */
  7168. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7169. if (offset === void 0) { offset = 0; }
  7170. this.iterations = iterations;
  7171. this._fn = _fn;
  7172. this._successCallback = _successCallback;
  7173. this.index = offset - 1;
  7174. this._done = false;
  7175. }
  7176. /**
  7177. * Execute the next iteration. Must be called after the last iteration was finished.
  7178. */
  7179. AsyncLoop.prototype.executeNext = function () {
  7180. if (!this._done) {
  7181. if (this.index + 1 < this.iterations) {
  7182. ++this.index;
  7183. this._fn(this);
  7184. }
  7185. else {
  7186. this.breakLoop();
  7187. }
  7188. }
  7189. };
  7190. /**
  7191. * Break the loop and run the success callback.
  7192. */
  7193. AsyncLoop.prototype.breakLoop = function () {
  7194. this._done = true;
  7195. this._successCallback();
  7196. };
  7197. /**
  7198. * Helper function
  7199. */
  7200. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7201. if (offset === void 0) { offset = 0; }
  7202. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7203. loop.executeNext();
  7204. return loop;
  7205. };
  7206. /**
  7207. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7208. * @param iterations total number of iterations
  7209. * @param syncedIterations number of synchronous iterations in each async iteration.
  7210. * @param fn the function to call each iteration.
  7211. * @param callback a success call back that will be called when iterating stops.
  7212. * @param breakFunction a break condition (optional)
  7213. * @param timeout timeout settings for the setTimeout function. default - 0.
  7214. * @constructor
  7215. */
  7216. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7217. if (timeout === void 0) { timeout = 0; }
  7218. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7219. if (breakFunction && breakFunction())
  7220. loop.breakLoop();
  7221. else {
  7222. setTimeout(function () {
  7223. for (var i = 0; i < syncedIterations; ++i) {
  7224. var iteration = (loop.index * syncedIterations) + i;
  7225. if (iteration >= iterations)
  7226. break;
  7227. fn(iteration);
  7228. if (breakFunction && breakFunction()) {
  7229. loop.breakLoop();
  7230. break;
  7231. }
  7232. }
  7233. loop.executeNext();
  7234. }, timeout);
  7235. }
  7236. }, callback);
  7237. };
  7238. return AsyncLoop;
  7239. }());
  7240. BABYLON.AsyncLoop = AsyncLoop;
  7241. })(BABYLON || (BABYLON = {}));
  7242. //# sourceMappingURL=babylon.tools.js.map
  7243. var BABYLON;
  7244. (function (BABYLON) {
  7245. var Internals;
  7246. (function (Internals) {
  7247. var _AlphaState = /** @class */ (function () {
  7248. /**
  7249. * Initializes the state.
  7250. */
  7251. function _AlphaState() {
  7252. this._isAlphaBlendDirty = false;
  7253. this._isBlendFunctionParametersDirty = false;
  7254. this._isBlendEquationParametersDirty = false;
  7255. this._isBlendConstantsDirty = false;
  7256. this._alphaBlend = false;
  7257. this._blendFunctionParameters = new Array(4);
  7258. this._blendEquationParameters = new Array(2);
  7259. this._blendConstants = new Array(4);
  7260. this.reset();
  7261. }
  7262. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7263. get: function () {
  7264. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7265. },
  7266. enumerable: true,
  7267. configurable: true
  7268. });
  7269. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7270. get: function () {
  7271. return this._alphaBlend;
  7272. },
  7273. set: function (value) {
  7274. if (this._alphaBlend === value) {
  7275. return;
  7276. }
  7277. this._alphaBlend = value;
  7278. this._isAlphaBlendDirty = true;
  7279. },
  7280. enumerable: true,
  7281. configurable: true
  7282. });
  7283. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7284. if (this._blendConstants[0] === r &&
  7285. this._blendConstants[1] === g &&
  7286. this._blendConstants[2] === b &&
  7287. this._blendConstants[3] === a) {
  7288. return;
  7289. }
  7290. this._blendConstants[0] = r;
  7291. this._blendConstants[1] = g;
  7292. this._blendConstants[2] = b;
  7293. this._blendConstants[3] = a;
  7294. this._isBlendConstantsDirty = true;
  7295. };
  7296. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7297. if (this._blendFunctionParameters[0] === value0 &&
  7298. this._blendFunctionParameters[1] === value1 &&
  7299. this._blendFunctionParameters[2] === value2 &&
  7300. this._blendFunctionParameters[3] === value3) {
  7301. return;
  7302. }
  7303. this._blendFunctionParameters[0] = value0;
  7304. this._blendFunctionParameters[1] = value1;
  7305. this._blendFunctionParameters[2] = value2;
  7306. this._blendFunctionParameters[3] = value3;
  7307. this._isBlendFunctionParametersDirty = true;
  7308. };
  7309. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7310. if (this._blendEquationParameters[0] === rgb &&
  7311. this._blendEquationParameters[1] === alpha) {
  7312. return;
  7313. }
  7314. this._blendEquationParameters[0] = rgb;
  7315. this._blendEquationParameters[1] = alpha;
  7316. this._isBlendEquationParametersDirty = true;
  7317. };
  7318. _AlphaState.prototype.reset = function () {
  7319. this._alphaBlend = false;
  7320. this._blendFunctionParameters[0] = null;
  7321. this._blendFunctionParameters[1] = null;
  7322. this._blendFunctionParameters[2] = null;
  7323. this._blendFunctionParameters[3] = null;
  7324. this._blendEquationParameters[0] = null;
  7325. this._blendEquationParameters[1] = null;
  7326. this._blendConstants[0] = null;
  7327. this._blendConstants[1] = null;
  7328. this._blendConstants[2] = null;
  7329. this._blendConstants[3] = null;
  7330. this._isAlphaBlendDirty = true;
  7331. this._isBlendFunctionParametersDirty = false;
  7332. this._isBlendEquationParametersDirty = false;
  7333. this._isBlendConstantsDirty = false;
  7334. };
  7335. _AlphaState.prototype.apply = function (gl) {
  7336. if (!this.isDirty) {
  7337. return;
  7338. }
  7339. // Alpha blend
  7340. if (this._isAlphaBlendDirty) {
  7341. if (this._alphaBlend) {
  7342. gl.enable(gl.BLEND);
  7343. }
  7344. else {
  7345. gl.disable(gl.BLEND);
  7346. }
  7347. this._isAlphaBlendDirty = false;
  7348. }
  7349. // Alpha function
  7350. if (this._isBlendFunctionParametersDirty) {
  7351. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7352. this._isBlendFunctionParametersDirty = false;
  7353. }
  7354. // Alpha equation
  7355. if (this._isBlendEquationParametersDirty) {
  7356. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7357. this._isBlendEquationParametersDirty = false;
  7358. }
  7359. // Constants
  7360. if (this._isBlendConstantsDirty) {
  7361. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7362. this._isBlendConstantsDirty = false;
  7363. }
  7364. };
  7365. return _AlphaState;
  7366. }());
  7367. Internals._AlphaState = _AlphaState;
  7368. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7369. })(BABYLON || (BABYLON = {}));
  7370. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7371. var BABYLON;
  7372. (function (BABYLON) {
  7373. var Internals;
  7374. (function (Internals) {
  7375. var _DepthCullingState = /** @class */ (function () {
  7376. /**
  7377. * Initializes the state.
  7378. */
  7379. function _DepthCullingState() {
  7380. this._isDepthTestDirty = false;
  7381. this._isDepthMaskDirty = false;
  7382. this._isDepthFuncDirty = false;
  7383. this._isCullFaceDirty = false;
  7384. this._isCullDirty = false;
  7385. this._isZOffsetDirty = false;
  7386. this.reset();
  7387. }
  7388. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7389. get: function () {
  7390. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7391. },
  7392. enumerable: true,
  7393. configurable: true
  7394. });
  7395. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7396. get: function () {
  7397. return this._zOffset;
  7398. },
  7399. set: function (value) {
  7400. if (this._zOffset === value) {
  7401. return;
  7402. }
  7403. this._zOffset = value;
  7404. this._isZOffsetDirty = true;
  7405. },
  7406. enumerable: true,
  7407. configurable: true
  7408. });
  7409. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7410. get: function () {
  7411. return this._cullFace;
  7412. },
  7413. set: function (value) {
  7414. if (this._cullFace === value) {
  7415. return;
  7416. }
  7417. this._cullFace = value;
  7418. this._isCullFaceDirty = true;
  7419. },
  7420. enumerable: true,
  7421. configurable: true
  7422. });
  7423. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7424. get: function () {
  7425. return this._cull;
  7426. },
  7427. set: function (value) {
  7428. if (this._cull === value) {
  7429. return;
  7430. }
  7431. this._cull = value;
  7432. this._isCullDirty = true;
  7433. },
  7434. enumerable: true,
  7435. configurable: true
  7436. });
  7437. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7438. get: function () {
  7439. return this._depthFunc;
  7440. },
  7441. set: function (value) {
  7442. if (this._depthFunc === value) {
  7443. return;
  7444. }
  7445. this._depthFunc = value;
  7446. this._isDepthFuncDirty = true;
  7447. },
  7448. enumerable: true,
  7449. configurable: true
  7450. });
  7451. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7452. get: function () {
  7453. return this._depthMask;
  7454. },
  7455. set: function (value) {
  7456. if (this._depthMask === value) {
  7457. return;
  7458. }
  7459. this._depthMask = value;
  7460. this._isDepthMaskDirty = true;
  7461. },
  7462. enumerable: true,
  7463. configurable: true
  7464. });
  7465. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7466. get: function () {
  7467. return this._depthTest;
  7468. },
  7469. set: function (value) {
  7470. if (this._depthTest === value) {
  7471. return;
  7472. }
  7473. this._depthTest = value;
  7474. this._isDepthTestDirty = true;
  7475. },
  7476. enumerable: true,
  7477. configurable: true
  7478. });
  7479. _DepthCullingState.prototype.reset = function () {
  7480. this._depthMask = true;
  7481. this._depthTest = true;
  7482. this._depthFunc = null;
  7483. this._cullFace = null;
  7484. this._cull = null;
  7485. this._zOffset = 0;
  7486. this._isDepthTestDirty = true;
  7487. this._isDepthMaskDirty = true;
  7488. this._isDepthFuncDirty = false;
  7489. this._isCullFaceDirty = false;
  7490. this._isCullDirty = false;
  7491. this._isZOffsetDirty = false;
  7492. };
  7493. _DepthCullingState.prototype.apply = function (gl) {
  7494. if (!this.isDirty) {
  7495. return;
  7496. }
  7497. // Cull
  7498. if (this._isCullDirty) {
  7499. if (this.cull) {
  7500. gl.enable(gl.CULL_FACE);
  7501. }
  7502. else {
  7503. gl.disable(gl.CULL_FACE);
  7504. }
  7505. this._isCullDirty = false;
  7506. }
  7507. // Cull face
  7508. if (this._isCullFaceDirty) {
  7509. gl.cullFace(this.cullFace);
  7510. this._isCullFaceDirty = false;
  7511. }
  7512. // Depth mask
  7513. if (this._isDepthMaskDirty) {
  7514. gl.depthMask(this.depthMask);
  7515. this._isDepthMaskDirty = false;
  7516. }
  7517. // Depth test
  7518. if (this._isDepthTestDirty) {
  7519. if (this.depthTest) {
  7520. gl.enable(gl.DEPTH_TEST);
  7521. }
  7522. else {
  7523. gl.disable(gl.DEPTH_TEST);
  7524. }
  7525. this._isDepthTestDirty = false;
  7526. }
  7527. // Depth func
  7528. if (this._isDepthFuncDirty) {
  7529. gl.depthFunc(this.depthFunc);
  7530. this._isDepthFuncDirty = false;
  7531. }
  7532. // zOffset
  7533. if (this._isZOffsetDirty) {
  7534. if (this.zOffset) {
  7535. gl.enable(gl.POLYGON_OFFSET_FILL);
  7536. gl.polygonOffset(this.zOffset, 0);
  7537. }
  7538. else {
  7539. gl.disable(gl.POLYGON_OFFSET_FILL);
  7540. }
  7541. this._isZOffsetDirty = false;
  7542. }
  7543. };
  7544. return _DepthCullingState;
  7545. }());
  7546. Internals._DepthCullingState = _DepthCullingState;
  7547. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7548. })(BABYLON || (BABYLON = {}));
  7549. //# sourceMappingURL=babylon.depthCullingState.js.map
  7550. var BABYLON;
  7551. (function (BABYLON) {
  7552. var Internals;
  7553. (function (Internals) {
  7554. var _StencilState = /** @class */ (function () {
  7555. function _StencilState() {
  7556. this._isStencilTestDirty = false;
  7557. this._isStencilMaskDirty = false;
  7558. this._isStencilFuncDirty = false;
  7559. this._isStencilOpDirty = false;
  7560. this.reset();
  7561. }
  7562. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7563. get: function () {
  7564. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7565. },
  7566. enumerable: true,
  7567. configurable: true
  7568. });
  7569. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7570. get: function () {
  7571. return this._stencilFunc;
  7572. },
  7573. set: function (value) {
  7574. if (this._stencilFunc === value) {
  7575. return;
  7576. }
  7577. this._stencilFunc = value;
  7578. this._isStencilFuncDirty = true;
  7579. },
  7580. enumerable: true,
  7581. configurable: true
  7582. });
  7583. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7584. get: function () {
  7585. return this._stencilFuncRef;
  7586. },
  7587. set: function (value) {
  7588. if (this._stencilFuncRef === value) {
  7589. return;
  7590. }
  7591. this._stencilFuncRef = value;
  7592. this._isStencilFuncDirty = true;
  7593. },
  7594. enumerable: true,
  7595. configurable: true
  7596. });
  7597. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7598. get: function () {
  7599. return this._stencilFuncMask;
  7600. },
  7601. set: function (value) {
  7602. if (this._stencilFuncMask === value) {
  7603. return;
  7604. }
  7605. this._stencilFuncMask = value;
  7606. this._isStencilFuncDirty = true;
  7607. },
  7608. enumerable: true,
  7609. configurable: true
  7610. });
  7611. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7612. get: function () {
  7613. return this._stencilOpStencilFail;
  7614. },
  7615. set: function (value) {
  7616. if (this._stencilOpStencilFail === value) {
  7617. return;
  7618. }
  7619. this._stencilOpStencilFail = value;
  7620. this._isStencilOpDirty = true;
  7621. },
  7622. enumerable: true,
  7623. configurable: true
  7624. });
  7625. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7626. get: function () {
  7627. return this._stencilOpDepthFail;
  7628. },
  7629. set: function (value) {
  7630. if (this._stencilOpDepthFail === value) {
  7631. return;
  7632. }
  7633. this._stencilOpDepthFail = value;
  7634. this._isStencilOpDirty = true;
  7635. },
  7636. enumerable: true,
  7637. configurable: true
  7638. });
  7639. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7640. get: function () {
  7641. return this._stencilOpStencilDepthPass;
  7642. },
  7643. set: function (value) {
  7644. if (this._stencilOpStencilDepthPass === value) {
  7645. return;
  7646. }
  7647. this._stencilOpStencilDepthPass = value;
  7648. this._isStencilOpDirty = true;
  7649. },
  7650. enumerable: true,
  7651. configurable: true
  7652. });
  7653. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7654. get: function () {
  7655. return this._stencilMask;
  7656. },
  7657. set: function (value) {
  7658. if (this._stencilMask === value) {
  7659. return;
  7660. }
  7661. this._stencilMask = value;
  7662. this._isStencilMaskDirty = true;
  7663. },
  7664. enumerable: true,
  7665. configurable: true
  7666. });
  7667. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7668. get: function () {
  7669. return this._stencilTest;
  7670. },
  7671. set: function (value) {
  7672. if (this._stencilTest === value) {
  7673. return;
  7674. }
  7675. this._stencilTest = value;
  7676. this._isStencilTestDirty = true;
  7677. },
  7678. enumerable: true,
  7679. configurable: true
  7680. });
  7681. _StencilState.prototype.reset = function () {
  7682. this._stencilTest = false;
  7683. this._stencilMask = 0xFF;
  7684. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7685. this._stencilFuncRef = 1;
  7686. this._stencilFuncMask = 0xFF;
  7687. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7688. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7689. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7690. this._isStencilTestDirty = true;
  7691. this._isStencilMaskDirty = true;
  7692. this._isStencilFuncDirty = true;
  7693. this._isStencilOpDirty = true;
  7694. };
  7695. _StencilState.prototype.apply = function (gl) {
  7696. if (!this.isDirty) {
  7697. return;
  7698. }
  7699. // Stencil test
  7700. if (this._isStencilTestDirty) {
  7701. if (this.stencilTest) {
  7702. gl.enable(gl.STENCIL_TEST);
  7703. }
  7704. else {
  7705. gl.disable(gl.STENCIL_TEST);
  7706. }
  7707. this._isStencilTestDirty = false;
  7708. }
  7709. // Stencil mask
  7710. if (this._isStencilMaskDirty) {
  7711. gl.stencilMask(this.stencilMask);
  7712. this._isStencilMaskDirty = false;
  7713. }
  7714. // Stencil func
  7715. if (this._isStencilFuncDirty) {
  7716. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7717. this._isStencilFuncDirty = false;
  7718. }
  7719. // Stencil op
  7720. if (this._isStencilOpDirty) {
  7721. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7722. this._isStencilOpDirty = false;
  7723. }
  7724. };
  7725. return _StencilState;
  7726. }());
  7727. Internals._StencilState = _StencilState;
  7728. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7729. })(BABYLON || (BABYLON = {}));
  7730. //# sourceMappingURL=babylon.stencilState.js.map
  7731. var BABYLON;
  7732. (function (BABYLON) {
  7733. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7734. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7735. };
  7736. var compileRawShader = function (gl, source, type) {
  7737. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7738. gl.shaderSource(shader, source);
  7739. gl.compileShader(shader);
  7740. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7741. var log = gl.getShaderInfoLog(shader);
  7742. if (log) {
  7743. throw new Error(log);
  7744. }
  7745. }
  7746. if (!shader) {
  7747. throw new Error("Something went wrong while compile the shader.");
  7748. }
  7749. return shader;
  7750. };
  7751. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7752. var magFilter = gl.NEAREST;
  7753. var minFilter = gl.NEAREST;
  7754. switch (samplingMode) {
  7755. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7756. magFilter = gl.LINEAR;
  7757. if (generateMipMaps) {
  7758. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7759. }
  7760. else {
  7761. minFilter = gl.LINEAR;
  7762. }
  7763. break;
  7764. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7765. magFilter = gl.LINEAR;
  7766. if (generateMipMaps) {
  7767. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7768. }
  7769. else {
  7770. minFilter = gl.LINEAR;
  7771. }
  7772. break;
  7773. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7774. magFilter = gl.NEAREST;
  7775. if (generateMipMaps) {
  7776. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7777. }
  7778. else {
  7779. minFilter = gl.NEAREST;
  7780. }
  7781. break;
  7782. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7783. magFilter = gl.NEAREST;
  7784. if (generateMipMaps) {
  7785. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7786. }
  7787. else {
  7788. minFilter = gl.NEAREST;
  7789. }
  7790. break;
  7791. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7792. magFilter = gl.NEAREST;
  7793. if (generateMipMaps) {
  7794. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7795. }
  7796. else {
  7797. minFilter = gl.LINEAR;
  7798. }
  7799. break;
  7800. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7801. magFilter = gl.NEAREST;
  7802. if (generateMipMaps) {
  7803. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7804. }
  7805. else {
  7806. minFilter = gl.LINEAR;
  7807. }
  7808. break;
  7809. case BABYLON.Texture.NEAREST_LINEAR:
  7810. magFilter = gl.NEAREST;
  7811. minFilter = gl.LINEAR;
  7812. break;
  7813. case BABYLON.Texture.NEAREST_NEAREST:
  7814. magFilter = gl.NEAREST;
  7815. minFilter = gl.NEAREST;
  7816. break;
  7817. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7818. magFilter = gl.LINEAR;
  7819. if (generateMipMaps) {
  7820. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7821. }
  7822. else {
  7823. minFilter = gl.NEAREST;
  7824. }
  7825. break;
  7826. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7827. magFilter = gl.LINEAR;
  7828. if (generateMipMaps) {
  7829. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7830. }
  7831. else {
  7832. minFilter = gl.NEAREST;
  7833. }
  7834. break;
  7835. case BABYLON.Texture.LINEAR_LINEAR:
  7836. magFilter = gl.LINEAR;
  7837. minFilter = gl.LINEAR;
  7838. break;
  7839. case BABYLON.Texture.LINEAR_NEAREST:
  7840. magFilter = gl.LINEAR;
  7841. minFilter = gl.NEAREST;
  7842. break;
  7843. }
  7844. return {
  7845. min: minFilter,
  7846. mag: magFilter
  7847. };
  7848. };
  7849. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7850. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7851. var img;
  7852. var onload = function () {
  7853. loadedImages[index] = img;
  7854. loadedImages._internalCount++;
  7855. if (scene) {
  7856. scene._removePendingData(img);
  7857. }
  7858. if (loadedImages._internalCount === 6) {
  7859. onfinish(loadedImages);
  7860. }
  7861. };
  7862. var onerror = function (message, exception) {
  7863. if (scene) {
  7864. scene._removePendingData(img);
  7865. }
  7866. if (onErrorCallBack) {
  7867. onErrorCallBack(message, exception);
  7868. }
  7869. };
  7870. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7871. if (scene) {
  7872. scene._addPendingData(img);
  7873. }
  7874. };
  7875. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7876. if (onError === void 0) { onError = null; }
  7877. var loadedImages = [];
  7878. loadedImages._internalCount = 0;
  7879. for (var index = 0; index < 6; index++) {
  7880. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7881. }
  7882. };
  7883. var BufferPointer = /** @class */ (function () {
  7884. function BufferPointer() {
  7885. }
  7886. return BufferPointer;
  7887. }());
  7888. var InstancingAttributeInfo = /** @class */ (function () {
  7889. function InstancingAttributeInfo() {
  7890. }
  7891. return InstancingAttributeInfo;
  7892. }());
  7893. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7894. /**
  7895. * Define options used to create a render target texture
  7896. */
  7897. var RenderTargetCreationOptions = /** @class */ (function () {
  7898. function RenderTargetCreationOptions() {
  7899. }
  7900. return RenderTargetCreationOptions;
  7901. }());
  7902. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7903. /**
  7904. * Regroup several parameters relative to the browser in use
  7905. */
  7906. var EngineCapabilities = /** @class */ (function () {
  7907. function EngineCapabilities() {
  7908. }
  7909. return EngineCapabilities;
  7910. }());
  7911. BABYLON.EngineCapabilities = EngineCapabilities;
  7912. /**
  7913. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7914. */
  7915. var Engine = /** @class */ (function () {
  7916. /**
  7917. * @constructor
  7918. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7919. * @param {boolean} [antialias] - enable antialias
  7920. * @param options - further options to be sent to the getContext function
  7921. */
  7922. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7923. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7924. var _this = this;
  7925. // Public members
  7926. this.forcePOTTextures = false;
  7927. this.isFullscreen = false;
  7928. this.isPointerLock = false;
  7929. this.cullBackFaces = true;
  7930. this.renderEvenInBackground = true;
  7931. this.preventCacheWipeBetweenFrames = false;
  7932. // To enable/disable IDB support and avoid XHR on .manifest
  7933. this.enableOfflineSupport = false;
  7934. this.scenes = new Array();
  7935. this.postProcesses = new Array();
  7936. // Observables
  7937. /**
  7938. * Observable event triggered each time the rendering canvas is resized
  7939. */
  7940. this.onResizeObservable = new BABYLON.Observable();
  7941. /**
  7942. * Observable event triggered each time the canvas loses focus
  7943. */
  7944. this.onCanvasBlurObservable = new BABYLON.Observable();
  7945. /**
  7946. * Observable event triggered each time the canvas gains focus
  7947. */
  7948. this.onCanvasFocusObservable = new BABYLON.Observable();
  7949. /**
  7950. * Observable event triggered each time the canvas receives pointerout event
  7951. */
  7952. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7953. /**
  7954. * Observable event triggered before each texture is initialized
  7955. */
  7956. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7957. //WebVR
  7958. this._vrDisplay = undefined;
  7959. this._vrSupported = false;
  7960. this._vrExclusivePointerMode = false;
  7961. // Uniform buffers list
  7962. this.disableUniformBuffers = false;
  7963. this._uniformBuffers = new Array();
  7964. // Observables
  7965. /**
  7966. * Observable raised when the engine begins a new frame
  7967. */
  7968. this.onBeginFrameObservable = new BABYLON.Observable();
  7969. /**
  7970. * Observable raised when the engine ends the current frame
  7971. */
  7972. this.onEndFrameObservable = new BABYLON.Observable();
  7973. /**
  7974. * Observable raised when the engine is about to compile a shader
  7975. */
  7976. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7977. /**
  7978. * Observable raised when the engine has jsut compiled a shader
  7979. */
  7980. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7981. this._windowIsBackground = false;
  7982. this._webGLVersion = 1.0;
  7983. this._badOS = false;
  7984. this._badDesktopOS = false;
  7985. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7986. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7987. this.onVRRequestPresentStart = new BABYLON.Observable();
  7988. this._colorWrite = true;
  7989. this._drawCalls = new BABYLON.PerfCounter();
  7990. this._renderingQueueLaunched = false;
  7991. this._activeRenderLoops = new Array();
  7992. // Deterministic lockstepMaxSteps
  7993. this._deterministicLockstep = false;
  7994. this._lockstepMaxSteps = 4;
  7995. // Lost context
  7996. this.onContextLostObservable = new BABYLON.Observable();
  7997. this.onContextRestoredObservable = new BABYLON.Observable();
  7998. this._contextWasLost = false;
  7999. this._doNotHandleContextLost = false;
  8000. // FPS
  8001. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8002. this._fps = 60;
  8003. this._deltaTime = 0;
  8004. /**
  8005. * Turn this value on if you want to pause FPS computation when in background
  8006. */
  8007. this.disablePerformanceMonitorInBackground = false;
  8008. // States
  8009. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  8010. this._stencilState = new BABYLON.Internals._StencilState();
  8011. this._alphaState = new BABYLON.Internals._AlphaState();
  8012. this._alphaMode = Engine.ALPHA_DISABLE;
  8013. // Cache
  8014. this._internalTexturesCache = new Array();
  8015. this._activeTexturesCache = {};
  8016. this._compiledEffects = {};
  8017. this._vertexAttribArraysEnabled = [];
  8018. this._uintIndicesCurrentlySet = false;
  8019. this._currentBoundBuffer = new Array();
  8020. this._currentBufferPointers = new Array();
  8021. this._currentInstanceLocations = new Array();
  8022. this._currentInstanceBuffers = new Array();
  8023. this._vaoRecordInProgress = false;
  8024. this._mustWipeVertexAttributes = false;
  8025. // Hardware supported Compressed Textures
  8026. this._texturesSupported = new Array();
  8027. this._onVRFullScreenTriggered = function () {
  8028. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8029. //get the old size before we change
  8030. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8031. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8032. //get the width and height, change the render size
  8033. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8034. _this.setHardwareScalingLevel(1);
  8035. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8036. }
  8037. else {
  8038. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8039. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8040. }
  8041. };
  8042. var canvas = null;
  8043. Engine.Instances.push(this);
  8044. if (!canvasOrContext) {
  8045. return;
  8046. }
  8047. options = options || {};
  8048. if (canvasOrContext.getContext) {
  8049. canvas = canvasOrContext;
  8050. this._renderingCanvas = canvas;
  8051. if (antialias != null) {
  8052. options.antialias = antialias;
  8053. }
  8054. if (options.deterministicLockstep === undefined) {
  8055. options.deterministicLockstep = false;
  8056. }
  8057. if (options.lockstepMaxSteps === undefined) {
  8058. options.lockstepMaxSteps = 4;
  8059. }
  8060. if (options.preserveDrawingBuffer === undefined) {
  8061. options.preserveDrawingBuffer = false;
  8062. }
  8063. if (options.audioEngine === undefined) {
  8064. options.audioEngine = true;
  8065. }
  8066. if (options.stencil === undefined) {
  8067. options.stencil = true;
  8068. }
  8069. this._deterministicLockstep = options.deterministicLockstep;
  8070. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8071. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8072. // GL
  8073. if (!options.disableWebGL2Support) {
  8074. try {
  8075. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8076. if (this._gl) {
  8077. this._webGLVersion = 2.0;
  8078. }
  8079. }
  8080. catch (e) {
  8081. // Do nothing
  8082. }
  8083. }
  8084. if (!this._gl) {
  8085. if (!canvas) {
  8086. throw new Error("The provided canvas is null or undefined.");
  8087. }
  8088. try {
  8089. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8090. }
  8091. catch (e) {
  8092. throw new Error("WebGL not supported");
  8093. }
  8094. }
  8095. if (!this._gl) {
  8096. throw new Error("WebGL not supported");
  8097. }
  8098. this._onCanvasFocus = function () {
  8099. _this.onCanvasFocusObservable.notifyObservers(_this);
  8100. };
  8101. this._onCanvasBlur = function () {
  8102. _this.onCanvasBlurObservable.notifyObservers(_this);
  8103. };
  8104. canvas.addEventListener("focus", this._onCanvasFocus);
  8105. canvas.addEventListener("blur", this._onCanvasBlur);
  8106. this._onBlur = function () {
  8107. if (_this.disablePerformanceMonitorInBackground) {
  8108. _this._performanceMonitor.disable();
  8109. }
  8110. _this._windowIsBackground = true;
  8111. };
  8112. this._onFocus = function () {
  8113. if (_this.disablePerformanceMonitorInBackground) {
  8114. _this._performanceMonitor.enable();
  8115. }
  8116. _this._windowIsBackground = false;
  8117. };
  8118. this._onCanvasPointerOut = function () {
  8119. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8120. };
  8121. window.addEventListener("blur", this._onBlur);
  8122. window.addEventListener("focus", this._onFocus);
  8123. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8124. // Context lost
  8125. if (!this._doNotHandleContextLost) {
  8126. this._onContextLost = function (evt) {
  8127. evt.preventDefault();
  8128. _this._contextWasLost = true;
  8129. BABYLON.Tools.Warn("WebGL context lost.");
  8130. _this.onContextLostObservable.notifyObservers(_this);
  8131. };
  8132. this._onContextRestored = function (evt) {
  8133. // Adding a timeout to avoid race condition at browser level
  8134. setTimeout(function () {
  8135. // Rebuild gl context
  8136. _this._initGLContext();
  8137. // Rebuild effects
  8138. _this._rebuildEffects();
  8139. // Rebuild textures
  8140. _this._rebuildInternalTextures();
  8141. // Rebuild buffers
  8142. _this._rebuildBuffers();
  8143. // Cache
  8144. _this.wipeCaches(true);
  8145. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8146. _this.onContextRestoredObservable.notifyObservers(_this);
  8147. _this._contextWasLost = false;
  8148. }, 0);
  8149. };
  8150. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8151. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8152. }
  8153. }
  8154. else {
  8155. this._gl = canvasOrContext;
  8156. this._renderingCanvas = this._gl.canvas;
  8157. if (this._gl.renderbufferStorageMultisample) {
  8158. this._webGLVersion = 2.0;
  8159. }
  8160. options.stencil = this._gl.getContextAttributes().stencil;
  8161. }
  8162. // Viewport
  8163. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8164. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8165. this.resize();
  8166. this._isStencilEnable = options.stencil ? true : false;
  8167. this._initGLContext();
  8168. if (canvas) {
  8169. // Fullscreen
  8170. this._onFullscreenChange = function () {
  8171. if (document.fullscreen !== undefined) {
  8172. _this.isFullscreen = document.fullscreen;
  8173. }
  8174. else if (document.mozFullScreen !== undefined) {
  8175. _this.isFullscreen = document.mozFullScreen;
  8176. }
  8177. else if (document.webkitIsFullScreen !== undefined) {
  8178. _this.isFullscreen = document.webkitIsFullScreen;
  8179. }
  8180. else if (document.msIsFullScreen !== undefined) {
  8181. _this.isFullscreen = document.msIsFullScreen;
  8182. }
  8183. // Pointer lock
  8184. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8185. canvas.requestPointerLock = canvas.requestPointerLock ||
  8186. canvas.msRequestPointerLock ||
  8187. canvas.mozRequestPointerLock ||
  8188. canvas.webkitRequestPointerLock;
  8189. if (canvas.requestPointerLock) {
  8190. canvas.requestPointerLock();
  8191. }
  8192. }
  8193. };
  8194. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8195. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8196. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8197. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8198. // Pointer lock
  8199. this._onPointerLockChange = function () {
  8200. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8201. document.webkitPointerLockElement === canvas ||
  8202. document.msPointerLockElement === canvas ||
  8203. document.pointerLockElement === canvas);
  8204. };
  8205. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8206. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8207. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8208. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8209. this._onVRDisplayPointerRestricted = function () {
  8210. if (canvas) {
  8211. canvas.requestPointerLock();
  8212. }
  8213. };
  8214. this._onVRDisplayPointerUnrestricted = function () {
  8215. document.exitPointerLock();
  8216. };
  8217. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8218. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8219. }
  8220. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8221. Engine.audioEngine = new BABYLON.AudioEngine();
  8222. }
  8223. // Prepare buffer pointers
  8224. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8225. this._currentBufferPointers[i] = new BufferPointer();
  8226. }
  8227. // Load WebVR Devices
  8228. if (options.autoEnableWebVR) {
  8229. this.initWebVR();
  8230. }
  8231. // Detect if we are running on a faulty buggy OS.
  8232. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8233. // Detect if we are running on a faulty buggy desktop OS.
  8234. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8235. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8236. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8237. }
  8238. Object.defineProperty(Engine, "LastCreatedEngine", {
  8239. get: function () {
  8240. if (Engine.Instances.length === 0) {
  8241. return null;
  8242. }
  8243. return Engine.Instances[Engine.Instances.length - 1];
  8244. },
  8245. enumerable: true,
  8246. configurable: true
  8247. });
  8248. Object.defineProperty(Engine, "LastCreatedScene", {
  8249. get: function () {
  8250. var lastCreatedEngine = Engine.LastCreatedEngine;
  8251. if (!lastCreatedEngine) {
  8252. return null;
  8253. }
  8254. if (lastCreatedEngine.scenes.length === 0) {
  8255. return null;
  8256. }
  8257. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8258. },
  8259. enumerable: true,
  8260. configurable: true
  8261. });
  8262. /**
  8263. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8264. */
  8265. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8266. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8267. var engine = Engine.Instances[engineIndex];
  8268. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8269. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8270. }
  8271. }
  8272. };
  8273. Object.defineProperty(Engine, "NEVER", {
  8274. get: function () {
  8275. return Engine._NEVER;
  8276. },
  8277. enumerable: true,
  8278. configurable: true
  8279. });
  8280. Object.defineProperty(Engine, "ALWAYS", {
  8281. get: function () {
  8282. return Engine._ALWAYS;
  8283. },
  8284. enumerable: true,
  8285. configurable: true
  8286. });
  8287. Object.defineProperty(Engine, "LESS", {
  8288. get: function () {
  8289. return Engine._LESS;
  8290. },
  8291. enumerable: true,
  8292. configurable: true
  8293. });
  8294. Object.defineProperty(Engine, "EQUAL", {
  8295. get: function () {
  8296. return Engine._EQUAL;
  8297. },
  8298. enumerable: true,
  8299. configurable: true
  8300. });
  8301. Object.defineProperty(Engine, "LEQUAL", {
  8302. get: function () {
  8303. return Engine._LEQUAL;
  8304. },
  8305. enumerable: true,
  8306. configurable: true
  8307. });
  8308. Object.defineProperty(Engine, "GREATER", {
  8309. get: function () {
  8310. return Engine._GREATER;
  8311. },
  8312. enumerable: true,
  8313. configurable: true
  8314. });
  8315. Object.defineProperty(Engine, "GEQUAL", {
  8316. get: function () {
  8317. return Engine._GEQUAL;
  8318. },
  8319. enumerable: true,
  8320. configurable: true
  8321. });
  8322. Object.defineProperty(Engine, "NOTEQUAL", {
  8323. get: function () {
  8324. return Engine._NOTEQUAL;
  8325. },
  8326. enumerable: true,
  8327. configurable: true
  8328. });
  8329. Object.defineProperty(Engine, "KEEP", {
  8330. get: function () {
  8331. return Engine._KEEP;
  8332. },
  8333. enumerable: true,
  8334. configurable: true
  8335. });
  8336. Object.defineProperty(Engine, "REPLACE", {
  8337. get: function () {
  8338. return Engine._REPLACE;
  8339. },
  8340. enumerable: true,
  8341. configurable: true
  8342. });
  8343. Object.defineProperty(Engine, "INCR", {
  8344. get: function () {
  8345. return Engine._INCR;
  8346. },
  8347. enumerable: true,
  8348. configurable: true
  8349. });
  8350. Object.defineProperty(Engine, "DECR", {
  8351. get: function () {
  8352. return Engine._DECR;
  8353. },
  8354. enumerable: true,
  8355. configurable: true
  8356. });
  8357. Object.defineProperty(Engine, "INVERT", {
  8358. get: function () {
  8359. return Engine._INVERT;
  8360. },
  8361. enumerable: true,
  8362. configurable: true
  8363. });
  8364. Object.defineProperty(Engine, "INCR_WRAP", {
  8365. get: function () {
  8366. return Engine._INCR_WRAP;
  8367. },
  8368. enumerable: true,
  8369. configurable: true
  8370. });
  8371. Object.defineProperty(Engine, "DECR_WRAP", {
  8372. get: function () {
  8373. return Engine._DECR_WRAP;
  8374. },
  8375. enumerable: true,
  8376. configurable: true
  8377. });
  8378. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8379. get: function () {
  8380. return Engine._ALPHA_DISABLE;
  8381. },
  8382. enumerable: true,
  8383. configurable: true
  8384. });
  8385. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8386. get: function () {
  8387. return Engine._ALPHA_ONEONE;
  8388. },
  8389. enumerable: true,
  8390. configurable: true
  8391. });
  8392. Object.defineProperty(Engine, "ALPHA_ADD", {
  8393. get: function () {
  8394. return Engine._ALPHA_ADD;
  8395. },
  8396. enumerable: true,
  8397. configurable: true
  8398. });
  8399. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8400. get: function () {
  8401. return Engine._ALPHA_COMBINE;
  8402. },
  8403. enumerable: true,
  8404. configurable: true
  8405. });
  8406. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8407. get: function () {
  8408. return Engine._ALPHA_SUBTRACT;
  8409. },
  8410. enumerable: true,
  8411. configurable: true
  8412. });
  8413. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8414. get: function () {
  8415. return Engine._ALPHA_MULTIPLY;
  8416. },
  8417. enumerable: true,
  8418. configurable: true
  8419. });
  8420. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8421. get: function () {
  8422. return Engine._ALPHA_MAXIMIZED;
  8423. },
  8424. enumerable: true,
  8425. configurable: true
  8426. });
  8427. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8428. get: function () {
  8429. return Engine._ALPHA_PREMULTIPLIED;
  8430. },
  8431. enumerable: true,
  8432. configurable: true
  8433. });
  8434. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8435. get: function () {
  8436. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8437. },
  8438. enumerable: true,
  8439. configurable: true
  8440. });
  8441. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8442. get: function () {
  8443. return Engine._ALPHA_INTERPOLATE;
  8444. },
  8445. enumerable: true,
  8446. configurable: true
  8447. });
  8448. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8449. get: function () {
  8450. return Engine._ALPHA_SCREENMODE;
  8451. },
  8452. enumerable: true,
  8453. configurable: true
  8454. });
  8455. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8456. get: function () {
  8457. return Engine._DELAYLOADSTATE_NONE;
  8458. },
  8459. enumerable: true,
  8460. configurable: true
  8461. });
  8462. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8463. get: function () {
  8464. return Engine._DELAYLOADSTATE_LOADED;
  8465. },
  8466. enumerable: true,
  8467. configurable: true
  8468. });
  8469. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8470. get: function () {
  8471. return Engine._DELAYLOADSTATE_LOADING;
  8472. },
  8473. enumerable: true,
  8474. configurable: true
  8475. });
  8476. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8477. get: function () {
  8478. return Engine._DELAYLOADSTATE_NOTLOADED;
  8479. },
  8480. enumerable: true,
  8481. configurable: true
  8482. });
  8483. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8484. get: function () {
  8485. return Engine._TEXTUREFORMAT_ALPHA;
  8486. },
  8487. enumerable: true,
  8488. configurable: true
  8489. });
  8490. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8491. get: function () {
  8492. return Engine._TEXTUREFORMAT_LUMINANCE;
  8493. },
  8494. enumerable: true,
  8495. configurable: true
  8496. });
  8497. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8498. get: function () {
  8499. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8500. },
  8501. enumerable: true,
  8502. configurable: true
  8503. });
  8504. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8505. get: function () {
  8506. return Engine._TEXTUREFORMAT_RGB;
  8507. },
  8508. enumerable: true,
  8509. configurable: true
  8510. });
  8511. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8512. get: function () {
  8513. return Engine._TEXTUREFORMAT_RGBA;
  8514. },
  8515. enumerable: true,
  8516. configurable: true
  8517. });
  8518. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8519. get: function () {
  8520. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8521. },
  8522. enumerable: true,
  8523. configurable: true
  8524. });
  8525. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8526. get: function () {
  8527. return Engine._TEXTURETYPE_FLOAT;
  8528. },
  8529. enumerable: true,
  8530. configurable: true
  8531. });
  8532. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8533. get: function () {
  8534. return Engine._TEXTURETYPE_HALF_FLOAT;
  8535. },
  8536. enumerable: true,
  8537. configurable: true
  8538. });
  8539. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8540. get: function () {
  8541. return Engine._SCALEMODE_FLOOR;
  8542. },
  8543. enumerable: true,
  8544. configurable: true
  8545. });
  8546. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8547. get: function () {
  8548. return Engine._SCALEMODE_NEAREST;
  8549. },
  8550. enumerable: true,
  8551. configurable: true
  8552. });
  8553. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8554. get: function () {
  8555. return Engine._SCALEMODE_CEILING;
  8556. },
  8557. enumerable: true,
  8558. configurable: true
  8559. });
  8560. Object.defineProperty(Engine, "Version", {
  8561. get: function () {
  8562. return "3.1-beta-3";
  8563. },
  8564. enumerable: true,
  8565. configurable: true
  8566. });
  8567. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8568. get: function () {
  8569. return this._vrExclusivePointerMode;
  8570. },
  8571. enumerable: true,
  8572. configurable: true
  8573. });
  8574. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8575. get: function () {
  8576. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8577. },
  8578. enumerable: true,
  8579. configurable: true
  8580. });
  8581. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8582. get: function () {
  8583. return this._webGLVersion < 2 || this.forcePOTTextures;
  8584. },
  8585. enumerable: true,
  8586. configurable: true
  8587. });
  8588. Object.defineProperty(Engine.prototype, "badOS", {
  8589. get: function () {
  8590. return this._badOS;
  8591. },
  8592. enumerable: true,
  8593. configurable: true
  8594. });
  8595. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8596. get: function () {
  8597. return this._badDesktopOS;
  8598. },
  8599. enumerable: true,
  8600. configurable: true
  8601. });
  8602. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8603. get: function () {
  8604. return this._performanceMonitor;
  8605. },
  8606. enumerable: true,
  8607. configurable: true
  8608. });
  8609. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8610. get: function () {
  8611. return this._texturesSupported;
  8612. },
  8613. enumerable: true,
  8614. configurable: true
  8615. });
  8616. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8617. get: function () {
  8618. return this._textureFormatInUse;
  8619. },
  8620. enumerable: true,
  8621. configurable: true
  8622. });
  8623. Object.defineProperty(Engine.prototype, "currentViewport", {
  8624. get: function () {
  8625. return this._cachedViewport;
  8626. },
  8627. enumerable: true,
  8628. configurable: true
  8629. });
  8630. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8631. // Empty texture
  8632. get: function () {
  8633. if (!this._emptyTexture) {
  8634. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8635. }
  8636. return this._emptyTexture;
  8637. },
  8638. enumerable: true,
  8639. configurable: true
  8640. });
  8641. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8642. get: function () {
  8643. if (!this._emptyTexture3D) {
  8644. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8645. }
  8646. return this._emptyTexture3D;
  8647. },
  8648. enumerable: true,
  8649. configurable: true
  8650. });
  8651. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8652. get: function () {
  8653. if (!this._emptyCubeTexture) {
  8654. var faceData = new Uint8Array(4);
  8655. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8656. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8657. }
  8658. return this._emptyCubeTexture;
  8659. },
  8660. enumerable: true,
  8661. configurable: true
  8662. });
  8663. Engine.prototype._rebuildInternalTextures = function () {
  8664. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8665. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8666. var internalTexture = currentState_1[_i];
  8667. internalTexture._rebuild();
  8668. }
  8669. };
  8670. Engine.prototype._rebuildEffects = function () {
  8671. for (var key in this._compiledEffects) {
  8672. var effect = this._compiledEffects[key];
  8673. effect._prepareEffect();
  8674. }
  8675. BABYLON.Effect.ResetCache();
  8676. };
  8677. Engine.prototype._rebuildBuffers = function () {
  8678. // Index / Vertex
  8679. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8680. var scene = _a[_i];
  8681. scene.resetCachedMaterial();
  8682. scene._rebuildGeometries();
  8683. scene._rebuildTextures();
  8684. }
  8685. // Uniforms
  8686. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8687. var uniformBuffer = _c[_b];
  8688. uniformBuffer._rebuild();
  8689. }
  8690. };
  8691. Engine.prototype._initGLContext = function () {
  8692. // Caps
  8693. this._caps = new EngineCapabilities();
  8694. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8695. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8696. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8697. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8698. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8699. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8700. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8701. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8702. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8703. // Infos
  8704. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8705. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8706. if (rendererInfo != null) {
  8707. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8708. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8709. }
  8710. if (!this._glVendor) {
  8711. this._glVendor = "Unknown vendor";
  8712. }
  8713. if (!this._glRenderer) {
  8714. this._glRenderer = "Unknown renderer";
  8715. }
  8716. // Constants
  8717. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8718. if (this._gl.RGBA16F !== 0x881A) {
  8719. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8720. }
  8721. if (this._gl.RGBA32F !== 0x8814) {
  8722. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8723. }
  8724. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8725. this._gl.DEPTH24_STENCIL8 = 35056;
  8726. }
  8727. // Extensions
  8728. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8729. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8730. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8731. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8732. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8733. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8734. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8735. 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');
  8736. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8737. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8738. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8739. this._caps.highPrecisionShaderSupported = true;
  8740. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8741. if (this._caps.timerQuery) {
  8742. if (this._webGLVersion === 1) {
  8743. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8744. }
  8745. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8746. }
  8747. // Checks if some of the format renders first to allow the use of webgl inspector.
  8748. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8749. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8750. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8751. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8752. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8753. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8754. if (this._webGLVersion > 1) {
  8755. this._gl.HALF_FLOAT_OES = 0x140B;
  8756. }
  8757. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8758. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8759. // Draw buffers
  8760. if (this._webGLVersion > 1) {
  8761. this._caps.drawBuffersExtension = true;
  8762. }
  8763. else {
  8764. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8765. if (drawBuffersExtension !== null) {
  8766. this._caps.drawBuffersExtension = true;
  8767. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8768. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8769. for (var i = 0; i < 16; i++) {
  8770. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8771. }
  8772. }
  8773. else {
  8774. this._caps.drawBuffersExtension = false;
  8775. }
  8776. }
  8777. // Depth Texture
  8778. if (this._webGLVersion > 1) {
  8779. this._caps.depthTextureExtension = true;
  8780. }
  8781. else {
  8782. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8783. if (depthTextureExtension != null) {
  8784. this._caps.depthTextureExtension = true;
  8785. }
  8786. }
  8787. // Vertex array object
  8788. if (this._webGLVersion > 1) {
  8789. this._caps.vertexArrayObject = true;
  8790. }
  8791. else {
  8792. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8793. if (vertexArrayObjectExtension != null) {
  8794. this._caps.vertexArrayObject = true;
  8795. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8796. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8797. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8798. }
  8799. else {
  8800. this._caps.vertexArrayObject = false;
  8801. }
  8802. }
  8803. // Instances count
  8804. if (this._webGLVersion > 1) {
  8805. this._caps.instancedArrays = true;
  8806. }
  8807. else {
  8808. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8809. if (instanceExtension != null) {
  8810. this._caps.instancedArrays = true;
  8811. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8812. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8813. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8814. }
  8815. else {
  8816. this._caps.instancedArrays = false;
  8817. }
  8818. }
  8819. // Intelligently add supported compressed formats in order to check for.
  8820. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8821. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8822. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8823. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8824. if (this._caps.astc)
  8825. this.texturesSupported.push('-astc.ktx');
  8826. if (this._caps.s3tc)
  8827. this.texturesSupported.push('-dxt.ktx');
  8828. if (this._caps.pvrtc)
  8829. this.texturesSupported.push('-pvrtc.ktx');
  8830. if (this._caps.etc2)
  8831. this.texturesSupported.push('-etc2.ktx');
  8832. if (this._caps.etc1)
  8833. this.texturesSupported.push('-etc1.ktx');
  8834. if (this._gl.getShaderPrecisionFormat) {
  8835. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8836. if (highp) {
  8837. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8838. }
  8839. }
  8840. // Depth buffer
  8841. this.setDepthBuffer(true);
  8842. this.setDepthFunctionToLessOrEqual();
  8843. this.setDepthWrite(true);
  8844. };
  8845. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8846. get: function () {
  8847. return this._webGLVersion;
  8848. },
  8849. enumerable: true,
  8850. configurable: true
  8851. });
  8852. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8853. /**
  8854. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8855. */
  8856. get: function () {
  8857. return this._isStencilEnable;
  8858. },
  8859. enumerable: true,
  8860. configurable: true
  8861. });
  8862. Engine.prototype._prepareWorkingCanvas = function () {
  8863. if (this._workingCanvas) {
  8864. return;
  8865. }
  8866. this._workingCanvas = document.createElement("canvas");
  8867. var context = this._workingCanvas.getContext("2d");
  8868. if (context) {
  8869. this._workingContext = context;
  8870. }
  8871. };
  8872. Engine.prototype.resetTextureCache = function () {
  8873. for (var key in this._activeTexturesCache) {
  8874. this._activeTexturesCache[key] = null;
  8875. }
  8876. };
  8877. Engine.prototype.isDeterministicLockStep = function () {
  8878. return this._deterministicLockstep;
  8879. };
  8880. Engine.prototype.getLockstepMaxSteps = function () {
  8881. return this._lockstepMaxSteps;
  8882. };
  8883. Engine.prototype.getGlInfo = function () {
  8884. return {
  8885. vendor: this._glVendor,
  8886. renderer: this._glRenderer,
  8887. version: this._glVersion
  8888. };
  8889. };
  8890. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8891. if (useScreen === void 0) { useScreen = false; }
  8892. var viewport = camera.viewport;
  8893. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8894. };
  8895. Engine.prototype.getRenderWidth = function (useScreen) {
  8896. if (useScreen === void 0) { useScreen = false; }
  8897. if (!useScreen && this._currentRenderTarget) {
  8898. return this._currentRenderTarget.width;
  8899. }
  8900. return this._gl.drawingBufferWidth;
  8901. };
  8902. Engine.prototype.getRenderHeight = function (useScreen) {
  8903. if (useScreen === void 0) { useScreen = false; }
  8904. if (!useScreen && this._currentRenderTarget) {
  8905. return this._currentRenderTarget.height;
  8906. }
  8907. return this._gl.drawingBufferHeight;
  8908. };
  8909. Engine.prototype.getRenderingCanvas = function () {
  8910. return this._renderingCanvas;
  8911. };
  8912. Engine.prototype.getRenderingCanvasClientRect = function () {
  8913. if (!this._renderingCanvas) {
  8914. return null;
  8915. }
  8916. return this._renderingCanvas.getBoundingClientRect();
  8917. };
  8918. Engine.prototype.setHardwareScalingLevel = function (level) {
  8919. this._hardwareScalingLevel = level;
  8920. this.resize();
  8921. };
  8922. Engine.prototype.getHardwareScalingLevel = function () {
  8923. return this._hardwareScalingLevel;
  8924. };
  8925. Engine.prototype.getLoadedTexturesCache = function () {
  8926. return this._internalTexturesCache;
  8927. };
  8928. Engine.prototype.getCaps = function () {
  8929. return this._caps;
  8930. };
  8931. Object.defineProperty(Engine.prototype, "drawCalls", {
  8932. /** The number of draw calls submitted last frame */
  8933. get: function () {
  8934. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  8935. return 0;
  8936. },
  8937. enumerable: true,
  8938. configurable: true
  8939. });
  8940. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8941. get: function () {
  8942. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  8943. return null;
  8944. },
  8945. enumerable: true,
  8946. configurable: true
  8947. });
  8948. Engine.prototype.getDepthFunction = function () {
  8949. return this._depthCullingState.depthFunc;
  8950. };
  8951. Engine.prototype.setDepthFunction = function (depthFunc) {
  8952. this._depthCullingState.depthFunc = depthFunc;
  8953. };
  8954. Engine.prototype.setDepthFunctionToGreater = function () {
  8955. this._depthCullingState.depthFunc = this._gl.GREATER;
  8956. };
  8957. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8958. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8959. };
  8960. Engine.prototype.setDepthFunctionToLess = function () {
  8961. this._depthCullingState.depthFunc = this._gl.LESS;
  8962. };
  8963. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8964. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8965. };
  8966. Engine.prototype.getStencilBuffer = function () {
  8967. return this._stencilState.stencilTest;
  8968. };
  8969. Engine.prototype.setStencilBuffer = function (enable) {
  8970. this._stencilState.stencilTest = enable;
  8971. };
  8972. Engine.prototype.getStencilMask = function () {
  8973. return this._stencilState.stencilMask;
  8974. };
  8975. Engine.prototype.setStencilMask = function (mask) {
  8976. this._stencilState.stencilMask = mask;
  8977. };
  8978. Engine.prototype.getStencilFunction = function () {
  8979. return this._stencilState.stencilFunc;
  8980. };
  8981. Engine.prototype.getStencilFunctionReference = function () {
  8982. return this._stencilState.stencilFuncRef;
  8983. };
  8984. Engine.prototype.getStencilFunctionMask = function () {
  8985. return this._stencilState.stencilFuncMask;
  8986. };
  8987. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8988. this._stencilState.stencilFunc = stencilFunc;
  8989. };
  8990. Engine.prototype.setStencilFunctionReference = function (reference) {
  8991. this._stencilState.stencilFuncRef = reference;
  8992. };
  8993. Engine.prototype.setStencilFunctionMask = function (mask) {
  8994. this._stencilState.stencilFuncMask = mask;
  8995. };
  8996. Engine.prototype.getStencilOperationFail = function () {
  8997. return this._stencilState.stencilOpStencilFail;
  8998. };
  8999. Engine.prototype.getStencilOperationDepthFail = function () {
  9000. return this._stencilState.stencilOpDepthFail;
  9001. };
  9002. Engine.prototype.getStencilOperationPass = function () {
  9003. return this._stencilState.stencilOpStencilDepthPass;
  9004. };
  9005. Engine.prototype.setStencilOperationFail = function (operation) {
  9006. this._stencilState.stencilOpStencilFail = operation;
  9007. };
  9008. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9009. this._stencilState.stencilOpDepthFail = operation;
  9010. };
  9011. Engine.prototype.setStencilOperationPass = function (operation) {
  9012. this._stencilState.stencilOpStencilDepthPass = operation;
  9013. };
  9014. Engine.prototype.setDitheringState = function (value) {
  9015. if (value) {
  9016. this._gl.enable(this._gl.DITHER);
  9017. }
  9018. else {
  9019. this._gl.disable(this._gl.DITHER);
  9020. }
  9021. };
  9022. Engine.prototype.setRasterizerState = function (value) {
  9023. if (value) {
  9024. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  9025. }
  9026. else {
  9027. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  9028. }
  9029. };
  9030. /**
  9031. * stop executing a render loop function and remove it from the execution array
  9032. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  9033. */
  9034. Engine.prototype.stopRenderLoop = function (renderFunction) {
  9035. if (!renderFunction) {
  9036. this._activeRenderLoops = [];
  9037. return;
  9038. }
  9039. var index = this._activeRenderLoops.indexOf(renderFunction);
  9040. if (index >= 0) {
  9041. this._activeRenderLoops.splice(index, 1);
  9042. }
  9043. };
  9044. Engine.prototype._renderLoop = function () {
  9045. if (!this._contextWasLost) {
  9046. var shouldRender = true;
  9047. if (!this.renderEvenInBackground && this._windowIsBackground) {
  9048. shouldRender = false;
  9049. }
  9050. if (shouldRender) {
  9051. // Start new frame
  9052. this.beginFrame();
  9053. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  9054. var renderFunction = this._activeRenderLoops[index];
  9055. renderFunction();
  9056. }
  9057. // Present
  9058. this.endFrame();
  9059. }
  9060. }
  9061. if (this._activeRenderLoops.length > 0) {
  9062. // Register new frame
  9063. var requester = null;
  9064. if (this._vrDisplay && this._vrDisplay.isPresenting)
  9065. requester = this._vrDisplay;
  9066. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  9067. }
  9068. else {
  9069. this._renderingQueueLaunched = false;
  9070. }
  9071. };
  9072. /**
  9073. * Register and execute a render loop. The engine can have more than one render function.
  9074. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  9075. * @example
  9076. * engine.runRenderLoop(function () {
  9077. * scene.render()
  9078. * })
  9079. */
  9080. Engine.prototype.runRenderLoop = function (renderFunction) {
  9081. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  9082. return;
  9083. }
  9084. this._activeRenderLoops.push(renderFunction);
  9085. if (!this._renderingQueueLaunched) {
  9086. this._renderingQueueLaunched = true;
  9087. this._bindedRenderFunction = this._renderLoop.bind(this);
  9088. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  9089. }
  9090. };
  9091. /**
  9092. * Toggle full screen mode.
  9093. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  9094. * @param {any} options - an options object to be sent to the requestFullscreen function
  9095. */
  9096. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  9097. if (this.isFullscreen) {
  9098. BABYLON.Tools.ExitFullscreen();
  9099. }
  9100. else {
  9101. this._pointerLockRequested = requestPointerLock;
  9102. if (this._renderingCanvas) {
  9103. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9104. }
  9105. }
  9106. };
  9107. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9108. if (stencil === void 0) { stencil = false; }
  9109. this.applyStates();
  9110. var mode = 0;
  9111. if (backBuffer && color) {
  9112. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9113. mode |= this._gl.COLOR_BUFFER_BIT;
  9114. }
  9115. if (depth) {
  9116. this._gl.clearDepth(1.0);
  9117. mode |= this._gl.DEPTH_BUFFER_BIT;
  9118. }
  9119. if (stencil) {
  9120. this._gl.clearStencil(0);
  9121. mode |= this._gl.STENCIL_BUFFER_BIT;
  9122. }
  9123. this._gl.clear(mode);
  9124. };
  9125. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9126. var gl = this._gl;
  9127. // Save state
  9128. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9129. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9130. // Change state
  9131. gl.enable(gl.SCISSOR_TEST);
  9132. gl.scissor(x, y, width, height);
  9133. // Clear
  9134. this.clear(clearColor, true, true, true);
  9135. // Restore state
  9136. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9137. if (curScissor === true) {
  9138. gl.enable(gl.SCISSOR_TEST);
  9139. }
  9140. else {
  9141. gl.disable(gl.SCISSOR_TEST);
  9142. }
  9143. };
  9144. /**
  9145. * Set the WebGL's viewport
  9146. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9147. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9148. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9149. */
  9150. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9151. var width = requiredWidth || this.getRenderWidth();
  9152. var height = requiredHeight || this.getRenderHeight();
  9153. var x = viewport.x || 0;
  9154. var y = viewport.y || 0;
  9155. this._cachedViewport = viewport;
  9156. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9157. };
  9158. /**
  9159. * Directly set the WebGL Viewport
  9160. * The x, y, width & height are directly passed to the WebGL call
  9161. * @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.
  9162. */
  9163. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9164. var currentViewport = this._cachedViewport;
  9165. this._cachedViewport = null;
  9166. this._gl.viewport(x, y, width, height);
  9167. return currentViewport;
  9168. };
  9169. Engine.prototype.beginFrame = function () {
  9170. this.onBeginFrameObservable.notifyObservers(this);
  9171. this._measureFps();
  9172. };
  9173. Engine.prototype.endFrame = function () {
  9174. //force a flush in case we are using a bad OS.
  9175. if (this._badOS) {
  9176. this.flushFramebuffer();
  9177. }
  9178. //submit frame to the vr device, if enabled
  9179. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9180. // TODO: We should only submit the frame if we read frameData successfully.
  9181. this._vrDisplay.submitFrame();
  9182. }
  9183. this.onEndFrameObservable.notifyObservers(this);
  9184. };
  9185. /**
  9186. * resize the view according to the canvas' size.
  9187. * @example
  9188. * window.addEventListener("resize", function () {
  9189. * engine.resize();
  9190. * });
  9191. */
  9192. Engine.prototype.resize = function () {
  9193. // We're not resizing the size of the canvas while in VR mode & presenting
  9194. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9195. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9196. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9197. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9198. }
  9199. };
  9200. /**
  9201. * force a specific size of the canvas
  9202. * @param {number} width - the new canvas' width
  9203. * @param {number} height - the new canvas' height
  9204. */
  9205. Engine.prototype.setSize = function (width, height) {
  9206. if (!this._renderingCanvas) {
  9207. return;
  9208. }
  9209. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9210. return;
  9211. }
  9212. this._renderingCanvas.width = width;
  9213. this._renderingCanvas.height = height;
  9214. for (var index = 0; index < this.scenes.length; index++) {
  9215. var scene = this.scenes[index];
  9216. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9217. var cam = scene.cameras[camIndex];
  9218. cam._currentRenderId = 0;
  9219. }
  9220. }
  9221. if (this.onResizeObservable.hasObservers) {
  9222. this.onResizeObservable.notifyObservers(this);
  9223. }
  9224. };
  9225. // WebVR functions
  9226. Engine.prototype.isVRDevicePresent = function () {
  9227. return !!this._vrDisplay;
  9228. };
  9229. Engine.prototype.getVRDevice = function () {
  9230. return this._vrDisplay;
  9231. };
  9232. Engine.prototype.initWebVR = function () {
  9233. var _this = this;
  9234. var notifyObservers = function () {
  9235. var eventArgs = {
  9236. vrDisplay: _this._vrDisplay,
  9237. vrSupported: _this._vrSupported
  9238. };
  9239. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9240. };
  9241. if (!this._onVrDisplayConnect) {
  9242. this._onVrDisplayConnect = function (event) {
  9243. _this._vrDisplay = event.display;
  9244. notifyObservers();
  9245. };
  9246. this._onVrDisplayDisconnect = function () {
  9247. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9248. _this._vrDisplay = undefined;
  9249. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9250. notifyObservers();
  9251. };
  9252. this._onVrDisplayPresentChange = function () {
  9253. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9254. };
  9255. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9256. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9257. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9258. }
  9259. this._getVRDisplays(notifyObservers);
  9260. return this.onVRDisplayChangedObservable;
  9261. };
  9262. Engine.prototype.enableVR = function () {
  9263. var _this = this;
  9264. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9265. var onResolved = function () {
  9266. _this.onVRRequestPresentComplete.notifyObservers(true);
  9267. _this._onVRFullScreenTriggered();
  9268. };
  9269. var onRejected = function () {
  9270. _this.onVRRequestPresentComplete.notifyObservers(false);
  9271. };
  9272. this.onVRRequestPresentStart.notifyObservers(this);
  9273. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9274. }
  9275. };
  9276. Engine.prototype.disableVR = function () {
  9277. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9278. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9279. }
  9280. };
  9281. Engine.prototype._getVRDisplays = function (callback) {
  9282. var _this = this;
  9283. var getWebVRDevices = function (devices) {
  9284. _this._vrSupported = true;
  9285. // note that devices may actually be an empty array. This is fine;
  9286. // we expect this._vrDisplay to be undefined in this case.
  9287. return _this._vrDisplay = devices[0];
  9288. };
  9289. if (navigator.getVRDisplays) {
  9290. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9291. // TODO: System CANNOT support WebVR, despite API presence.
  9292. _this._vrSupported = false;
  9293. callback();
  9294. });
  9295. }
  9296. else {
  9297. // TODO: Browser does not support WebVR
  9298. this._vrDisplay = undefined;
  9299. this._vrSupported = false;
  9300. callback();
  9301. }
  9302. };
  9303. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9304. if (this._currentRenderTarget) {
  9305. this.unBindFramebuffer(this._currentRenderTarget);
  9306. }
  9307. this._currentRenderTarget = texture;
  9308. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9309. var gl = this._gl;
  9310. if (texture.isCube) {
  9311. if (faceIndex === undefined) {
  9312. faceIndex = 0;
  9313. }
  9314. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9315. }
  9316. if (this._cachedViewport && !forceFullscreenViewport) {
  9317. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9318. }
  9319. else {
  9320. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9321. }
  9322. this.wipeCaches();
  9323. };
  9324. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9325. if (this._currentFramebuffer !== framebuffer) {
  9326. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9327. this._currentFramebuffer = framebuffer;
  9328. }
  9329. };
  9330. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9331. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9332. this._currentRenderTarget = null;
  9333. // If MSAA, we need to bitblt back to main texture
  9334. var gl = this._gl;
  9335. if (texture._MSAAFramebuffer) {
  9336. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9337. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9338. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9339. }
  9340. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9341. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9342. gl.generateMipmap(gl.TEXTURE_2D);
  9343. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9344. }
  9345. if (onBeforeUnbind) {
  9346. if (texture._MSAAFramebuffer) {
  9347. // Bind the correct framebuffer
  9348. this.bindUnboundFramebuffer(texture._framebuffer);
  9349. }
  9350. onBeforeUnbind();
  9351. }
  9352. this.bindUnboundFramebuffer(null);
  9353. };
  9354. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9355. if (texture.generateMipMaps) {
  9356. var gl = this._gl;
  9357. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9358. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9359. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9360. }
  9361. };
  9362. Engine.prototype.flushFramebuffer = function () {
  9363. this._gl.flush();
  9364. };
  9365. Engine.prototype.restoreDefaultFramebuffer = function () {
  9366. if (this._currentRenderTarget) {
  9367. this.unBindFramebuffer(this._currentRenderTarget);
  9368. }
  9369. else {
  9370. this.bindUnboundFramebuffer(null);
  9371. }
  9372. if (this._cachedViewport) {
  9373. this.setViewport(this._cachedViewport);
  9374. }
  9375. this.wipeCaches();
  9376. };
  9377. // UBOs
  9378. Engine.prototype.createUniformBuffer = function (elements) {
  9379. var ubo = this._gl.createBuffer();
  9380. if (!ubo) {
  9381. throw new Error("Unable to create uniform buffer");
  9382. }
  9383. this.bindUniformBuffer(ubo);
  9384. if (elements instanceof Float32Array) {
  9385. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9386. }
  9387. else {
  9388. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9389. }
  9390. this.bindUniformBuffer(null);
  9391. ubo.references = 1;
  9392. return ubo;
  9393. };
  9394. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9395. var ubo = this._gl.createBuffer();
  9396. if (!ubo) {
  9397. throw new Error("Unable to create dynamic uniform buffer");
  9398. }
  9399. this.bindUniformBuffer(ubo);
  9400. if (elements instanceof Float32Array) {
  9401. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9402. }
  9403. else {
  9404. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9405. }
  9406. this.bindUniformBuffer(null);
  9407. ubo.references = 1;
  9408. return ubo;
  9409. };
  9410. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9411. this.bindUniformBuffer(uniformBuffer);
  9412. if (offset === undefined) {
  9413. offset = 0;
  9414. }
  9415. if (count === undefined) {
  9416. if (elements instanceof Float32Array) {
  9417. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9418. }
  9419. else {
  9420. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9421. }
  9422. }
  9423. else {
  9424. if (elements instanceof Float32Array) {
  9425. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9426. }
  9427. else {
  9428. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9429. }
  9430. }
  9431. this.bindUniformBuffer(null);
  9432. };
  9433. // VBOs
  9434. Engine.prototype._resetVertexBufferBinding = function () {
  9435. this.bindArrayBuffer(null);
  9436. this._cachedVertexBuffers = null;
  9437. };
  9438. Engine.prototype.createVertexBuffer = function (vertices) {
  9439. var vbo = this._gl.createBuffer();
  9440. if (!vbo) {
  9441. throw new Error("Unable to create vertex buffer");
  9442. }
  9443. this.bindArrayBuffer(vbo);
  9444. if (vertices instanceof Float32Array) {
  9445. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9446. }
  9447. else {
  9448. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9449. }
  9450. this._resetVertexBufferBinding();
  9451. vbo.references = 1;
  9452. return vbo;
  9453. };
  9454. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9455. var vbo = this._gl.createBuffer();
  9456. if (!vbo) {
  9457. throw new Error("Unable to create dynamic vertex buffer");
  9458. }
  9459. this.bindArrayBuffer(vbo);
  9460. if (vertices instanceof Float32Array) {
  9461. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9462. }
  9463. else {
  9464. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9465. }
  9466. this._resetVertexBufferBinding();
  9467. vbo.references = 1;
  9468. return vbo;
  9469. };
  9470. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9471. if (offset === void 0) { offset = 0; }
  9472. // Force cache update
  9473. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9474. this.bindIndexBuffer(indexBuffer);
  9475. var arrayBuffer;
  9476. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9477. arrayBuffer = indices;
  9478. }
  9479. else {
  9480. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9481. }
  9482. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9483. this._resetIndexBufferBinding();
  9484. };
  9485. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9486. this.bindArrayBuffer(vertexBuffer);
  9487. if (offset === undefined) {
  9488. offset = 0;
  9489. }
  9490. if (count === undefined) {
  9491. if (vertices instanceof Float32Array) {
  9492. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9493. }
  9494. else {
  9495. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9496. }
  9497. }
  9498. else {
  9499. if (vertices instanceof Float32Array) {
  9500. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9501. }
  9502. else {
  9503. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9504. }
  9505. }
  9506. this._resetVertexBufferBinding();
  9507. };
  9508. Engine.prototype._resetIndexBufferBinding = function () {
  9509. this.bindIndexBuffer(null);
  9510. this._cachedIndexBuffer = null;
  9511. };
  9512. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9513. var vbo = this._gl.createBuffer();
  9514. if (!vbo) {
  9515. throw new Error("Unable to create index buffer");
  9516. }
  9517. this.bindIndexBuffer(vbo);
  9518. // Check for 32 bits indices
  9519. var arrayBuffer;
  9520. var need32Bits = false;
  9521. if (indices instanceof Uint16Array) {
  9522. arrayBuffer = indices;
  9523. }
  9524. else {
  9525. //check 32 bit support
  9526. if (this._caps.uintIndices) {
  9527. if (indices instanceof Uint32Array) {
  9528. arrayBuffer = indices;
  9529. need32Bits = true;
  9530. }
  9531. else {
  9532. //number[] or Int32Array, check if 32 bit is necessary
  9533. for (var index = 0; index < indices.length; index++) {
  9534. if (indices[index] > 65535) {
  9535. need32Bits = true;
  9536. break;
  9537. }
  9538. }
  9539. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9540. }
  9541. }
  9542. else {
  9543. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9544. arrayBuffer = new Uint16Array(indices);
  9545. }
  9546. }
  9547. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9548. this._resetIndexBufferBinding();
  9549. vbo.references = 1;
  9550. vbo.is32Bits = need32Bits;
  9551. return vbo;
  9552. };
  9553. Engine.prototype.bindArrayBuffer = function (buffer) {
  9554. if (!this._vaoRecordInProgress) {
  9555. this._unbindVertexArrayObject();
  9556. }
  9557. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9558. };
  9559. Engine.prototype.bindUniformBuffer = function (buffer) {
  9560. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9561. };
  9562. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9563. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9564. };
  9565. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9566. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9567. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9568. };
  9569. ;
  9570. Engine.prototype.bindIndexBuffer = function (buffer) {
  9571. if (!this._vaoRecordInProgress) {
  9572. this._unbindVertexArrayObject();
  9573. }
  9574. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9575. };
  9576. Engine.prototype.bindBuffer = function (buffer, target) {
  9577. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9578. this._gl.bindBuffer(target, buffer);
  9579. this._currentBoundBuffer[target] = buffer;
  9580. }
  9581. };
  9582. Engine.prototype.updateArrayBuffer = function (data) {
  9583. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9584. };
  9585. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9586. var pointer = this._currentBufferPointers[indx];
  9587. var changed = false;
  9588. if (!pointer.active) {
  9589. changed = true;
  9590. pointer.active = true;
  9591. pointer.index = indx;
  9592. pointer.size = size;
  9593. pointer.type = type;
  9594. pointer.normalized = normalized;
  9595. pointer.stride = stride;
  9596. pointer.offset = offset;
  9597. pointer.buffer = buffer;
  9598. }
  9599. else {
  9600. if (pointer.buffer !== buffer) {
  9601. pointer.buffer = buffer;
  9602. changed = true;
  9603. }
  9604. if (pointer.size !== size) {
  9605. pointer.size = size;
  9606. changed = true;
  9607. }
  9608. if (pointer.type !== type) {
  9609. pointer.type = type;
  9610. changed = true;
  9611. }
  9612. if (pointer.normalized !== normalized) {
  9613. pointer.normalized = normalized;
  9614. changed = true;
  9615. }
  9616. if (pointer.stride !== stride) {
  9617. pointer.stride = stride;
  9618. changed = true;
  9619. }
  9620. if (pointer.offset !== offset) {
  9621. pointer.offset = offset;
  9622. changed = true;
  9623. }
  9624. }
  9625. if (changed || this._vaoRecordInProgress) {
  9626. this.bindArrayBuffer(buffer);
  9627. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9628. }
  9629. };
  9630. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9631. if (indexBuffer == null) {
  9632. return;
  9633. }
  9634. if (this._cachedIndexBuffer !== indexBuffer) {
  9635. this._cachedIndexBuffer = indexBuffer;
  9636. this.bindIndexBuffer(indexBuffer);
  9637. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9638. }
  9639. };
  9640. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9641. var attributes = effect.getAttributesNames();
  9642. if (!this._vaoRecordInProgress) {
  9643. this._unbindVertexArrayObject();
  9644. }
  9645. this.unbindAllAttributes();
  9646. for (var index = 0; index < attributes.length; index++) {
  9647. var order = effect.getAttributeLocation(index);
  9648. if (order >= 0) {
  9649. var vertexBuffer = vertexBuffers[attributes[index]];
  9650. if (!vertexBuffer) {
  9651. continue;
  9652. }
  9653. this._gl.enableVertexAttribArray(order);
  9654. if (!this._vaoRecordInProgress) {
  9655. this._vertexAttribArraysEnabled[order] = true;
  9656. }
  9657. var buffer = vertexBuffer.getBuffer();
  9658. if (buffer) {
  9659. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9660. if (vertexBuffer.getIsInstanced()) {
  9661. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9662. if (!this._vaoRecordInProgress) {
  9663. this._currentInstanceLocations.push(order);
  9664. this._currentInstanceBuffers.push(buffer);
  9665. }
  9666. }
  9667. }
  9668. }
  9669. }
  9670. };
  9671. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9672. var vao = this._gl.createVertexArray();
  9673. this._vaoRecordInProgress = true;
  9674. this._gl.bindVertexArray(vao);
  9675. this._mustWipeVertexAttributes = true;
  9676. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9677. this.bindIndexBuffer(indexBuffer);
  9678. this._vaoRecordInProgress = false;
  9679. this._gl.bindVertexArray(null);
  9680. return vao;
  9681. };
  9682. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9683. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9684. this._cachedVertexArrayObject = vertexArrayObject;
  9685. this._gl.bindVertexArray(vertexArrayObject);
  9686. this._cachedVertexBuffers = null;
  9687. this._cachedIndexBuffer = null;
  9688. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9689. this._mustWipeVertexAttributes = true;
  9690. }
  9691. };
  9692. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9693. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9694. this._cachedVertexBuffers = vertexBuffer;
  9695. this._cachedEffectForVertexBuffers = effect;
  9696. var attributesCount = effect.getAttributesCount();
  9697. this._unbindVertexArrayObject();
  9698. this.unbindAllAttributes();
  9699. var offset = 0;
  9700. for (var index = 0; index < attributesCount; index++) {
  9701. if (index < vertexDeclaration.length) {
  9702. var order = effect.getAttributeLocation(index);
  9703. if (order >= 0) {
  9704. this._gl.enableVertexAttribArray(order);
  9705. this._vertexAttribArraysEnabled[order] = true;
  9706. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9707. }
  9708. offset += vertexDeclaration[index] * 4;
  9709. }
  9710. }
  9711. }
  9712. this._bindIndexBufferWithCache(indexBuffer);
  9713. };
  9714. Engine.prototype._unbindVertexArrayObject = function () {
  9715. if (!this._cachedVertexArrayObject) {
  9716. return;
  9717. }
  9718. this._cachedVertexArrayObject = null;
  9719. this._gl.bindVertexArray(null);
  9720. };
  9721. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9722. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9723. this._cachedVertexBuffers = vertexBuffers;
  9724. this._cachedEffectForVertexBuffers = effect;
  9725. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9726. }
  9727. this._bindIndexBufferWithCache(indexBuffer);
  9728. };
  9729. Engine.prototype.unbindInstanceAttributes = function () {
  9730. var boundBuffer;
  9731. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9732. var instancesBuffer = this._currentInstanceBuffers[i];
  9733. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9734. boundBuffer = instancesBuffer;
  9735. this.bindArrayBuffer(instancesBuffer);
  9736. }
  9737. var offsetLocation = this._currentInstanceLocations[i];
  9738. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9739. }
  9740. this._currentInstanceBuffers.length = 0;
  9741. this._currentInstanceLocations.length = 0;
  9742. };
  9743. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9744. this._gl.deleteVertexArray(vao);
  9745. };
  9746. Engine.prototype._releaseBuffer = function (buffer) {
  9747. buffer.references--;
  9748. if (buffer.references === 0) {
  9749. this._gl.deleteBuffer(buffer);
  9750. return true;
  9751. }
  9752. return false;
  9753. };
  9754. Engine.prototype.createInstancesBuffer = function (capacity) {
  9755. var buffer = this._gl.createBuffer();
  9756. if (!buffer) {
  9757. throw new Error("Unable to create instance buffer");
  9758. }
  9759. buffer.capacity = capacity;
  9760. this.bindArrayBuffer(buffer);
  9761. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9762. return buffer;
  9763. };
  9764. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9765. this._gl.deleteBuffer(buffer);
  9766. };
  9767. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9768. this.bindArrayBuffer(instancesBuffer);
  9769. if (data) {
  9770. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9771. }
  9772. if (offsetLocations[0].index !== undefined) {
  9773. var stride = 0;
  9774. for (var i = 0; i < offsetLocations.length; i++) {
  9775. var ai = offsetLocations[i];
  9776. stride += ai.attributeSize * 4;
  9777. }
  9778. for (var i = 0; i < offsetLocations.length; i++) {
  9779. var ai = offsetLocations[i];
  9780. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9781. this._gl.enableVertexAttribArray(ai.index);
  9782. this._vertexAttribArraysEnabled[ai.index] = true;
  9783. }
  9784. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9785. this._gl.vertexAttribDivisor(ai.index, 1);
  9786. this._currentInstanceLocations.push(ai.index);
  9787. this._currentInstanceBuffers.push(instancesBuffer);
  9788. }
  9789. }
  9790. else {
  9791. for (var index = 0; index < 4; index++) {
  9792. var offsetLocation = offsetLocations[index];
  9793. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9794. this._gl.enableVertexAttribArray(offsetLocation);
  9795. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9796. }
  9797. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9798. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9799. this._currentInstanceLocations.push(offsetLocation);
  9800. this._currentInstanceBuffers.push(instancesBuffer);
  9801. }
  9802. }
  9803. };
  9804. Engine.prototype.applyStates = function () {
  9805. this._depthCullingState.apply(this._gl);
  9806. this._stencilState.apply(this._gl);
  9807. this._alphaState.apply(this._gl);
  9808. };
  9809. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9810. // Apply states
  9811. this.applyStates();
  9812. this._drawCalls.addCount(1, false);
  9813. // Render
  9814. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9815. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9816. if (instancesCount) {
  9817. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9818. return;
  9819. }
  9820. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9821. };
  9822. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9823. // Apply states
  9824. this.applyStates();
  9825. this._drawCalls.addCount(1, false);
  9826. if (instancesCount) {
  9827. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9828. return;
  9829. }
  9830. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9831. };
  9832. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9833. // Apply states
  9834. this.applyStates();
  9835. this._drawCalls.addCount(1, false);
  9836. if (instancesCount) {
  9837. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9838. return;
  9839. }
  9840. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9841. };
  9842. // Shaders
  9843. Engine.prototype._releaseEffect = function (effect) {
  9844. if (this._compiledEffects[effect._key]) {
  9845. delete this._compiledEffects[effect._key];
  9846. this._deleteProgram(effect.getProgram());
  9847. }
  9848. };
  9849. Engine.prototype._deleteProgram = function (program) {
  9850. if (program) {
  9851. program.__SPECTOR_rebuildProgram = null;
  9852. if (program.transformFeedback) {
  9853. this.deleteTransformFeedback(program.transformFeedback);
  9854. program.transformFeedback = null;
  9855. }
  9856. this._gl.deleteProgram(program);
  9857. }
  9858. };
  9859. /**
  9860. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9861. * @param samplers An array of string used to represent textures
  9862. */
  9863. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9864. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9865. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9866. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9867. if (this._compiledEffects[name]) {
  9868. var compiledEffect = this._compiledEffects[name];
  9869. if (onCompiled && compiledEffect.isReady()) {
  9870. onCompiled(compiledEffect);
  9871. }
  9872. return compiledEffect;
  9873. }
  9874. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9875. effect._key = name;
  9876. this._compiledEffects[name] = effect;
  9877. return effect;
  9878. };
  9879. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9880. if (uniformsNames === void 0) { uniformsNames = []; }
  9881. if (samplers === void 0) { samplers = []; }
  9882. if (defines === void 0) { defines = ""; }
  9883. return this.createEffect({
  9884. vertex: "particles",
  9885. fragmentElement: fragmentName
  9886. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9887. };
  9888. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9889. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9890. context = context || this._gl;
  9891. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9892. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9893. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9894. };
  9895. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9896. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9897. context = context || this._gl;
  9898. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9899. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9900. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9901. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9902. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9903. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9904. return program;
  9905. };
  9906. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  9907. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9908. var shaderProgram = context.createProgram();
  9909. if (!shaderProgram) {
  9910. throw new Error("Unable to create program");
  9911. }
  9912. context.attachShader(shaderProgram, vertexShader);
  9913. context.attachShader(shaderProgram, fragmentShader);
  9914. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9915. var transformFeedback = this.createTransformFeedback();
  9916. this.bindTransformFeedback(transformFeedback);
  9917. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  9918. shaderProgram.transformFeedback = transformFeedback;
  9919. }
  9920. context.linkProgram(shaderProgram);
  9921. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9922. this.bindTransformFeedback(null);
  9923. }
  9924. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9925. if (!linked) {
  9926. context.validateProgram(shaderProgram);
  9927. var error = context.getProgramInfoLog(shaderProgram);
  9928. if (error) {
  9929. throw new Error(error);
  9930. }
  9931. }
  9932. context.deleteShader(vertexShader);
  9933. context.deleteShader(fragmentShader);
  9934. return shaderProgram;
  9935. };
  9936. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9937. var results = new Array();
  9938. for (var index = 0; index < uniformsNames.length; index++) {
  9939. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9940. }
  9941. return results;
  9942. };
  9943. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9944. var results = [];
  9945. for (var index = 0; index < attributesNames.length; index++) {
  9946. try {
  9947. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9948. }
  9949. catch (e) {
  9950. results.push(-1);
  9951. }
  9952. }
  9953. return results;
  9954. };
  9955. Engine.prototype.enableEffect = function (effect) {
  9956. if (!effect) {
  9957. return;
  9958. }
  9959. // Use program
  9960. this.setProgram(effect.getProgram());
  9961. this._currentEffect = effect;
  9962. if (effect.onBind) {
  9963. effect.onBind(effect);
  9964. }
  9965. effect.onBindObservable.notifyObservers(effect);
  9966. };
  9967. Engine.prototype.setIntArray = function (uniform, array) {
  9968. if (!uniform)
  9969. return;
  9970. this._gl.uniform1iv(uniform, array);
  9971. };
  9972. Engine.prototype.setIntArray2 = function (uniform, array) {
  9973. if (!uniform || array.length % 2 !== 0)
  9974. return;
  9975. this._gl.uniform2iv(uniform, array);
  9976. };
  9977. Engine.prototype.setIntArray3 = function (uniform, array) {
  9978. if (!uniform || array.length % 3 !== 0)
  9979. return;
  9980. this._gl.uniform3iv(uniform, array);
  9981. };
  9982. Engine.prototype.setIntArray4 = function (uniform, array) {
  9983. if (!uniform || array.length % 4 !== 0)
  9984. return;
  9985. this._gl.uniform4iv(uniform, array);
  9986. };
  9987. Engine.prototype.setFloatArray = function (uniform, array) {
  9988. if (!uniform)
  9989. return;
  9990. this._gl.uniform1fv(uniform, array);
  9991. };
  9992. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9993. if (!uniform || array.length % 2 !== 0)
  9994. return;
  9995. this._gl.uniform2fv(uniform, array);
  9996. };
  9997. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9998. if (!uniform || array.length % 3 !== 0)
  9999. return;
  10000. this._gl.uniform3fv(uniform, array);
  10001. };
  10002. Engine.prototype.setFloatArray4 = function (uniform, array) {
  10003. if (!uniform || array.length % 4 !== 0)
  10004. return;
  10005. this._gl.uniform4fv(uniform, array);
  10006. };
  10007. Engine.prototype.setArray = function (uniform, array) {
  10008. if (!uniform)
  10009. return;
  10010. this._gl.uniform1fv(uniform, array);
  10011. };
  10012. Engine.prototype.setArray2 = function (uniform, array) {
  10013. if (!uniform || array.length % 2 !== 0)
  10014. return;
  10015. this._gl.uniform2fv(uniform, array);
  10016. };
  10017. Engine.prototype.setArray3 = function (uniform, array) {
  10018. if (!uniform || array.length % 3 !== 0)
  10019. return;
  10020. this._gl.uniform3fv(uniform, array);
  10021. };
  10022. Engine.prototype.setArray4 = function (uniform, array) {
  10023. if (!uniform || array.length % 4 !== 0)
  10024. return;
  10025. this._gl.uniform4fv(uniform, array);
  10026. };
  10027. Engine.prototype.setMatrices = function (uniform, matrices) {
  10028. if (!uniform)
  10029. return;
  10030. this._gl.uniformMatrix4fv(uniform, false, matrices);
  10031. };
  10032. Engine.prototype.setMatrix = function (uniform, matrix) {
  10033. if (!uniform)
  10034. return;
  10035. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  10036. };
  10037. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  10038. if (!uniform)
  10039. return;
  10040. this._gl.uniformMatrix3fv(uniform, false, matrix);
  10041. };
  10042. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  10043. if (!uniform)
  10044. return;
  10045. this._gl.uniformMatrix2fv(uniform, false, matrix);
  10046. };
  10047. Engine.prototype.setFloat = function (uniform, value) {
  10048. if (!uniform)
  10049. return;
  10050. this._gl.uniform1f(uniform, value);
  10051. };
  10052. Engine.prototype.setFloat2 = function (uniform, x, y) {
  10053. if (!uniform)
  10054. return;
  10055. this._gl.uniform2f(uniform, x, y);
  10056. };
  10057. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  10058. if (!uniform)
  10059. return;
  10060. this._gl.uniform3f(uniform, x, y, z);
  10061. };
  10062. Engine.prototype.setBool = function (uniform, bool) {
  10063. if (!uniform)
  10064. return;
  10065. this._gl.uniform1i(uniform, bool);
  10066. };
  10067. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  10068. if (!uniform)
  10069. return;
  10070. this._gl.uniform4f(uniform, x, y, z, w);
  10071. };
  10072. Engine.prototype.setColor3 = function (uniform, color3) {
  10073. if (!uniform)
  10074. return;
  10075. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  10076. };
  10077. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  10078. if (!uniform)
  10079. return;
  10080. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  10081. };
  10082. // States
  10083. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  10084. if (zOffset === void 0) { zOffset = 0; }
  10085. if (reverseSide === void 0) { reverseSide = false; }
  10086. // Culling
  10087. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  10088. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  10089. var cullFace = this.cullBackFaces ? showSide : hideSide;
  10090. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  10091. if (culling) {
  10092. this._depthCullingState.cullFace = cullFace;
  10093. this._depthCullingState.cull = true;
  10094. }
  10095. else {
  10096. this._depthCullingState.cull = false;
  10097. }
  10098. }
  10099. // Z offset
  10100. this.setZOffset(zOffset);
  10101. };
  10102. Engine.prototype.setZOffset = function (value) {
  10103. this._depthCullingState.zOffset = value;
  10104. };
  10105. Engine.prototype.getZOffset = function () {
  10106. return this._depthCullingState.zOffset;
  10107. };
  10108. Engine.prototype.setDepthBuffer = function (enable) {
  10109. this._depthCullingState.depthTest = enable;
  10110. };
  10111. Engine.prototype.getDepthWrite = function () {
  10112. return this._depthCullingState.depthMask;
  10113. };
  10114. Engine.prototype.setDepthWrite = function (enable) {
  10115. this._depthCullingState.depthMask = enable;
  10116. };
  10117. Engine.prototype.setColorWrite = function (enable) {
  10118. this._gl.colorMask(enable, enable, enable, enable);
  10119. this._colorWrite = enable;
  10120. };
  10121. Engine.prototype.getColorWrite = function () {
  10122. return this._colorWrite;
  10123. };
  10124. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10125. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10126. };
  10127. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10128. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10129. if (this._alphaMode === mode) {
  10130. return;
  10131. }
  10132. switch (mode) {
  10133. case Engine.ALPHA_DISABLE:
  10134. this._alphaState.alphaBlend = false;
  10135. break;
  10136. case Engine.ALPHA_PREMULTIPLIED:
  10137. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10138. this._alphaState.alphaBlend = true;
  10139. break;
  10140. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10141. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10142. this._alphaState.alphaBlend = true;
  10143. break;
  10144. case Engine.ALPHA_COMBINE:
  10145. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10146. this._alphaState.alphaBlend = true;
  10147. break;
  10148. case Engine.ALPHA_ONEONE:
  10149. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10150. this._alphaState.alphaBlend = true;
  10151. break;
  10152. case Engine.ALPHA_ADD:
  10153. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10154. this._alphaState.alphaBlend = true;
  10155. break;
  10156. case Engine.ALPHA_SUBTRACT:
  10157. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10158. this._alphaState.alphaBlend = true;
  10159. break;
  10160. case Engine.ALPHA_MULTIPLY:
  10161. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10162. this._alphaState.alphaBlend = true;
  10163. break;
  10164. case Engine.ALPHA_MAXIMIZED:
  10165. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10166. this._alphaState.alphaBlend = true;
  10167. break;
  10168. case Engine.ALPHA_INTERPOLATE:
  10169. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10170. this._alphaState.alphaBlend = true;
  10171. break;
  10172. case Engine.ALPHA_SCREENMODE:
  10173. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10174. this._alphaState.alphaBlend = true;
  10175. break;
  10176. }
  10177. if (!noDepthWriteChange) {
  10178. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10179. }
  10180. this._alphaMode = mode;
  10181. };
  10182. Engine.prototype.getAlphaMode = function () {
  10183. return this._alphaMode;
  10184. };
  10185. Engine.prototype.setAlphaTesting = function (enable) {
  10186. this._alphaTest = enable;
  10187. };
  10188. Engine.prototype.getAlphaTesting = function () {
  10189. return !!this._alphaTest;
  10190. };
  10191. // Textures
  10192. Engine.prototype.wipeCaches = function (bruteForce) {
  10193. if (this.preventCacheWipeBetweenFrames) {
  10194. return;
  10195. }
  10196. this.resetTextureCache();
  10197. this._currentEffect = null;
  10198. // 6/8/2017: deltakosh: Should not be required anymore.
  10199. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10200. if (bruteForce) {
  10201. this._currentProgram = null;
  10202. this._stencilState.reset();
  10203. this._depthCullingState.reset();
  10204. this.setDepthFunctionToLessOrEqual();
  10205. this._alphaState.reset();
  10206. }
  10207. this._cachedVertexBuffers = null;
  10208. this._cachedIndexBuffer = null;
  10209. this._cachedEffectForVertexBuffers = null;
  10210. this._unbindVertexArrayObject();
  10211. this.bindIndexBuffer(null);
  10212. this.bindArrayBuffer(null);
  10213. };
  10214. /**
  10215. * Set the compressed texture format to use, based on the formats you have, and the formats
  10216. * supported by the hardware / browser.
  10217. *
  10218. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10219. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10220. * to API arguments needed to compressed textures. This puts the burden on the container
  10221. * generator to house the arcane code for determining these for current & future formats.
  10222. *
  10223. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10224. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10225. *
  10226. * Note: The result of this call is not taken into account when a texture is base64.
  10227. *
  10228. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10229. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10230. *
  10231. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10232. * @returns The extension selected.
  10233. */
  10234. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10235. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10236. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10237. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10238. return this._textureFormatInUse = this._texturesSupported[i];
  10239. }
  10240. }
  10241. }
  10242. // actively set format to nothing, to allow this to be called more than once
  10243. // and possibly fail the 2nd time
  10244. this._textureFormatInUse = null;
  10245. return null;
  10246. };
  10247. Engine.prototype._createTexture = function () {
  10248. var texture = this._gl.createTexture();
  10249. if (!texture) {
  10250. throw new Error("Unable to create texture");
  10251. }
  10252. return texture;
  10253. };
  10254. /**
  10255. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10256. * @param {string} urlArg- This contains one of the following:
  10257. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10258. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10259. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10260. *
  10261. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10262. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10263. * @param {Scene} scene- Needed for loading to the correct scene.
  10264. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10265. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10266. * @param {callback} onError- Optional callback to be called upon failure.
  10267. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10268. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10269. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10270. *
  10271. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10272. */
  10273. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10274. var _this = this;
  10275. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10276. if (onLoad === void 0) { onLoad = null; }
  10277. if (onError === void 0) { onError = null; }
  10278. if (buffer === void 0) { buffer = null; }
  10279. if (fallBack === void 0) { fallBack = null; }
  10280. if (format === void 0) { format = null; }
  10281. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10282. var fromData = url.substr(0, 5) === "data:";
  10283. var fromBlob = url.substr(0, 5) === "blob:";
  10284. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10285. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10286. // establish the file extension, if possible
  10287. var lastDot = url.lastIndexOf('.');
  10288. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10289. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10290. var isTGA = (extension === ".tga");
  10291. // determine if a ktx file should be substituted
  10292. var isKTX = false;
  10293. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10294. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10295. isKTX = true;
  10296. }
  10297. if (scene) {
  10298. scene._addPendingData(texture);
  10299. }
  10300. texture.url = url;
  10301. texture.generateMipMaps = !noMipmap;
  10302. texture.samplingMode = samplingMode;
  10303. texture.invertY = invertY;
  10304. if (!this._doNotHandleContextLost) {
  10305. // Keep a link to the buffer only if we plan to handle context lost
  10306. texture._buffer = buffer;
  10307. }
  10308. if (onLoad) {
  10309. texture.onLoadedObservable.add(onLoad);
  10310. }
  10311. if (!fallBack)
  10312. this._internalTexturesCache.push(texture);
  10313. var onerror = function () {
  10314. if (scene) {
  10315. scene._removePendingData(texture);
  10316. }
  10317. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10318. if (isKTX) {
  10319. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10320. }
  10321. else if ((isTGA || isDDS) && BABYLON.Tools.UseFallbackTexture) {
  10322. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10323. }
  10324. else if (onError) {
  10325. onError();
  10326. }
  10327. };
  10328. var callback = null;
  10329. // processing for non-image formats
  10330. if (isKTX || isTGA || isDDS) {
  10331. if (isKTX) {
  10332. callback = function (data) {
  10333. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10334. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10335. ktx.uploadLevels(_this._gl, !noMipmap);
  10336. return false;
  10337. }, samplingMode);
  10338. };
  10339. }
  10340. else if (isTGA) {
  10341. callback = function (arrayBuffer) {
  10342. var data = new Uint8Array(arrayBuffer);
  10343. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10344. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10345. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10346. return false;
  10347. }, samplingMode);
  10348. };
  10349. }
  10350. else if (isDDS) {
  10351. callback = function (data) {
  10352. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10353. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10354. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10355. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10356. return false;
  10357. }, samplingMode);
  10358. };
  10359. }
  10360. if (!buffer) {
  10361. BABYLON.Tools.LoadFile(url, function (data) {
  10362. if (callback) {
  10363. callback(data);
  10364. }
  10365. }, undefined, scene ? scene.database : undefined, true, onerror);
  10366. }
  10367. else {
  10368. if (callback) {
  10369. callback(buffer);
  10370. }
  10371. }
  10372. // image format processing
  10373. }
  10374. else {
  10375. var onload = function (img) {
  10376. if (fromBlob && !_this._doNotHandleContextLost) {
  10377. // We need to store the image if we need to rebuild the texture
  10378. // in case of a webgl context lost
  10379. texture._buffer = img;
  10380. }
  10381. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10382. var gl = _this._gl;
  10383. var isPot = (img.width === potWidth && img.height === potHeight);
  10384. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10385. if (isPot) {
  10386. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10387. return false;
  10388. }
  10389. // Using shaders to rescale because canvas.drawImage is lossy
  10390. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10391. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10392. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10393. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10394. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10395. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10396. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10397. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10398. _this._releaseTexture(source);
  10399. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10400. continuationCallback();
  10401. });
  10402. return true;
  10403. }, samplingMode);
  10404. };
  10405. if (!fromData || isBase64)
  10406. if (buffer instanceof HTMLImageElement) {
  10407. onload(buffer);
  10408. }
  10409. else {
  10410. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10411. }
  10412. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10413. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10414. else
  10415. onload(buffer);
  10416. }
  10417. return texture;
  10418. };
  10419. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10420. var _this = this;
  10421. var rtt = this.createRenderTargetTexture({
  10422. width: destination.width,
  10423. height: destination.height,
  10424. }, {
  10425. generateMipMaps: false,
  10426. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10427. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10428. generateDepthBuffer: false,
  10429. generateStencilBuffer: false
  10430. });
  10431. if (!this._rescalePostProcess) {
  10432. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10433. }
  10434. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10435. _this._rescalePostProcess.onApply = function (effect) {
  10436. effect._bindTexture("textureSampler", source);
  10437. };
  10438. var hostingScene = scene;
  10439. if (!hostingScene) {
  10440. hostingScene = _this.scenes[_this.scenes.length - 1];
  10441. }
  10442. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10443. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10444. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10445. _this.unBindFramebuffer(rtt);
  10446. _this._releaseTexture(rtt);
  10447. if (onComplete) {
  10448. onComplete();
  10449. }
  10450. });
  10451. };
  10452. Engine.prototype._getInternalFormat = function (format) {
  10453. var internalFormat = this._gl.RGBA;
  10454. switch (format) {
  10455. case Engine.TEXTUREFORMAT_ALPHA:
  10456. internalFormat = this._gl.ALPHA;
  10457. break;
  10458. case Engine.TEXTUREFORMAT_LUMINANCE:
  10459. internalFormat = this._gl.LUMINANCE;
  10460. break;
  10461. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10462. internalFormat = this._gl.LUMINANCE_ALPHA;
  10463. break;
  10464. case Engine.TEXTUREFORMAT_RGB:
  10465. internalFormat = this._gl.RGB;
  10466. break;
  10467. case Engine.TEXTUREFORMAT_RGBA:
  10468. internalFormat = this._gl.RGBA;
  10469. break;
  10470. }
  10471. return internalFormat;
  10472. };
  10473. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10474. if (compression === void 0) { compression = null; }
  10475. if (!texture) {
  10476. return;
  10477. }
  10478. var internalFormat = this._getInternalFormat(format);
  10479. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10480. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10481. if (!this._doNotHandleContextLost) {
  10482. texture._bufferView = data;
  10483. texture.format = format;
  10484. texture.invertY = invertY;
  10485. texture._compression = compression;
  10486. }
  10487. if (texture.width % 4 !== 0) {
  10488. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10489. }
  10490. if (compression && data) {
  10491. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10492. }
  10493. else {
  10494. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10495. }
  10496. if (texture.generateMipMaps) {
  10497. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10498. }
  10499. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10500. this.resetTextureCache();
  10501. texture.isReady = true;
  10502. };
  10503. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10504. if (compression === void 0) { compression = null; }
  10505. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10506. texture.baseWidth = width;
  10507. texture.baseHeight = height;
  10508. texture.width = width;
  10509. texture.height = height;
  10510. texture.format = format;
  10511. texture.generateMipMaps = generateMipMaps;
  10512. texture.samplingMode = samplingMode;
  10513. texture.invertY = invertY;
  10514. texture._compression = compression;
  10515. if (!this._doNotHandleContextLost) {
  10516. texture._bufferView = data;
  10517. }
  10518. this.updateRawTexture(texture, data, format, invertY, compression);
  10519. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10520. // Filters
  10521. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10522. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10523. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10524. if (generateMipMaps) {
  10525. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10526. }
  10527. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10528. this._internalTexturesCache.push(texture);
  10529. return texture;
  10530. };
  10531. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10532. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10533. texture.baseWidth = width;
  10534. texture.baseHeight = height;
  10535. if (generateMipMaps) {
  10536. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10537. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10538. }
  10539. this.resetTextureCache();
  10540. texture.width = width;
  10541. texture.height = height;
  10542. texture.isReady = false;
  10543. texture.generateMipMaps = generateMipMaps;
  10544. texture.samplingMode = samplingMode;
  10545. this.updateTextureSamplingMode(samplingMode, texture);
  10546. this._internalTexturesCache.push(texture);
  10547. return texture;
  10548. };
  10549. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10550. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10551. if (texture.isCube) {
  10552. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10553. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10554. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10555. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10556. }
  10557. else if (texture.is3D) {
  10558. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10559. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10560. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10561. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10562. }
  10563. else {
  10564. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10565. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10566. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10567. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10568. }
  10569. texture.samplingMode = samplingMode;
  10570. };
  10571. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10572. if (premulAlpha === void 0) { premulAlpha = false; }
  10573. if (!texture) {
  10574. return;
  10575. }
  10576. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10577. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10578. if (premulAlpha) {
  10579. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10580. }
  10581. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10582. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10583. if (texture.generateMipMaps) {
  10584. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10585. }
  10586. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10587. if (premulAlpha) {
  10588. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10589. }
  10590. this.resetTextureCache();
  10591. texture.isReady = true;
  10592. };
  10593. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10594. if (!texture || texture._isDisabled) {
  10595. return;
  10596. }
  10597. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10598. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10599. try {
  10600. // Testing video texture support
  10601. if (this._videoTextureSupported === undefined) {
  10602. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10603. if (this._gl.getError() !== 0) {
  10604. this._videoTextureSupported = false;
  10605. }
  10606. else {
  10607. this._videoTextureSupported = true;
  10608. }
  10609. }
  10610. // Copy video through the current working canvas if video texture is not supported
  10611. if (!this._videoTextureSupported) {
  10612. if (!texture._workingCanvas) {
  10613. texture._workingCanvas = document.createElement("canvas");
  10614. var context = texture._workingCanvas.getContext("2d");
  10615. if (!context) {
  10616. throw new Error("Unable to get 2d context");
  10617. }
  10618. texture._workingContext = context;
  10619. texture._workingCanvas.width = texture.width;
  10620. texture._workingCanvas.height = texture.height;
  10621. }
  10622. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10623. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10624. }
  10625. else {
  10626. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10627. }
  10628. if (texture.generateMipMaps) {
  10629. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10630. }
  10631. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10632. this.resetTextureCache();
  10633. texture.isReady = true;
  10634. }
  10635. catch (ex) {
  10636. // Something unexpected
  10637. // Let's disable the texture
  10638. texture._isDisabled = true;
  10639. }
  10640. };
  10641. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10642. var fullOptions = new RenderTargetCreationOptions();
  10643. if (options !== undefined && typeof options === "object") {
  10644. fullOptions.generateMipMaps = options.generateMipMaps;
  10645. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10646. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10647. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10648. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10649. }
  10650. else {
  10651. fullOptions.generateMipMaps = options;
  10652. fullOptions.generateDepthBuffer = true;
  10653. fullOptions.generateStencilBuffer = false;
  10654. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10655. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10656. }
  10657. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10658. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10659. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10660. }
  10661. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10662. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10663. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10664. }
  10665. var gl = this._gl;
  10666. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10667. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10668. var width = size.width || size;
  10669. var height = size.height || size;
  10670. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10671. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10672. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10673. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10674. }
  10675. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10676. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10677. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10678. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10679. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10680. // Create the framebuffer
  10681. var framebuffer = gl.createFramebuffer();
  10682. this.bindUnboundFramebuffer(framebuffer);
  10683. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10684. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10685. if (fullOptions.generateMipMaps) {
  10686. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10687. }
  10688. // Unbind
  10689. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10690. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10691. this.bindUnboundFramebuffer(null);
  10692. texture._framebuffer = framebuffer;
  10693. texture.baseWidth = width;
  10694. texture.baseHeight = height;
  10695. texture.width = width;
  10696. texture.height = height;
  10697. texture.isReady = true;
  10698. texture.samples = 1;
  10699. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10700. texture.samplingMode = fullOptions.samplingMode;
  10701. texture.type = fullOptions.type;
  10702. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10703. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10704. this.resetTextureCache();
  10705. this._internalTexturesCache.push(texture);
  10706. return texture;
  10707. };
  10708. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10709. var generateMipMaps = false;
  10710. var generateDepthBuffer = true;
  10711. var generateStencilBuffer = false;
  10712. var generateDepthTexture = false;
  10713. var textureCount = 1;
  10714. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10715. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10716. var types = [], samplingModes = [];
  10717. if (options !== undefined) {
  10718. generateMipMaps = options.generateMipMaps;
  10719. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10720. generateStencilBuffer = options.generateStencilBuffer;
  10721. generateDepthTexture = options.generateDepthTexture;
  10722. textureCount = options.textureCount || 1;
  10723. if (options.types) {
  10724. types = options.types;
  10725. }
  10726. if (options.samplingModes) {
  10727. samplingModes = options.samplingModes;
  10728. }
  10729. }
  10730. var gl = this._gl;
  10731. // Create the framebuffer
  10732. var framebuffer = gl.createFramebuffer();
  10733. this.bindUnboundFramebuffer(framebuffer);
  10734. var width = size.width || size;
  10735. var height = size.height || size;
  10736. var textures = [];
  10737. var attachments = [];
  10738. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10739. for (var i = 0; i < textureCount; i++) {
  10740. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10741. var type = types[i] || defaultType;
  10742. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10743. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10744. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10745. }
  10746. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10747. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10748. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10749. }
  10750. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10751. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10752. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10753. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10754. }
  10755. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10756. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10757. textures.push(texture);
  10758. attachments.push(attachment);
  10759. gl.activeTexture(gl["TEXTURE" + i]);
  10760. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10761. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10763. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10765. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10766. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10767. if (generateMipMaps) {
  10768. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10769. }
  10770. // Unbind
  10771. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10772. texture._framebuffer = framebuffer;
  10773. texture._depthStencilBuffer = depthStencilBuffer;
  10774. texture.baseWidth = width;
  10775. texture.baseHeight = height;
  10776. texture.width = width;
  10777. texture.height = height;
  10778. texture.isReady = true;
  10779. texture.samples = 1;
  10780. texture.generateMipMaps = generateMipMaps;
  10781. texture.samplingMode = samplingMode;
  10782. texture.type = type;
  10783. texture._generateDepthBuffer = generateDepthBuffer;
  10784. texture._generateStencilBuffer = generateStencilBuffer;
  10785. this._internalTexturesCache.push(texture);
  10786. }
  10787. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10788. // Depth texture
  10789. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10790. gl.activeTexture(gl.TEXTURE0);
  10791. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10792. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10793. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10794. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10795. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10796. 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);
  10797. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10798. depthTexture._framebuffer = framebuffer;
  10799. depthTexture.baseWidth = width;
  10800. depthTexture.baseHeight = height;
  10801. depthTexture.width = width;
  10802. depthTexture.height = height;
  10803. depthTexture.isReady = true;
  10804. depthTexture.samples = 1;
  10805. depthTexture.generateMipMaps = generateMipMaps;
  10806. depthTexture.samplingMode = gl.NEAREST;
  10807. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10808. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10809. textures.push(depthTexture);
  10810. this._internalTexturesCache.push(depthTexture);
  10811. }
  10812. gl.drawBuffers(attachments);
  10813. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10814. this.bindUnboundFramebuffer(null);
  10815. this.resetTextureCache();
  10816. return textures;
  10817. };
  10818. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10819. if (samples === void 0) { samples = 1; }
  10820. var depthStencilBuffer = null;
  10821. var gl = this._gl;
  10822. // Create the depth/stencil buffer
  10823. if (generateStencilBuffer) {
  10824. depthStencilBuffer = gl.createRenderbuffer();
  10825. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10826. if (samples > 1) {
  10827. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10828. }
  10829. else {
  10830. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10831. }
  10832. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10833. }
  10834. else if (generateDepthBuffer) {
  10835. depthStencilBuffer = gl.createRenderbuffer();
  10836. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10837. if (samples > 1) {
  10838. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10839. }
  10840. else {
  10841. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10842. }
  10843. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10844. }
  10845. return depthStencilBuffer;
  10846. };
  10847. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10848. if (this.webGLVersion < 2 || !texture) {
  10849. return 1;
  10850. }
  10851. if (texture.samples === samples) {
  10852. return samples;
  10853. }
  10854. var gl = this._gl;
  10855. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10856. // Dispose previous render buffers
  10857. if (texture._depthStencilBuffer) {
  10858. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10859. }
  10860. if (texture._MSAAFramebuffer) {
  10861. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10862. }
  10863. if (texture._MSAARenderBuffer) {
  10864. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10865. }
  10866. if (samples > 1) {
  10867. var framebuffer = gl.createFramebuffer();
  10868. if (!framebuffer) {
  10869. throw new Error("Unable to create multi sampled framebuffer");
  10870. }
  10871. texture._MSAAFramebuffer = framebuffer;
  10872. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10873. var colorRenderbuffer = gl.createRenderbuffer();
  10874. if (!colorRenderbuffer) {
  10875. throw new Error("Unable to create multi sampled framebuffer");
  10876. }
  10877. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10878. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10879. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10880. texture._MSAARenderBuffer = colorRenderbuffer;
  10881. }
  10882. else {
  10883. this.bindUnboundFramebuffer(texture._framebuffer);
  10884. }
  10885. texture.samples = samples;
  10886. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10887. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10888. this.bindUnboundFramebuffer(null);
  10889. return samples;
  10890. };
  10891. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10892. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10893. };
  10894. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10895. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10896. };
  10897. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10898. var gl = this._gl;
  10899. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10900. var generateMipMaps = true;
  10901. var generateDepthBuffer = true;
  10902. var generateStencilBuffer = false;
  10903. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10904. if (options !== undefined) {
  10905. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10906. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10907. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10908. if (options.samplingMode !== undefined) {
  10909. samplingMode = options.samplingMode;
  10910. }
  10911. }
  10912. texture.isCube = true;
  10913. texture.generateMipMaps = generateMipMaps;
  10914. texture.samples = 1;
  10915. texture.samplingMode = samplingMode;
  10916. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10917. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10918. for (var face = 0; face < 6; face++) {
  10919. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10920. }
  10921. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10922. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10923. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10924. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10925. // Create the framebuffer
  10926. var framebuffer = gl.createFramebuffer();
  10927. this.bindUnboundFramebuffer(framebuffer);
  10928. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10929. // Mipmaps
  10930. if (texture.generateMipMaps) {
  10931. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10932. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10933. }
  10934. // Unbind
  10935. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10936. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10937. this.bindUnboundFramebuffer(null);
  10938. texture._framebuffer = framebuffer;
  10939. texture.width = size;
  10940. texture.height = size;
  10941. texture.isReady = true;
  10942. this.resetTextureCache();
  10943. this._internalTexturesCache.push(texture);
  10944. return texture;
  10945. };
  10946. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10947. var _this = this;
  10948. if (onLoad === void 0) { onLoad = null; }
  10949. if (onError === void 0) { onError = null; }
  10950. if (forcedExtension === void 0) { forcedExtension = null; }
  10951. var callback = function (loadData) {
  10952. if (!loadData) {
  10953. if (onLoad) {
  10954. onLoad(null);
  10955. }
  10956. return;
  10957. }
  10958. var texture = loadData.texture;
  10959. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10960. texture._lodGenerationScale = scale;
  10961. texture._lodGenerationOffset = offset;
  10962. if (_this._caps.textureLOD) {
  10963. // Do not add extra process if texture lod is supported.
  10964. if (onLoad) {
  10965. onLoad(texture);
  10966. }
  10967. return;
  10968. }
  10969. var mipSlices = 3;
  10970. var gl = _this._gl;
  10971. var width = loadData.width;
  10972. if (!width) {
  10973. return;
  10974. }
  10975. var textures = [];
  10976. for (var i = 0; i < mipSlices; i++) {
  10977. //compute LOD from even spacing in smoothness (matching shader calculation)
  10978. var smoothness = i / (mipSlices - 1);
  10979. var roughness = 1 - smoothness;
  10980. var minLODIndex = offset; // roughness = 0
  10981. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10982. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10983. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10984. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10985. glTextureFromLod.isCube = true;
  10986. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10987. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10988. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10989. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10990. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10991. if (loadData.isDDS) {
  10992. var info = loadData.info;
  10993. var data = loadData.data;
  10994. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10995. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10996. }
  10997. else {
  10998. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10999. }
  11000. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11001. // Wrap in a base texture for easy binding.
  11002. var lodTexture = new BABYLON.BaseTexture(scene);
  11003. lodTexture.isCube = true;
  11004. lodTexture._texture = glTextureFromLod;
  11005. glTextureFromLod.isReady = true;
  11006. textures.push(lodTexture);
  11007. }
  11008. texture._lodTextureHigh = textures[2];
  11009. texture._lodTextureMid = textures[1];
  11010. texture._lodTextureLow = textures[0];
  11011. if (onLoad) {
  11012. onLoad(texture);
  11013. }
  11014. };
  11015. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  11016. };
  11017. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  11018. var _this = this;
  11019. if (onLoad === void 0) { onLoad = null; }
  11020. if (onError === void 0) { onError = null; }
  11021. if (forcedExtension === void 0) { forcedExtension = null; }
  11022. var gl = this._gl;
  11023. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  11024. texture.isCube = true;
  11025. texture.url = rootUrl;
  11026. texture.generateMipMaps = !noMipmap;
  11027. if (!this._doNotHandleContextLost) {
  11028. texture._extension = forcedExtension;
  11029. texture._files = files;
  11030. }
  11031. var isKTX = false;
  11032. var isDDS = false;
  11033. var lastDot = rootUrl.lastIndexOf('.');
  11034. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  11035. if (this._textureFormatInUse) {
  11036. extension = this._textureFormatInUse;
  11037. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  11038. isKTX = true;
  11039. }
  11040. else {
  11041. isDDS = (extension === ".dds");
  11042. }
  11043. var onerror = function (request, exception) {
  11044. if (onError) {
  11045. onError(request.status + " " + request.statusText, exception);
  11046. }
  11047. };
  11048. if (isKTX) {
  11049. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11050. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  11051. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  11052. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11053. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  11054. ktx.uploadLevels(_this._gl, !noMipmap);
  11055. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11056. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11057. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11058. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11059. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11060. _this.resetTextureCache();
  11061. texture.width = ktx.pixelWidth;
  11062. texture.height = ktx.pixelHeight;
  11063. texture.isReady = true;
  11064. }, undefined, undefined, true, onerror);
  11065. }
  11066. else if (isDDS) {
  11067. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  11068. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11069. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11070. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11071. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11072. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  11073. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11074. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11075. }
  11076. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11077. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11078. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11079. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11080. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11081. _this.resetTextureCache();
  11082. texture.width = info.width;
  11083. texture.height = info.height;
  11084. texture.isReady = true;
  11085. texture.type = info.textureType;
  11086. if (onLoad) {
  11087. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  11088. }
  11089. }, undefined, undefined, true, onerror);
  11090. }
  11091. else {
  11092. if (!files) {
  11093. throw new Error("Cannot load cubemap because files were not defined");
  11094. }
  11095. cascadeLoad(rootUrl, scene, function (imgs) {
  11096. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  11097. var height = width;
  11098. _this._prepareWorkingCanvas();
  11099. if (!_this._workingCanvas || !_this._workingContext) {
  11100. return;
  11101. }
  11102. _this._workingCanvas.width = width;
  11103. _this._workingCanvas.height = height;
  11104. var faces = [
  11105. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11106. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11107. ];
  11108. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11109. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11110. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11111. for (var index = 0; index < faces.length; index++) {
  11112. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11113. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11114. }
  11115. if (!noMipmap) {
  11116. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11117. }
  11118. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11119. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  11120. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11121. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11122. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11123. _this.resetTextureCache();
  11124. texture.width = width;
  11125. texture.height = height;
  11126. texture.isReady = true;
  11127. if (format) {
  11128. texture.format = format;
  11129. }
  11130. texture.onLoadedObservable.notifyObservers(texture);
  11131. texture.onLoadedObservable.clear();
  11132. if (onLoad) {
  11133. onLoad();
  11134. }
  11135. }, files, onError);
  11136. }
  11137. this._internalTexturesCache.push(texture);
  11138. return texture;
  11139. };
  11140. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11141. if (compression === void 0) { compression = null; }
  11142. if (level === void 0) { level = 0; }
  11143. texture._bufferViewArray = data;
  11144. texture.format = format;
  11145. texture.type = type;
  11146. texture.invertY = invertY;
  11147. texture._compression = compression;
  11148. var gl = this._gl;
  11149. var textureType = this._getWebGLTextureType(type);
  11150. var internalFormat = this._getInternalFormat(format);
  11151. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11152. var needConversion = false;
  11153. if (internalFormat === gl.RGB) {
  11154. internalFormat = gl.RGBA;
  11155. needConversion = true;
  11156. }
  11157. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11158. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11159. if (texture.width % 4 !== 0) {
  11160. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11161. }
  11162. // Data are known to be in +X +Y +Z -X -Y -Z
  11163. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11164. var faceData = data[faceIndex];
  11165. if (compression) {
  11166. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11167. }
  11168. else {
  11169. if (needConversion) {
  11170. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11171. }
  11172. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11173. }
  11174. }
  11175. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11176. if (isPot && texture.generateMipMaps && level === 0) {
  11177. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11178. }
  11179. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11180. this.resetTextureCache();
  11181. texture.isReady = true;
  11182. };
  11183. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11184. if (compression === void 0) { compression = null; }
  11185. var gl = this._gl;
  11186. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11187. texture.isCube = true;
  11188. texture.generateMipMaps = generateMipMaps;
  11189. texture.format = format;
  11190. texture.type = type;
  11191. if (!this._doNotHandleContextLost) {
  11192. texture._bufferViewArray = data;
  11193. }
  11194. var textureType = this._getWebGLTextureType(type);
  11195. var internalFormat = this._getInternalFormat(format);
  11196. var needConversion = false;
  11197. if (internalFormat === gl.RGB) {
  11198. internalFormat = gl.RGBA;
  11199. needConversion = true;
  11200. }
  11201. var width = size;
  11202. var height = width;
  11203. texture.width = width;
  11204. texture.height = height;
  11205. // Double check on POT to generate Mips.
  11206. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11207. if (!isPot) {
  11208. generateMipMaps = false;
  11209. }
  11210. // Upload data if needed. The texture won't be ready until then.
  11211. if (data) {
  11212. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11213. }
  11214. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11215. // Filters
  11216. if (data && generateMipMaps) {
  11217. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11218. }
  11219. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11220. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11221. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11222. }
  11223. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11224. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11225. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11226. }
  11227. else {
  11228. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11229. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11230. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11231. }
  11232. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11233. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11234. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11235. return texture;
  11236. };
  11237. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11238. var _this = this;
  11239. if (onLoad === void 0) { onLoad = null; }
  11240. if (onError === void 0) { onError = null; }
  11241. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11242. if (invertY === void 0) { invertY = false; }
  11243. var gl = this._gl;
  11244. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11245. scene._addPendingData(texture);
  11246. texture.url = url;
  11247. this._internalTexturesCache.push(texture);
  11248. var onerror = function (request, exception) {
  11249. scene._removePendingData(texture);
  11250. if (onError) {
  11251. onError(request.status + " " + request.statusText, exception);
  11252. }
  11253. };
  11254. var internalCallback = function (data) {
  11255. var width = texture.width;
  11256. var faceDataArrays = callback(data);
  11257. if (!faceDataArrays) {
  11258. return;
  11259. }
  11260. if (mipmmapGenerator) {
  11261. var textureType = _this._getWebGLTextureType(type);
  11262. var internalFormat = _this._getInternalFormat(format);
  11263. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11264. var needConversion = false;
  11265. if (internalFormat === gl.RGB) {
  11266. internalFormat = gl.RGBA;
  11267. needConversion = true;
  11268. }
  11269. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11270. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11271. var mipData = mipmmapGenerator(faceDataArrays);
  11272. for (var level = 0; level < mipData.length; level++) {
  11273. var mipSize = width >> level;
  11274. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11275. var mipFaceData = mipData[level][faceIndex];
  11276. if (needConversion) {
  11277. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11278. }
  11279. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11280. }
  11281. }
  11282. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11283. }
  11284. else {
  11285. texture.generateMipMaps = !noMipmap;
  11286. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11287. }
  11288. texture.isReady = true;
  11289. _this.resetTextureCache();
  11290. scene._removePendingData(texture);
  11291. if (onLoad) {
  11292. onLoad();
  11293. }
  11294. };
  11295. BABYLON.Tools.LoadFile(url, function (data) {
  11296. internalCallback(data);
  11297. }, undefined, scene.database, true, onerror);
  11298. return texture;
  11299. };
  11300. ;
  11301. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11302. if (compression === void 0) { compression = null; }
  11303. var internalFormat = this._getInternalFormat(format);
  11304. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11305. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11306. if (!this._doNotHandleContextLost) {
  11307. texture._bufferView = data;
  11308. texture.format = format;
  11309. texture.invertY = invertY;
  11310. texture._compression = compression;
  11311. }
  11312. if (texture.width % 4 !== 0) {
  11313. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11314. }
  11315. if (compression && data) {
  11316. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11317. }
  11318. else {
  11319. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11320. }
  11321. if (texture.generateMipMaps) {
  11322. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11323. }
  11324. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11325. this.resetTextureCache();
  11326. texture.isReady = true;
  11327. };
  11328. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11329. if (compression === void 0) { compression = null; }
  11330. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11331. texture.baseWidth = width;
  11332. texture.baseHeight = height;
  11333. texture.baseDepth = depth;
  11334. texture.width = width;
  11335. texture.height = height;
  11336. texture.depth = depth;
  11337. texture.format = format;
  11338. texture.generateMipMaps = generateMipMaps;
  11339. texture.samplingMode = samplingMode;
  11340. texture.is3D = true;
  11341. if (!this._doNotHandleContextLost) {
  11342. texture._bufferView = data;
  11343. }
  11344. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11345. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11346. // Filters
  11347. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11348. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11349. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11350. if (generateMipMaps) {
  11351. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11352. }
  11353. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11354. this._internalTexturesCache.push(texture);
  11355. return texture;
  11356. };
  11357. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11358. var gl = this._gl;
  11359. if (!gl) {
  11360. return;
  11361. }
  11362. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11363. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11364. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11365. if (!noMipmap && !isCompressed) {
  11366. gl.generateMipmap(gl.TEXTURE_2D);
  11367. }
  11368. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11369. this.resetTextureCache();
  11370. if (scene) {
  11371. scene._removePendingData(texture);
  11372. }
  11373. texture.onLoadedObservable.notifyObservers(texture);
  11374. texture.onLoadedObservable.clear();
  11375. };
  11376. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11377. var _this = this;
  11378. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11379. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11380. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11381. var gl = this._gl;
  11382. if (!gl) {
  11383. return;
  11384. }
  11385. if (!texture._webGLTexture) {
  11386. this.resetTextureCache();
  11387. if (scene) {
  11388. scene._removePendingData(texture);
  11389. }
  11390. return;
  11391. }
  11392. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11393. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11394. texture.baseWidth = width;
  11395. texture.baseHeight = height;
  11396. texture.width = potWidth;
  11397. texture.height = potHeight;
  11398. texture.isReady = true;
  11399. if (processFunction(potWidth, potHeight, function () {
  11400. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11401. })) {
  11402. // Returning as texture needs extra async steps
  11403. return;
  11404. }
  11405. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11406. };
  11407. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11408. // Create new RGBA data container.
  11409. var rgbaData;
  11410. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11411. rgbaData = new Float32Array(width * height * 4);
  11412. }
  11413. else {
  11414. rgbaData = new Uint32Array(width * height * 4);
  11415. }
  11416. // Convert each pixel.
  11417. for (var x = 0; x < width; x++) {
  11418. for (var y = 0; y < height; y++) {
  11419. var index = (y * width + x) * 3;
  11420. var newIndex = (y * width + x) * 4;
  11421. // Map Old Value to new value.
  11422. rgbaData[newIndex + 0] = rgbData[index + 0];
  11423. rgbaData[newIndex + 1] = rgbData[index + 1];
  11424. rgbaData[newIndex + 2] = rgbData[index + 2];
  11425. // Add fully opaque alpha channel.
  11426. rgbaData[newIndex + 3] = 1;
  11427. }
  11428. }
  11429. return rgbaData;
  11430. };
  11431. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11432. var gl = this._gl;
  11433. if (texture._framebuffer) {
  11434. gl.deleteFramebuffer(texture._framebuffer);
  11435. texture._framebuffer = null;
  11436. }
  11437. if (texture._depthStencilBuffer) {
  11438. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11439. texture._depthStencilBuffer = null;
  11440. }
  11441. if (texture._MSAAFramebuffer) {
  11442. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11443. texture._MSAAFramebuffer = null;
  11444. }
  11445. if (texture._MSAARenderBuffer) {
  11446. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11447. texture._MSAARenderBuffer = null;
  11448. }
  11449. };
  11450. Engine.prototype._releaseTexture = function (texture) {
  11451. var gl = this._gl;
  11452. this._releaseFramebufferObjects(texture);
  11453. gl.deleteTexture(texture._webGLTexture);
  11454. // Unbind channels
  11455. this.unbindAllTextures();
  11456. var index = this._internalTexturesCache.indexOf(texture);
  11457. if (index !== -1) {
  11458. this._internalTexturesCache.splice(index, 1);
  11459. }
  11460. // Integrated fixed lod samplers.
  11461. if (texture._lodTextureHigh) {
  11462. texture._lodTextureHigh.dispose();
  11463. }
  11464. if (texture._lodTextureMid) {
  11465. texture._lodTextureMid.dispose();
  11466. }
  11467. if (texture._lodTextureLow) {
  11468. texture._lodTextureLow.dispose();
  11469. }
  11470. };
  11471. Engine.prototype.setProgram = function (program) {
  11472. if (this._currentProgram !== program) {
  11473. this._gl.useProgram(program);
  11474. this._currentProgram = program;
  11475. }
  11476. };
  11477. Engine.prototype.bindSamplers = function (effect) {
  11478. this.setProgram(effect.getProgram());
  11479. var samplers = effect.getSamplers();
  11480. for (var index = 0; index < samplers.length; index++) {
  11481. var uniform = effect.getUniform(samplers[index]);
  11482. this._gl.uniform1i(uniform, index);
  11483. }
  11484. this._currentEffect = null;
  11485. };
  11486. Engine.prototype.activateTextureChannel = function (textureChannel) {
  11487. if (this._activeTextureChannel !== textureChannel) {
  11488. this._gl.activeTexture(textureChannel);
  11489. this._activeTextureChannel = textureChannel;
  11490. }
  11491. };
  11492. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11493. if (this._activeTexturesCache[this._activeTextureChannel] !== texture) {
  11494. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11495. this._activeTexturesCache[this._activeTextureChannel] = texture;
  11496. }
  11497. };
  11498. Engine.prototype._bindTexture = function (channel, texture) {
  11499. if (channel < 0) {
  11500. return;
  11501. }
  11502. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11503. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11504. };
  11505. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11506. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11507. };
  11508. Engine.prototype.unbindAllTextures = function () {
  11509. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11510. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11511. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11512. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11513. if (this.webGLVersion > 1) {
  11514. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11515. }
  11516. }
  11517. };
  11518. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11519. if (channel < 0) {
  11520. return;
  11521. }
  11522. if (this._setTexture(channel, texture)) {
  11523. this._gl.uniform1i(uniform, channel);
  11524. }
  11525. };
  11526. Engine.prototype._setTexture = function (channel, texture) {
  11527. // Not ready?
  11528. if (!texture) {
  11529. if (this._activeTexturesCache[channel] != null) {
  11530. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11531. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11532. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11533. if (this.webGLVersion > 1) {
  11534. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11535. }
  11536. }
  11537. return false;
  11538. }
  11539. // Video
  11540. var alreadyActivated = false;
  11541. if (texture.video) {
  11542. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11543. alreadyActivated = true;
  11544. texture.update();
  11545. }
  11546. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11547. texture.delayLoad();
  11548. return false;
  11549. }
  11550. var internalTexture;
  11551. if (texture.isReady()) {
  11552. internalTexture = texture.getInternalTexture();
  11553. }
  11554. else if (texture.isCube) {
  11555. internalTexture = this.emptyCubeTexture;
  11556. }
  11557. else if (texture.is3D) {
  11558. internalTexture = this.emptyTexture3D;
  11559. }
  11560. else {
  11561. internalTexture = this.emptyTexture;
  11562. }
  11563. if (!alreadyActivated) {
  11564. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11565. }
  11566. if (this._activeTexturesCache[this._activeTextureChannel] === internalTexture) {
  11567. return false;
  11568. }
  11569. if (internalTexture && internalTexture.is3D) {
  11570. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11571. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11572. internalTexture._cachedWrapU = texture.wrapU;
  11573. switch (texture.wrapU) {
  11574. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11575. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11576. break;
  11577. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11578. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11579. break;
  11580. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11581. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11582. break;
  11583. }
  11584. }
  11585. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11586. internalTexture._cachedWrapV = texture.wrapV;
  11587. switch (texture.wrapV) {
  11588. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11589. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11590. break;
  11591. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11592. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11593. break;
  11594. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11595. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11596. break;
  11597. }
  11598. }
  11599. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11600. internalTexture._cachedWrapR = texture.wrapR;
  11601. switch (texture.wrapV) {
  11602. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11603. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11604. break;
  11605. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11606. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11607. break;
  11608. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11609. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11610. break;
  11611. }
  11612. }
  11613. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11614. }
  11615. else if (internalTexture && internalTexture.isCube) {
  11616. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11617. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11618. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11619. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11620. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11621. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11622. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11623. }
  11624. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11625. }
  11626. else {
  11627. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11628. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11629. internalTexture._cachedWrapU = texture.wrapU;
  11630. switch (texture.wrapU) {
  11631. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11632. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11633. break;
  11634. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11635. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11636. break;
  11637. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11638. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11639. break;
  11640. }
  11641. }
  11642. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11643. internalTexture._cachedWrapV = texture.wrapV;
  11644. switch (texture.wrapV) {
  11645. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11646. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11647. break;
  11648. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11649. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11650. break;
  11651. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11652. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11653. break;
  11654. }
  11655. }
  11656. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11657. }
  11658. return true;
  11659. };
  11660. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11661. if (channel < 0 || !uniform) {
  11662. return;
  11663. }
  11664. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11665. this._textureUnits = new Int32Array(textures.length);
  11666. }
  11667. for (var i = 0; i < textures.length; i++) {
  11668. this._textureUnits[i] = channel + i;
  11669. }
  11670. this._gl.uniform1iv(uniform, this._textureUnits);
  11671. for (var index = 0; index < textures.length; index++) {
  11672. this._setTexture(channel + index, textures[index]);
  11673. }
  11674. };
  11675. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11676. var internalTexture = texture.getInternalTexture();
  11677. if (!internalTexture) {
  11678. return;
  11679. }
  11680. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11681. var value = texture.anisotropicFilteringLevel;
  11682. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11683. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11684. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11685. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11686. }
  11687. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11688. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11689. internalTexture._cachedAnisotropicFilteringLevel = value;
  11690. }
  11691. };
  11692. Engine.prototype.readPixels = function (x, y, width, height) {
  11693. var data = new Uint8Array(height * width * 4);
  11694. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11695. return data;
  11696. };
  11697. /**
  11698. * Add an externaly attached data from its key.
  11699. * This method call will fail and return false, if such key already exists.
  11700. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11701. * @param key the unique key that identifies the data
  11702. * @param data the data object to associate to the key for this Engine instance
  11703. * @return true if no such key were already present and the data was added successfully, false otherwise
  11704. */
  11705. Engine.prototype.addExternalData = function (key, data) {
  11706. if (!this._externalData) {
  11707. this._externalData = new BABYLON.StringDictionary();
  11708. }
  11709. return this._externalData.add(key, data);
  11710. };
  11711. /**
  11712. * Get an externaly attached data from its key
  11713. * @param key the unique key that identifies the data
  11714. * @return the associated data, if present (can be null), or undefined if not present
  11715. */
  11716. Engine.prototype.getExternalData = function (key) {
  11717. if (!this._externalData) {
  11718. this._externalData = new BABYLON.StringDictionary();
  11719. }
  11720. return this._externalData.get(key);
  11721. };
  11722. /**
  11723. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11724. * @param key the unique key that identifies the data
  11725. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11726. * @return the associated data, can be null if the factory returned null.
  11727. */
  11728. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11729. if (!this._externalData) {
  11730. this._externalData = new BABYLON.StringDictionary();
  11731. }
  11732. return this._externalData.getOrAddWithFactory(key, factory);
  11733. };
  11734. /**
  11735. * Remove an externaly attached data from the Engine instance
  11736. * @param key the unique key that identifies the data
  11737. * @return true if the data was successfully removed, false if it doesn't exist
  11738. */
  11739. Engine.prototype.removeExternalData = function (key) {
  11740. if (!this._externalData) {
  11741. this._externalData = new BABYLON.StringDictionary();
  11742. }
  11743. return this._externalData.remove(key);
  11744. };
  11745. Engine.prototype.unbindAllAttributes = function () {
  11746. if (this._mustWipeVertexAttributes) {
  11747. this._mustWipeVertexAttributes = false;
  11748. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11749. this._gl.disableVertexAttribArray(i);
  11750. this._vertexAttribArraysEnabled[i] = false;
  11751. this._currentBufferPointers[i].active = false;
  11752. }
  11753. return;
  11754. }
  11755. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11756. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11757. continue;
  11758. }
  11759. this._gl.disableVertexAttribArray(i);
  11760. this._vertexAttribArraysEnabled[i] = false;
  11761. this._currentBufferPointers[i].active = false;
  11762. }
  11763. };
  11764. Engine.prototype.releaseEffects = function () {
  11765. for (var name in this._compiledEffects) {
  11766. this._deleteProgram(this._compiledEffects[name]._program);
  11767. }
  11768. this._compiledEffects = {};
  11769. };
  11770. // Dispose
  11771. Engine.prototype.dispose = function () {
  11772. this.hideLoadingUI();
  11773. this.stopRenderLoop();
  11774. // Release postProcesses
  11775. while (this.postProcesses.length) {
  11776. this.postProcesses[0].dispose();
  11777. }
  11778. // Empty texture
  11779. if (this._emptyTexture) {
  11780. this._releaseTexture(this._emptyTexture);
  11781. this._emptyTexture = null;
  11782. }
  11783. if (this._emptyCubeTexture) {
  11784. this._releaseTexture(this._emptyCubeTexture);
  11785. this._emptyCubeTexture = null;
  11786. }
  11787. // Rescale PP
  11788. if (this._rescalePostProcess) {
  11789. this._rescalePostProcess.dispose();
  11790. }
  11791. // Release scenes
  11792. while (this.scenes.length) {
  11793. this.scenes[0].dispose();
  11794. }
  11795. // Release audio engine
  11796. if (Engine.audioEngine) {
  11797. Engine.audioEngine.dispose();
  11798. }
  11799. // Release effects
  11800. this.releaseEffects();
  11801. // Unbind
  11802. this.unbindAllAttributes();
  11803. if (this._dummyFramebuffer) {
  11804. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11805. }
  11806. //WebVR
  11807. this.disableVR();
  11808. // Events
  11809. if (BABYLON.Tools.IsWindowObjectExist()) {
  11810. window.removeEventListener("blur", this._onBlur);
  11811. window.removeEventListener("focus", this._onFocus);
  11812. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11813. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11814. if (this._renderingCanvas) {
  11815. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11816. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11817. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11818. if (!this._doNotHandleContextLost) {
  11819. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11820. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11821. }
  11822. }
  11823. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11824. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11825. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11826. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11827. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11828. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11829. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11830. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11831. if (this._onVrDisplayConnect) {
  11832. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11833. if (this._onVrDisplayDisconnect) {
  11834. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11835. }
  11836. if (this._onVrDisplayPresentChange) {
  11837. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11838. }
  11839. this._onVrDisplayConnect = null;
  11840. this._onVrDisplayDisconnect = null;
  11841. }
  11842. }
  11843. // Remove from Instances
  11844. var index = Engine.Instances.indexOf(this);
  11845. if (index >= 0) {
  11846. Engine.Instances.splice(index, 1);
  11847. }
  11848. this._workingCanvas = null;
  11849. this._workingContext = null;
  11850. this._currentBufferPointers = [];
  11851. this._renderingCanvas = null;
  11852. this._currentProgram = null;
  11853. this.onResizeObservable.clear();
  11854. this.onCanvasBlurObservable.clear();
  11855. this.onCanvasFocusObservable.clear();
  11856. this.onCanvasPointerOutObservable.clear();
  11857. this.onBeginFrameObservable.clear();
  11858. this.onEndFrameObservable.clear();
  11859. BABYLON.Effect.ResetCache();
  11860. };
  11861. // Loading screen
  11862. Engine.prototype.displayLoadingUI = function () {
  11863. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11864. return;
  11865. }
  11866. var loadingScreen = this.loadingScreen;
  11867. if (loadingScreen) {
  11868. loadingScreen.displayLoadingUI();
  11869. }
  11870. };
  11871. Engine.prototype.hideLoadingUI = function () {
  11872. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11873. return;
  11874. }
  11875. var loadingScreen = this.loadingScreen;
  11876. if (loadingScreen) {
  11877. loadingScreen.hideLoadingUI();
  11878. }
  11879. };
  11880. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11881. get: function () {
  11882. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11883. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11884. return this._loadingScreen;
  11885. },
  11886. set: function (loadingScreen) {
  11887. this._loadingScreen = loadingScreen;
  11888. },
  11889. enumerable: true,
  11890. configurable: true
  11891. });
  11892. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11893. set: function (text) {
  11894. this.loadingScreen.loadingUIText = text;
  11895. },
  11896. enumerable: true,
  11897. configurable: true
  11898. });
  11899. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11900. set: function (color) {
  11901. this.loadingScreen.loadingUIBackgroundColor = color;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Engine.prototype.attachContextLostEvent = function (callback) {
  11907. if (this._renderingCanvas) {
  11908. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11909. }
  11910. };
  11911. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11912. if (this._renderingCanvas) {
  11913. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11914. }
  11915. };
  11916. Engine.prototype.getVertexShaderSource = function (program) {
  11917. var shaders = this._gl.getAttachedShaders(program);
  11918. if (!shaders) {
  11919. return null;
  11920. }
  11921. return this._gl.getShaderSource(shaders[0]);
  11922. };
  11923. Engine.prototype.getFragmentShaderSource = function (program) {
  11924. var shaders = this._gl.getAttachedShaders(program);
  11925. if (!shaders) {
  11926. return null;
  11927. }
  11928. return this._gl.getShaderSource(shaders[1]);
  11929. };
  11930. Engine.prototype.getError = function () {
  11931. return this._gl.getError();
  11932. };
  11933. // FPS
  11934. Engine.prototype.getFps = function () {
  11935. return this._fps;
  11936. };
  11937. Engine.prototype.getDeltaTime = function () {
  11938. return this._deltaTime;
  11939. };
  11940. Engine.prototype._measureFps = function () {
  11941. this._performanceMonitor.sampleFrame();
  11942. this._fps = this._performanceMonitor.averageFPS;
  11943. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11944. };
  11945. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11946. if (faceIndex === void 0) { faceIndex = -1; }
  11947. var gl = this._gl;
  11948. if (!this._dummyFramebuffer) {
  11949. var dummy = gl.createFramebuffer();
  11950. if (!dummy) {
  11951. throw new Error("Unable to create dummy framebuffer");
  11952. }
  11953. this._dummyFramebuffer = dummy;
  11954. }
  11955. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11956. if (faceIndex > -1) {
  11957. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11958. }
  11959. else {
  11960. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11961. }
  11962. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11963. var buffer;
  11964. switch (readType) {
  11965. case gl.UNSIGNED_BYTE:
  11966. buffer = new Uint8Array(4 * width * height);
  11967. readType = gl.UNSIGNED_BYTE;
  11968. break;
  11969. default:
  11970. buffer = new Float32Array(4 * width * height);
  11971. readType = gl.FLOAT;
  11972. break;
  11973. }
  11974. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11975. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11976. return buffer;
  11977. };
  11978. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11979. if (this._webGLVersion > 1) {
  11980. return this._caps.colorBufferFloat;
  11981. }
  11982. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11983. };
  11984. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11985. if (this._webGLVersion > 1) {
  11986. return this._caps.colorBufferFloat;
  11987. }
  11988. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11989. };
  11990. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11991. Engine.prototype._canRenderToFramebuffer = function (type) {
  11992. var gl = this._gl;
  11993. //clear existing errors
  11994. while (gl.getError() !== gl.NO_ERROR) { }
  11995. var successful = true;
  11996. var texture = gl.createTexture();
  11997. gl.bindTexture(gl.TEXTURE_2D, texture);
  11998. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12001. var fb = gl.createFramebuffer();
  12002. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  12003. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  12004. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  12005. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  12006. successful = successful && (gl.getError() === gl.NO_ERROR);
  12007. //try render by clearing frame buffer's color buffer
  12008. if (successful) {
  12009. gl.clear(gl.COLOR_BUFFER_BIT);
  12010. successful = successful && (gl.getError() === gl.NO_ERROR);
  12011. }
  12012. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  12013. if (successful) {
  12014. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  12015. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12016. var readFormat = gl.RGBA;
  12017. var readType = gl.UNSIGNED_BYTE;
  12018. var buffer = new Uint8Array(4);
  12019. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  12020. successful = successful && (gl.getError() === gl.NO_ERROR);
  12021. }
  12022. //clean up
  12023. gl.deleteTexture(texture);
  12024. gl.deleteFramebuffer(fb);
  12025. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12026. //clear accumulated errors
  12027. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  12028. return successful;
  12029. };
  12030. Engine.prototype._getWebGLTextureType = function (type) {
  12031. if (type === Engine.TEXTURETYPE_FLOAT) {
  12032. return this._gl.FLOAT;
  12033. }
  12034. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12035. // Add Half Float Constant.
  12036. return this._gl.HALF_FLOAT_OES;
  12037. }
  12038. return this._gl.UNSIGNED_BYTE;
  12039. };
  12040. ;
  12041. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  12042. if (this._webGLVersion === 1) {
  12043. return this._gl.RGBA;
  12044. }
  12045. if (type === Engine.TEXTURETYPE_FLOAT) {
  12046. return this._gl.RGBA32F;
  12047. }
  12048. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12049. return this._gl.RGBA16F;
  12050. }
  12051. return this._gl.RGBA;
  12052. };
  12053. ;
  12054. Engine.prototype.createQuery = function () {
  12055. return this._gl.createQuery();
  12056. };
  12057. Engine.prototype.deleteQuery = function (query) {
  12058. this._gl.deleteQuery(query);
  12059. return this;
  12060. };
  12061. Engine.prototype.isQueryResultAvailable = function (query) {
  12062. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  12063. };
  12064. Engine.prototype.getQueryResult = function (query) {
  12065. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  12066. };
  12067. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  12068. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12069. this._gl.beginQuery(glAlgorithm, query);
  12070. return this;
  12071. };
  12072. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  12073. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12074. this._gl.endQuery(glAlgorithm);
  12075. return this;
  12076. };
  12077. /* Time queries */
  12078. Engine.prototype._createTimeQuery = function () {
  12079. var timerQuery = this._caps.timerQuery;
  12080. if (timerQuery.createQueryEXT) {
  12081. return timerQuery.createQueryEXT();
  12082. }
  12083. return this.createQuery();
  12084. };
  12085. Engine.prototype._deleteTimeQuery = function (query) {
  12086. var timerQuery = this._caps.timerQuery;
  12087. if (timerQuery.deleteQueryEXT) {
  12088. timerQuery.deleteQueryEXT(query);
  12089. return;
  12090. }
  12091. this.deleteQuery(query);
  12092. };
  12093. Engine.prototype._getTimeQueryResult = function (query) {
  12094. var timerQuery = this._caps.timerQuery;
  12095. if (timerQuery.getQueryObjectEXT) {
  12096. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  12097. }
  12098. return this.getQueryResult(query);
  12099. };
  12100. Engine.prototype._getTimeQueryAvailability = function (query) {
  12101. var timerQuery = this._caps.timerQuery;
  12102. if (timerQuery.getQueryObjectEXT) {
  12103. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  12104. }
  12105. return this.isQueryResultAvailable(query);
  12106. };
  12107. Engine.prototype.startTimeQuery = function () {
  12108. var timerQuery = this._caps.timerQuery;
  12109. if (!timerQuery) {
  12110. return null;
  12111. }
  12112. var token = new BABYLON._TimeToken();
  12113. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12114. if (this._caps.canUseTimestampForTimerQuery) {
  12115. token._startTimeQuery = this._createTimeQuery();
  12116. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12117. }
  12118. else {
  12119. if (this._currentNonTimestampToken) {
  12120. return this._currentNonTimestampToken;
  12121. }
  12122. token._timeElapsedQuery = this._createTimeQuery();
  12123. if (timerQuery.beginQueryEXT) {
  12124. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12125. }
  12126. else {
  12127. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12128. }
  12129. this._currentNonTimestampToken = token;
  12130. }
  12131. return token;
  12132. };
  12133. Engine.prototype.endTimeQuery = function (token) {
  12134. var timerQuery = this._caps.timerQuery;
  12135. if (!timerQuery || !token) {
  12136. return -1;
  12137. }
  12138. if (this._caps.canUseTimestampForTimerQuery) {
  12139. if (!token._startTimeQuery) {
  12140. return -1;
  12141. }
  12142. if (!token._endTimeQuery) {
  12143. token._endTimeQuery = this._createTimeQuery();
  12144. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12145. }
  12146. }
  12147. else if (!token._timeElapsedQueryEnded) {
  12148. if (!token._timeElapsedQuery) {
  12149. return -1;
  12150. }
  12151. if (timerQuery.endQueryEXT) {
  12152. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12153. }
  12154. else {
  12155. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12156. }
  12157. token._timeElapsedQueryEnded = true;
  12158. }
  12159. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12160. var available = false;
  12161. if (token._endTimeQuery) {
  12162. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12163. }
  12164. else if (token._timeElapsedQuery) {
  12165. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12166. }
  12167. if (available && !disjoint) {
  12168. var result = 0;
  12169. if (this._caps.canUseTimestampForTimerQuery) {
  12170. if (!token._startTimeQuery || !token._endTimeQuery) {
  12171. return -1;
  12172. }
  12173. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12174. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12175. result = timeEnd - timeStart;
  12176. this._deleteTimeQuery(token._startTimeQuery);
  12177. this._deleteTimeQuery(token._endTimeQuery);
  12178. token._startTimeQuery = null;
  12179. token._endTimeQuery = null;
  12180. }
  12181. else {
  12182. if (!token._timeElapsedQuery) {
  12183. return -1;
  12184. }
  12185. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12186. this._deleteTimeQuery(token._timeElapsedQuery);
  12187. token._timeElapsedQuery = null;
  12188. token._timeElapsedQueryEnded = false;
  12189. this._currentNonTimestampToken = null;
  12190. }
  12191. return result;
  12192. }
  12193. return -1;
  12194. };
  12195. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12196. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12197. };
  12198. // Transform feedback
  12199. Engine.prototype.createTransformFeedback = function () {
  12200. return this._gl.createTransformFeedback();
  12201. };
  12202. Engine.prototype.deleteTransformFeedback = function (value) {
  12203. this._gl.deleteTransformFeedback(value);
  12204. };
  12205. Engine.prototype.bindTransformFeedback = function (value) {
  12206. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12207. };
  12208. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12209. if (usePoints === void 0) { usePoints = true; }
  12210. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12211. };
  12212. Engine.prototype.endTransformFeedback = function () {
  12213. this._gl.endTransformFeedback();
  12214. };
  12215. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12216. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12217. };
  12218. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12219. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12220. };
  12221. // Statics
  12222. Engine.isSupported = function () {
  12223. try {
  12224. var tempcanvas = document.createElement("canvas");
  12225. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12226. return gl != null && !!window.WebGLRenderingContext;
  12227. }
  12228. catch (e) {
  12229. return false;
  12230. }
  12231. };
  12232. Engine.Instances = new Array();
  12233. // Const statics
  12234. Engine._ALPHA_DISABLE = 0;
  12235. Engine._ALPHA_ADD = 1;
  12236. Engine._ALPHA_COMBINE = 2;
  12237. Engine._ALPHA_SUBTRACT = 3;
  12238. Engine._ALPHA_MULTIPLY = 4;
  12239. Engine._ALPHA_MAXIMIZED = 5;
  12240. Engine._ALPHA_ONEONE = 6;
  12241. Engine._ALPHA_PREMULTIPLIED = 7;
  12242. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12243. Engine._ALPHA_INTERPOLATE = 9;
  12244. Engine._ALPHA_SCREENMODE = 10;
  12245. Engine._DELAYLOADSTATE_NONE = 0;
  12246. Engine._DELAYLOADSTATE_LOADED = 1;
  12247. Engine._DELAYLOADSTATE_LOADING = 2;
  12248. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12249. Engine._TEXTUREFORMAT_ALPHA = 0;
  12250. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12251. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12252. Engine._TEXTUREFORMAT_RGB = 4;
  12253. Engine._TEXTUREFORMAT_RGBA = 5;
  12254. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12255. Engine._TEXTURETYPE_FLOAT = 1;
  12256. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12257. // Depht or Stencil test Constants.
  12258. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12259. 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.
  12260. 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.
  12261. 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.
  12262. 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.
  12263. 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.
  12264. 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.
  12265. 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.
  12266. // Stencil Actions Constants.
  12267. Engine._KEEP = 0x1E00;
  12268. Engine._REPLACE = 0x1E01;
  12269. Engine._INCR = 0x1E02;
  12270. Engine._DECR = 0x1E03;
  12271. Engine._INVERT = 0x150A;
  12272. Engine._INCR_WRAP = 0x8507;
  12273. Engine._DECR_WRAP = 0x8508;
  12274. // Texture rescaling mode
  12275. Engine._SCALEMODE_FLOOR = 1;
  12276. Engine._SCALEMODE_NEAREST = 2;
  12277. Engine._SCALEMODE_CEILING = 3;
  12278. // Updatable statics so stick with vars here
  12279. Engine.CollisionsEpsilon = 0.001;
  12280. Engine.CodeRepository = "src/";
  12281. Engine.ShadersRepository = "src/Shaders/";
  12282. return Engine;
  12283. }());
  12284. BABYLON.Engine = Engine;
  12285. })(BABYLON || (BABYLON = {}));
  12286. //# sourceMappingURL=babylon.engine.js.map
  12287. var BABYLON;
  12288. (function (BABYLON) {
  12289. /**
  12290. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12291. */
  12292. var Node = /** @class */ (function () {
  12293. /**
  12294. * @constructor
  12295. * @param {string} name - the name and id to be given to this node
  12296. * @param {BABYLON.Scene} the scene this node will be added to
  12297. */
  12298. function Node(name, scene) {
  12299. if (scene === void 0) { scene = null; }
  12300. this.state = "";
  12301. this.metadata = null;
  12302. this.doNotSerialize = false;
  12303. this.animations = new Array();
  12304. this._ranges = {};
  12305. this._isEnabled = true;
  12306. this._isReady = true;
  12307. this._currentRenderId = -1;
  12308. this._parentRenderId = -1;
  12309. /**
  12310. * An event triggered when the mesh is disposed.
  12311. * @type {BABYLON.Observable}
  12312. */
  12313. this.onDisposeObservable = new BABYLON.Observable();
  12314. // Behaviors
  12315. this._behaviors = new Array();
  12316. this.name = name;
  12317. this.id = name;
  12318. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12319. this.uniqueId = this._scene.getUniqueId();
  12320. this._initCache();
  12321. }
  12322. Object.defineProperty(Node.prototype, "parent", {
  12323. get: function () {
  12324. return this._parentNode;
  12325. },
  12326. set: function (parent) {
  12327. if (this._parentNode === parent) {
  12328. return;
  12329. }
  12330. if (this._parentNode) {
  12331. var index = this._parentNode._children.indexOf(this);
  12332. if (index !== -1) {
  12333. this._parentNode._children.splice(index, 1);
  12334. }
  12335. }
  12336. this._parentNode = parent;
  12337. if (this._parentNode) {
  12338. if (!this._parentNode._children) {
  12339. this._parentNode._children = new Array();
  12340. }
  12341. this._parentNode._children.push(this);
  12342. }
  12343. },
  12344. enumerable: true,
  12345. configurable: true
  12346. });
  12347. Node.prototype.getClassName = function () {
  12348. return "Node";
  12349. };
  12350. Object.defineProperty(Node.prototype, "onDispose", {
  12351. set: function (callback) {
  12352. if (this._onDisposeObserver) {
  12353. this.onDisposeObservable.remove(this._onDisposeObserver);
  12354. }
  12355. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12356. },
  12357. enumerable: true,
  12358. configurable: true
  12359. });
  12360. Node.prototype.getScene = function () {
  12361. return this._scene;
  12362. };
  12363. Node.prototype.getEngine = function () {
  12364. return this._scene.getEngine();
  12365. };
  12366. Node.prototype.addBehavior = function (behavior) {
  12367. var _this = this;
  12368. var index = this._behaviors.indexOf(behavior);
  12369. if (index !== -1) {
  12370. return this;
  12371. }
  12372. behavior.init();
  12373. if (this._scene.isLoading) {
  12374. // We defer the attach when the scene will be loaded
  12375. var observer = this._scene.onDataLoadedObservable.add(function () {
  12376. behavior.attach(_this);
  12377. _this._scene.onDataLoadedObservable.remove(observer);
  12378. });
  12379. }
  12380. else {
  12381. behavior.attach(this);
  12382. }
  12383. this._behaviors.push(behavior);
  12384. return this;
  12385. };
  12386. Node.prototype.removeBehavior = function (behavior) {
  12387. var index = this._behaviors.indexOf(behavior);
  12388. if (index === -1) {
  12389. return this;
  12390. }
  12391. this._behaviors[index].detach();
  12392. this._behaviors.splice(index, 1);
  12393. return this;
  12394. };
  12395. Object.defineProperty(Node.prototype, "behaviors", {
  12396. get: function () {
  12397. return this._behaviors;
  12398. },
  12399. enumerable: true,
  12400. configurable: true
  12401. });
  12402. Node.prototype.getBehaviorByName = function (name) {
  12403. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12404. var behavior = _a[_i];
  12405. if (behavior.name === name) {
  12406. return behavior;
  12407. }
  12408. }
  12409. return null;
  12410. };
  12411. // override it in derived class
  12412. Node.prototype.getWorldMatrix = function () {
  12413. return BABYLON.Matrix.Identity();
  12414. };
  12415. // override it in derived class if you add new variables to the cache
  12416. // and call the parent class method
  12417. Node.prototype._initCache = function () {
  12418. this._cache = {};
  12419. this._cache.parent = undefined;
  12420. };
  12421. Node.prototype.updateCache = function (force) {
  12422. if (!force && this.isSynchronized())
  12423. return;
  12424. this._cache.parent = this.parent;
  12425. this._updateCache();
  12426. };
  12427. // override it in derived class if you add new variables to the cache
  12428. // and call the parent class method if !ignoreParentClass
  12429. Node.prototype._updateCache = function (ignoreParentClass) {
  12430. };
  12431. // override it in derived class if you add new variables to the cache
  12432. Node.prototype._isSynchronized = function () {
  12433. return true;
  12434. };
  12435. Node.prototype._markSyncedWithParent = function () {
  12436. if (this.parent) {
  12437. this._parentRenderId = this.parent._currentRenderId;
  12438. }
  12439. };
  12440. Node.prototype.isSynchronizedWithParent = function () {
  12441. if (!this.parent) {
  12442. return true;
  12443. }
  12444. if (this._parentRenderId !== this.parent._currentRenderId) {
  12445. return false;
  12446. }
  12447. return this.parent.isSynchronized();
  12448. };
  12449. Node.prototype.isSynchronized = function (updateCache) {
  12450. var check = this.hasNewParent();
  12451. check = check || !this.isSynchronizedWithParent();
  12452. check = check || !this._isSynchronized();
  12453. if (updateCache)
  12454. this.updateCache(true);
  12455. return !check;
  12456. };
  12457. Node.prototype.hasNewParent = function (update) {
  12458. if (this._cache.parent === this.parent)
  12459. return false;
  12460. if (update)
  12461. this._cache.parent = this.parent;
  12462. return true;
  12463. };
  12464. /**
  12465. * Is this node ready to be used/rendered
  12466. * @return {boolean} is it ready
  12467. */
  12468. Node.prototype.isReady = function () {
  12469. return this._isReady;
  12470. };
  12471. /**
  12472. * Is this node enabled.
  12473. * If the node has a parent and is enabled, the parent will be inspected as well.
  12474. * @return {boolean} whether this node (and its parent) is enabled.
  12475. * @see setEnabled
  12476. */
  12477. Node.prototype.isEnabled = function () {
  12478. if (!this._isEnabled) {
  12479. return false;
  12480. }
  12481. if (this.parent) {
  12482. return this.parent.isEnabled();
  12483. }
  12484. return true;
  12485. };
  12486. /**
  12487. * Set the enabled state of this node.
  12488. * @param {boolean} value - the new enabled state
  12489. * @see isEnabled
  12490. */
  12491. Node.prototype.setEnabled = function (value) {
  12492. this._isEnabled = value;
  12493. };
  12494. /**
  12495. * Is this node a descendant of the given node.
  12496. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12497. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12498. * @see parent
  12499. */
  12500. Node.prototype.isDescendantOf = function (ancestor) {
  12501. if (this.parent) {
  12502. if (this.parent === ancestor) {
  12503. return true;
  12504. }
  12505. return this.parent.isDescendantOf(ancestor);
  12506. }
  12507. return false;
  12508. };
  12509. /**
  12510. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12511. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12512. * @param {boolean} directDescendantsOnly 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.
  12513. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  12514. */
  12515. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12516. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12517. if (!this._children) {
  12518. return;
  12519. }
  12520. for (var index = 0; index < this._children.length; index++) {
  12521. var item = this._children[index];
  12522. if (!predicate || predicate(item)) {
  12523. results.push(item);
  12524. }
  12525. if (!directDescendantsOnly) {
  12526. item._getDescendants(results, false, predicate);
  12527. }
  12528. }
  12529. };
  12530. /**
  12531. * Will return all nodes that have this node as ascendant.
  12532. * @param {boolean} directDescendantsOnly 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.
  12533. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  12534. * @return {BABYLON.Node[]} all children nodes of all types.
  12535. */
  12536. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12537. var results = new Array();
  12538. this._getDescendants(results, directDescendantsOnly, predicate);
  12539. return results;
  12540. };
  12541. /**
  12542. * Get all child-meshes of this node.
  12543. */
  12544. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  12545. var results = [];
  12546. this._getDescendants(results, directDecendantsOnly, function (node) {
  12547. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12548. });
  12549. return results;
  12550. };
  12551. /**
  12552. * Get all direct children of this node.
  12553. */
  12554. Node.prototype.getChildren = function (predicate) {
  12555. return this.getDescendants(true, predicate);
  12556. };
  12557. Node.prototype._setReady = function (state) {
  12558. if (state === this._isReady) {
  12559. return;
  12560. }
  12561. if (!state) {
  12562. this._isReady = false;
  12563. return;
  12564. }
  12565. this._isReady = true;
  12566. if (this.onReady) {
  12567. this.onReady(this);
  12568. }
  12569. };
  12570. Node.prototype.getAnimationByName = function (name) {
  12571. for (var i = 0; i < this.animations.length; i++) {
  12572. var animation = this.animations[i];
  12573. if (animation.name === name) {
  12574. return animation;
  12575. }
  12576. }
  12577. return null;
  12578. };
  12579. Node.prototype.createAnimationRange = function (name, from, to) {
  12580. // check name not already in use
  12581. if (!this._ranges[name]) {
  12582. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12583. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12584. if (this.animations[i]) {
  12585. this.animations[i].createRange(name, from, to);
  12586. }
  12587. }
  12588. }
  12589. };
  12590. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12591. if (deleteFrames === void 0) { deleteFrames = true; }
  12592. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12593. if (this.animations[i]) {
  12594. this.animations[i].deleteRange(name, deleteFrames);
  12595. }
  12596. }
  12597. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12598. };
  12599. Node.prototype.getAnimationRange = function (name) {
  12600. return this._ranges[name];
  12601. };
  12602. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12603. var range = this.getAnimationRange(name);
  12604. if (!range) {
  12605. return;
  12606. }
  12607. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12608. };
  12609. Node.prototype.serializeAnimationRanges = function () {
  12610. var serializationRanges = [];
  12611. for (var name in this._ranges) {
  12612. var localRange = this._ranges[name];
  12613. if (!localRange) {
  12614. continue;
  12615. }
  12616. var range = {};
  12617. range.name = name;
  12618. range.from = localRange.from;
  12619. range.to = localRange.to;
  12620. serializationRanges.push(range);
  12621. }
  12622. return serializationRanges;
  12623. };
  12624. Node.prototype.dispose = function () {
  12625. this.parent = null;
  12626. // Callback
  12627. this.onDisposeObservable.notifyObservers(this);
  12628. this.onDisposeObservable.clear();
  12629. // Behaviors
  12630. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12631. var behavior = _a[_i];
  12632. behavior.detach();
  12633. }
  12634. this._behaviors = [];
  12635. };
  12636. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12637. if (parsedNode.ranges) {
  12638. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12639. var data = parsedNode.ranges[index];
  12640. node.createAnimationRange(data.name, data.from, data.to);
  12641. }
  12642. }
  12643. };
  12644. __decorate([
  12645. BABYLON.serialize()
  12646. ], Node.prototype, "name", void 0);
  12647. __decorate([
  12648. BABYLON.serialize()
  12649. ], Node.prototype, "id", void 0);
  12650. __decorate([
  12651. BABYLON.serialize()
  12652. ], Node.prototype, "uniqueId", void 0);
  12653. __decorate([
  12654. BABYLON.serialize()
  12655. ], Node.prototype, "state", void 0);
  12656. __decorate([
  12657. BABYLON.serialize()
  12658. ], Node.prototype, "metadata", void 0);
  12659. return Node;
  12660. }());
  12661. BABYLON.Node = Node;
  12662. })(BABYLON || (BABYLON = {}));
  12663. //# sourceMappingURL=babylon.node.js.map
  12664. var BABYLON;
  12665. (function (BABYLON) {
  12666. var BoundingSphere = /** @class */ (function () {
  12667. function BoundingSphere(minimum, maximum) {
  12668. this.minimum = minimum;
  12669. this.maximum = maximum;
  12670. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12671. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12672. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12673. this.radius = distance * 0.5;
  12674. this.centerWorld = BABYLON.Vector3.Zero();
  12675. this._update(BABYLON.Matrix.Identity());
  12676. }
  12677. // Methods
  12678. BoundingSphere.prototype._update = function (world) {
  12679. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12680. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12681. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12682. };
  12683. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12684. for (var i = 0; i < 6; i++) {
  12685. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12686. return false;
  12687. }
  12688. return true;
  12689. };
  12690. BoundingSphere.prototype.intersectsPoint = function (point) {
  12691. var x = this.centerWorld.x - point.x;
  12692. var y = this.centerWorld.y - point.y;
  12693. var z = this.centerWorld.z - point.z;
  12694. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12695. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12696. return false;
  12697. return true;
  12698. };
  12699. // Statics
  12700. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12701. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12702. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12703. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12704. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12705. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12706. return false;
  12707. return true;
  12708. };
  12709. return BoundingSphere;
  12710. }());
  12711. BABYLON.BoundingSphere = BoundingSphere;
  12712. })(BABYLON || (BABYLON = {}));
  12713. //# sourceMappingURL=babylon.boundingSphere.js.map
  12714. var BABYLON;
  12715. (function (BABYLON) {
  12716. var BoundingBox = /** @class */ (function () {
  12717. function BoundingBox(minimum, maximum) {
  12718. this.minimum = minimum;
  12719. this.maximum = maximum;
  12720. this.vectors = new Array();
  12721. this.vectorsWorld = new Array();
  12722. // Bounding vectors
  12723. this.vectors.push(this.minimum.clone());
  12724. this.vectors.push(this.maximum.clone());
  12725. this.vectors.push(this.minimum.clone());
  12726. this.vectors[2].x = this.maximum.x;
  12727. this.vectors.push(this.minimum.clone());
  12728. this.vectors[3].y = this.maximum.y;
  12729. this.vectors.push(this.minimum.clone());
  12730. this.vectors[4].z = this.maximum.z;
  12731. this.vectors.push(this.maximum.clone());
  12732. this.vectors[5].z = this.minimum.z;
  12733. this.vectors.push(this.maximum.clone());
  12734. this.vectors[6].x = this.minimum.x;
  12735. this.vectors.push(this.maximum.clone());
  12736. this.vectors[7].y = this.minimum.y;
  12737. // OBB
  12738. this.center = this.maximum.add(this.minimum).scale(0.5);
  12739. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12740. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12741. // World
  12742. for (var index = 0; index < this.vectors.length; index++) {
  12743. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12744. }
  12745. this.minimumWorld = BABYLON.Vector3.Zero();
  12746. this.maximumWorld = BABYLON.Vector3.Zero();
  12747. this.centerWorld = BABYLON.Vector3.Zero();
  12748. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12749. this._update(BABYLON.Matrix.Identity());
  12750. }
  12751. // Methods
  12752. BoundingBox.prototype.getWorldMatrix = function () {
  12753. return this._worldMatrix;
  12754. };
  12755. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12756. this._worldMatrix.copyFrom(matrix);
  12757. return this;
  12758. };
  12759. BoundingBox.prototype._update = function (world) {
  12760. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12761. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12762. for (var index = 0; index < this.vectors.length; index++) {
  12763. var v = this.vectorsWorld[index];
  12764. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12765. if (v.x < this.minimumWorld.x)
  12766. this.minimumWorld.x = v.x;
  12767. if (v.y < this.minimumWorld.y)
  12768. this.minimumWorld.y = v.y;
  12769. if (v.z < this.minimumWorld.z)
  12770. this.minimumWorld.z = v.z;
  12771. if (v.x > this.maximumWorld.x)
  12772. this.maximumWorld.x = v.x;
  12773. if (v.y > this.maximumWorld.y)
  12774. this.maximumWorld.y = v.y;
  12775. if (v.z > this.maximumWorld.z)
  12776. this.maximumWorld.z = v.z;
  12777. }
  12778. // Extend
  12779. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12780. this.extendSizeWorld.scaleInPlace(0.5);
  12781. // OBB
  12782. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12783. this.centerWorld.scaleInPlace(0.5);
  12784. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12785. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12786. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12787. this._worldMatrix = world;
  12788. };
  12789. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12790. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12791. };
  12792. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12793. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12794. };
  12795. BoundingBox.prototype.intersectsPoint = function (point) {
  12796. var delta = -BABYLON.Epsilon;
  12797. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12798. return false;
  12799. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12800. return false;
  12801. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12802. return false;
  12803. return true;
  12804. };
  12805. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12806. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12807. };
  12808. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12809. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12810. return false;
  12811. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12812. return false;
  12813. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12814. return false;
  12815. return true;
  12816. };
  12817. // Statics
  12818. BoundingBox.Intersects = function (box0, box1) {
  12819. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12820. return false;
  12821. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12822. return false;
  12823. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12824. return false;
  12825. return true;
  12826. };
  12827. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12828. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12829. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12830. return (num <= (sphereRadius * sphereRadius));
  12831. };
  12832. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12833. for (var p = 0; p < 6; p++) {
  12834. for (var i = 0; i < 8; i++) {
  12835. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12836. return false;
  12837. }
  12838. }
  12839. }
  12840. return true;
  12841. };
  12842. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12843. for (var p = 0; p < 6; p++) {
  12844. var inCount = 8;
  12845. for (var i = 0; i < 8; i++) {
  12846. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12847. --inCount;
  12848. }
  12849. else {
  12850. break;
  12851. }
  12852. }
  12853. if (inCount === 0)
  12854. return false;
  12855. }
  12856. return true;
  12857. };
  12858. return BoundingBox;
  12859. }());
  12860. BABYLON.BoundingBox = BoundingBox;
  12861. })(BABYLON || (BABYLON = {}));
  12862. //# sourceMappingURL=babylon.boundingBox.js.map
  12863. var BABYLON;
  12864. (function (BABYLON) {
  12865. var computeBoxExtents = function (axis, box) {
  12866. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12867. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12868. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12869. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12870. var r = r0 + r1 + r2;
  12871. return {
  12872. min: p - r,
  12873. max: p + r
  12874. };
  12875. };
  12876. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12877. var axisOverlap = function (axis, box0, box1) {
  12878. var result0 = computeBoxExtents(axis, box0);
  12879. var result1 = computeBoxExtents(axis, box1);
  12880. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12881. };
  12882. var BoundingInfo = /** @class */ (function () {
  12883. function BoundingInfo(minimum, maximum) {
  12884. this.minimum = minimum;
  12885. this.maximum = maximum;
  12886. this._isLocked = false;
  12887. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12888. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12889. }
  12890. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12891. get: function () {
  12892. return this._isLocked;
  12893. },
  12894. set: function (value) {
  12895. this._isLocked = value;
  12896. },
  12897. enumerable: true,
  12898. configurable: true
  12899. });
  12900. // Methods
  12901. BoundingInfo.prototype.update = function (world) {
  12902. if (this._isLocked) {
  12903. return;
  12904. }
  12905. this.boundingBox._update(world);
  12906. this.boundingSphere._update(world);
  12907. };
  12908. /**
  12909. * Recreate the bounding info to be centered around a specific point given a specific extend.
  12910. * @param center New center of the bounding info
  12911. * @param extend New extend of the bounding info
  12912. */
  12913. BoundingInfo.prototype.centerOn = function (center, extend) {
  12914. this.minimum = center.subtract(extend);
  12915. this.maximum = center.add(extend);
  12916. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  12917. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  12918. return this;
  12919. };
  12920. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12921. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12922. return false;
  12923. return this.boundingBox.isInFrustum(frustumPlanes);
  12924. };
  12925. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12926. /**
  12927. * Gets the world distance between the min and max points of the bounding box
  12928. */
  12929. get: function () {
  12930. var boundingBox = this.boundingBox;
  12931. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12932. return size.length();
  12933. },
  12934. enumerable: true,
  12935. configurable: true
  12936. });
  12937. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12938. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12939. };
  12940. BoundingInfo.prototype._checkCollision = function (collider) {
  12941. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12942. };
  12943. BoundingInfo.prototype.intersectsPoint = function (point) {
  12944. if (!this.boundingSphere.centerWorld) {
  12945. return false;
  12946. }
  12947. if (!this.boundingSphere.intersectsPoint(point)) {
  12948. return false;
  12949. }
  12950. if (!this.boundingBox.intersectsPoint(point)) {
  12951. return false;
  12952. }
  12953. return true;
  12954. };
  12955. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12956. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12957. return false;
  12958. }
  12959. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12960. return false;
  12961. }
  12962. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12963. return false;
  12964. }
  12965. if (!precise) {
  12966. return true;
  12967. }
  12968. var box0 = this.boundingBox;
  12969. var box1 = boundingInfo.boundingBox;
  12970. if (!axisOverlap(box0.directions[0], box0, box1))
  12971. return false;
  12972. if (!axisOverlap(box0.directions[1], box0, box1))
  12973. return false;
  12974. if (!axisOverlap(box0.directions[2], box0, box1))
  12975. return false;
  12976. if (!axisOverlap(box1.directions[0], box0, box1))
  12977. return false;
  12978. if (!axisOverlap(box1.directions[1], box0, box1))
  12979. return false;
  12980. if (!axisOverlap(box1.directions[2], box0, box1))
  12981. return false;
  12982. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12983. return false;
  12984. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12985. return false;
  12986. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12987. return false;
  12988. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12989. return false;
  12990. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12991. return false;
  12992. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12993. return false;
  12994. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12995. return false;
  12996. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12997. return false;
  12998. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12999. return false;
  13000. return true;
  13001. };
  13002. return BoundingInfo;
  13003. }());
  13004. BABYLON.BoundingInfo = BoundingInfo;
  13005. })(BABYLON || (BABYLON = {}));
  13006. //# sourceMappingURL=babylon.boundingInfo.js.map
  13007. var BABYLON;
  13008. (function (BABYLON) {
  13009. var TransformNode = /** @class */ (function (_super) {
  13010. __extends(TransformNode, _super);
  13011. function TransformNode(name, scene, isPure) {
  13012. if (scene === void 0) { scene = null; }
  13013. if (isPure === void 0) { isPure = true; }
  13014. var _this = _super.call(this, name, scene) || this;
  13015. // Properties
  13016. _this._rotation = BABYLON.Vector3.Zero();
  13017. _this._scaling = BABYLON.Vector3.One();
  13018. _this._isDirty = false;
  13019. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  13020. _this.scalingDeterminant = 1;
  13021. _this.infiniteDistance = false;
  13022. _this.position = BABYLON.Vector3.Zero();
  13023. _this._localWorld = BABYLON.Matrix.Zero();
  13024. _this._worldMatrix = BABYLON.Matrix.Zero();
  13025. _this._absolutePosition = BABYLON.Vector3.Zero();
  13026. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13027. _this._postMultiplyPivotMatrix = false;
  13028. _this._isWorldMatrixFrozen = false;
  13029. /**
  13030. * An event triggered after the world matrix is updated
  13031. * @type {BABYLON.Observable}
  13032. */
  13033. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  13034. _this._nonUniformScaling = false;
  13035. if (isPure) {
  13036. _this.getScene().addTransformNode(_this);
  13037. }
  13038. return _this;
  13039. }
  13040. Object.defineProperty(TransformNode.prototype, "rotation", {
  13041. /**
  13042. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13043. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13044. * Default : (0.0, 0.0, 0.0)
  13045. */
  13046. get: function () {
  13047. return this._rotation;
  13048. },
  13049. set: function (newRotation) {
  13050. this._rotation = newRotation;
  13051. },
  13052. enumerable: true,
  13053. configurable: true
  13054. });
  13055. Object.defineProperty(TransformNode.prototype, "scaling", {
  13056. /**
  13057. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13058. * Default : (1.0, 1.0, 1.0)
  13059. */
  13060. get: function () {
  13061. return this._scaling;
  13062. },
  13063. /**
  13064. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13065. * Default : (1.0, 1.0, 1.0)
  13066. */
  13067. set: function (newScaling) {
  13068. this._scaling = newScaling;
  13069. },
  13070. enumerable: true,
  13071. configurable: true
  13072. });
  13073. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  13074. /**
  13075. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13076. * It's null by default.
  13077. * 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)
  13078. */
  13079. get: function () {
  13080. return this._rotationQuaternion;
  13081. },
  13082. set: function (quaternion) {
  13083. this._rotationQuaternion = quaternion;
  13084. //reset the rotation vector.
  13085. if (quaternion && this.rotation.length()) {
  13086. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13087. }
  13088. },
  13089. enumerable: true,
  13090. configurable: true
  13091. });
  13092. /**
  13093. * Returns the latest update of the World matrix
  13094. * Returns a Matrix.
  13095. */
  13096. TransformNode.prototype.getWorldMatrix = function () {
  13097. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13098. this.computeWorldMatrix();
  13099. }
  13100. return this._worldMatrix;
  13101. };
  13102. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  13103. /**
  13104. * Returns directly the latest state of the mesh World matrix.
  13105. * A Matrix is returned.
  13106. */
  13107. get: function () {
  13108. return this._worldMatrix;
  13109. },
  13110. enumerable: true,
  13111. configurable: true
  13112. });
  13113. /**
  13114. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13115. * Returns the AbstractMesh.
  13116. */
  13117. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  13118. this._poseMatrix.copyFrom(matrix);
  13119. return this;
  13120. };
  13121. /**
  13122. * Returns the mesh Pose matrix.
  13123. * Returned object : Matrix
  13124. */
  13125. TransformNode.prototype.getPoseMatrix = function () {
  13126. return this._poseMatrix;
  13127. };
  13128. TransformNode.prototype._isSynchronized = function () {
  13129. if (this._isDirty) {
  13130. return false;
  13131. }
  13132. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  13133. return false;
  13134. if (this._cache.pivotMatrixUpdated) {
  13135. return false;
  13136. }
  13137. if (this.infiniteDistance) {
  13138. return false;
  13139. }
  13140. if (!this._cache.position.equals(this.position))
  13141. return false;
  13142. if (this.rotationQuaternion) {
  13143. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13144. return false;
  13145. }
  13146. if (!this._cache.rotation.equals(this.rotation))
  13147. return false;
  13148. if (!this._cache.scaling.equals(this.scaling))
  13149. return false;
  13150. return true;
  13151. };
  13152. TransformNode.prototype._initCache = function () {
  13153. _super.prototype._initCache.call(this);
  13154. this._cache.localMatrixUpdated = false;
  13155. this._cache.position = BABYLON.Vector3.Zero();
  13156. this._cache.scaling = BABYLON.Vector3.Zero();
  13157. this._cache.rotation = BABYLON.Vector3.Zero();
  13158. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13159. this._cache.billboardMode = -1;
  13160. };
  13161. TransformNode.prototype.markAsDirty = function (property) {
  13162. if (property === "rotation") {
  13163. this.rotationQuaternion = null;
  13164. }
  13165. this._currentRenderId = Number.MAX_VALUE;
  13166. this._isDirty = true;
  13167. return this;
  13168. };
  13169. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  13170. /**
  13171. * Returns the current mesh absolute position.
  13172. * Retuns a Vector3.
  13173. */
  13174. get: function () {
  13175. return this._absolutePosition;
  13176. },
  13177. enumerable: true,
  13178. configurable: true
  13179. });
  13180. /**
  13181. * Sets a new pivot matrix to the mesh.
  13182. * Returns the AbstractMesh.
  13183. */
  13184. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13185. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13186. this._pivotMatrix = matrix.clone();
  13187. this._cache.pivotMatrixUpdated = true;
  13188. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13189. if (this._postMultiplyPivotMatrix) {
  13190. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13191. }
  13192. return this;
  13193. };
  13194. /**
  13195. * Returns the mesh pivot matrix.
  13196. * Default : Identity.
  13197. * A Matrix is returned.
  13198. */
  13199. TransformNode.prototype.getPivotMatrix = function () {
  13200. return this._pivotMatrix;
  13201. };
  13202. /**
  13203. * Prevents the World matrix to be computed any longer.
  13204. * Returns the AbstractMesh.
  13205. */
  13206. TransformNode.prototype.freezeWorldMatrix = function () {
  13207. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13208. this.computeWorldMatrix(true);
  13209. this._isWorldMatrixFrozen = true;
  13210. return this;
  13211. };
  13212. /**
  13213. * Allows back the World matrix computation.
  13214. * Returns the AbstractMesh.
  13215. */
  13216. TransformNode.prototype.unfreezeWorldMatrix = function () {
  13217. this._isWorldMatrixFrozen = false;
  13218. this.computeWorldMatrix(true);
  13219. return this;
  13220. };
  13221. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  13222. /**
  13223. * True if the World matrix has been frozen.
  13224. * Returns a boolean.
  13225. */
  13226. get: function () {
  13227. return this._isWorldMatrixFrozen;
  13228. },
  13229. enumerable: true,
  13230. configurable: true
  13231. });
  13232. /**
  13233. * Retuns the mesh absolute position in the World.
  13234. * Returns a Vector3.
  13235. */
  13236. TransformNode.prototype.getAbsolutePosition = function () {
  13237. this.computeWorldMatrix();
  13238. return this._absolutePosition;
  13239. };
  13240. /**
  13241. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13242. * Returns the AbstractMesh.
  13243. */
  13244. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  13245. if (!absolutePosition) {
  13246. return this;
  13247. }
  13248. var absolutePositionX;
  13249. var absolutePositionY;
  13250. var absolutePositionZ;
  13251. if (absolutePosition.x === undefined) {
  13252. if (arguments.length < 3) {
  13253. return this;
  13254. }
  13255. absolutePositionX = arguments[0];
  13256. absolutePositionY = arguments[1];
  13257. absolutePositionZ = arguments[2];
  13258. }
  13259. else {
  13260. absolutePositionX = absolutePosition.x;
  13261. absolutePositionY = absolutePosition.y;
  13262. absolutePositionZ = absolutePosition.z;
  13263. }
  13264. if (this.parent) {
  13265. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13266. invertParentWorldMatrix.invert();
  13267. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13268. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13269. }
  13270. else {
  13271. this.position.x = absolutePositionX;
  13272. this.position.y = absolutePositionY;
  13273. this.position.z = absolutePositionZ;
  13274. }
  13275. return this;
  13276. };
  13277. /**
  13278. * Sets the mesh position in its local space.
  13279. * Returns the AbstractMesh.
  13280. */
  13281. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  13282. this.computeWorldMatrix();
  13283. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13284. return this;
  13285. };
  13286. /**
  13287. * Returns the mesh position in the local space from the current World matrix values.
  13288. * Returns a new Vector3.
  13289. */
  13290. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  13291. this.computeWorldMatrix();
  13292. var invLocalWorldMatrix = this._localWorld.clone();
  13293. invLocalWorldMatrix.invert();
  13294. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13295. };
  13296. /**
  13297. * Translates the mesh along the passed Vector3 in its local space.
  13298. * Returns the AbstractMesh.
  13299. */
  13300. TransformNode.prototype.locallyTranslate = function (vector3) {
  13301. this.computeWorldMatrix(true);
  13302. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13303. return this;
  13304. };
  13305. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13306. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13307. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13308. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13309. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13310. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13311. /// <returns>Mesh oriented towards targetMesh</returns>
  13312. if (yawCor === void 0) { yawCor = 0; }
  13313. if (pitchCor === void 0) { pitchCor = 0; }
  13314. if (rollCor === void 0) { rollCor = 0; }
  13315. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13316. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  13317. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13318. targetPoint.subtractToRef(pos, dv);
  13319. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13320. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13321. var pitch = Math.atan2(dv.y, len);
  13322. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13323. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13324. return this;
  13325. };
  13326. /**
  13327. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13328. * This Vector3 is expressed in the World space.
  13329. */
  13330. TransformNode.prototype.getDirection = function (localAxis) {
  13331. var result = BABYLON.Vector3.Zero();
  13332. this.getDirectionToRef(localAxis, result);
  13333. return result;
  13334. };
  13335. /**
  13336. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13337. * localAxis is expressed in the mesh local space.
  13338. * result is computed in the Wordl space from the mesh World matrix.
  13339. * Returns the AbstractMesh.
  13340. */
  13341. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  13342. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13343. return this;
  13344. };
  13345. TransformNode.prototype.setPivotPoint = function (point, space) {
  13346. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13347. if (this.getScene().getRenderId() == 0) {
  13348. this.computeWorldMatrix(true);
  13349. }
  13350. var wm = this.getWorldMatrix();
  13351. if (space == BABYLON.Space.WORLD) {
  13352. var tmat = BABYLON.Tmp.Matrix[0];
  13353. wm.invertToRef(tmat);
  13354. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13355. }
  13356. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13357. this._pivotMatrix.m[12] = -point.x;
  13358. this._pivotMatrix.m[13] = -point.y;
  13359. this._pivotMatrix.m[14] = -point.z;
  13360. this._cache.pivotMatrixUpdated = true;
  13361. return this;
  13362. };
  13363. /**
  13364. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13365. */
  13366. TransformNode.prototype.getPivotPoint = function () {
  13367. var point = BABYLON.Vector3.Zero();
  13368. this.getPivotPointToRef(point);
  13369. return point;
  13370. };
  13371. /**
  13372. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13373. * Returns the AbstractMesh.
  13374. */
  13375. TransformNode.prototype.getPivotPointToRef = function (result) {
  13376. result.x = -this._pivotMatrix.m[12];
  13377. result.y = -this._pivotMatrix.m[13];
  13378. result.z = -this._pivotMatrix.m[14];
  13379. return this;
  13380. };
  13381. /**
  13382. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13383. */
  13384. TransformNode.prototype.getAbsolutePivotPoint = function () {
  13385. var point = BABYLON.Vector3.Zero();
  13386. this.getAbsolutePivotPointToRef(point);
  13387. return point;
  13388. };
  13389. /**
  13390. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13391. * Returns the AbstractMesh.
  13392. */
  13393. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  13394. result.x = this._pivotMatrix.m[12];
  13395. result.y = this._pivotMatrix.m[13];
  13396. result.z = this._pivotMatrix.m[14];
  13397. this.getPivotPointToRef(result);
  13398. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13399. return this;
  13400. };
  13401. /**
  13402. * Defines the passed mesh as the parent of the current mesh.
  13403. * Returns the AbstractMesh.
  13404. */
  13405. TransformNode.prototype.setParent = function (mesh) {
  13406. var parent = mesh;
  13407. if (mesh == null) {
  13408. var rotation = BABYLON.Tmp.Quaternion[0];
  13409. var position = BABYLON.Tmp.Vector3[0];
  13410. var scale = BABYLON.Tmp.Vector3[1];
  13411. this.getWorldMatrix().decompose(scale, rotation, position);
  13412. if (this.rotationQuaternion) {
  13413. this.rotationQuaternion.copyFrom(rotation);
  13414. }
  13415. else {
  13416. rotation.toEulerAnglesToRef(this.rotation);
  13417. }
  13418. this.position.x = position.x;
  13419. this.position.y = position.y;
  13420. this.position.z = position.z;
  13421. }
  13422. else {
  13423. var position = BABYLON.Tmp.Vector3[0];
  13424. var m1 = BABYLON.Tmp.Matrix[0];
  13425. parent.getWorldMatrix().invertToRef(m1);
  13426. BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position);
  13427. this.position.copyFrom(position);
  13428. }
  13429. this.parent = parent;
  13430. return this;
  13431. };
  13432. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  13433. get: function () {
  13434. return this._nonUniformScaling;
  13435. },
  13436. enumerable: true,
  13437. configurable: true
  13438. });
  13439. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  13440. if (this._nonUniformScaling === value) {
  13441. return false;
  13442. }
  13443. this._nonUniformScaling = true;
  13444. return true;
  13445. };
  13446. /**
  13447. * Attach the current TransformNode to another TransformNode associated with a bone
  13448. * @param bone Bone affecting the TransformNode
  13449. * @param affectedTransformNode TransformNode associated with the bone
  13450. */
  13451. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  13452. this._transformToBoneReferal = affectedTransformNode;
  13453. this.parent = bone;
  13454. if (bone.getWorldMatrix().determinant() < 0) {
  13455. this.scalingDeterminant *= -1;
  13456. }
  13457. return this;
  13458. };
  13459. TransformNode.prototype.detachFromBone = function () {
  13460. if (!this.parent) {
  13461. return this;
  13462. }
  13463. if (this.parent.getWorldMatrix().determinant() < 0) {
  13464. this.scalingDeterminant *= -1;
  13465. }
  13466. this._transformToBoneReferal = null;
  13467. this.parent = null;
  13468. return this;
  13469. };
  13470. /**
  13471. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13472. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13473. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13474. * The passed axis is also normalized.
  13475. * Returns the AbstractMesh.
  13476. */
  13477. TransformNode.prototype.rotate = function (axis, amount, space) {
  13478. axis.normalize();
  13479. if (!this.rotationQuaternion) {
  13480. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13481. this.rotation = BABYLON.Vector3.Zero();
  13482. }
  13483. var rotationQuaternion;
  13484. if (!space || space === BABYLON.Space.LOCAL) {
  13485. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13486. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13487. }
  13488. else {
  13489. if (this.parent) {
  13490. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13491. invertParentWorldMatrix.invert();
  13492. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13493. }
  13494. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13495. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13496. }
  13497. return this;
  13498. };
  13499. /**
  13500. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13501. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13502. * The passed axis is also normalized.
  13503. * Returns the AbstractMesh.
  13504. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13505. */
  13506. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  13507. axis.normalize();
  13508. if (!this.rotationQuaternion) {
  13509. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13510. this.rotation.copyFromFloats(0, 0, 0);
  13511. }
  13512. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13513. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13514. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13515. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13516. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13517. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13518. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13519. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13520. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13521. return this;
  13522. };
  13523. /**
  13524. * Translates the mesh along the axis vector for the passed distance in the given space.
  13525. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13526. * Returns the AbstractMesh.
  13527. */
  13528. TransformNode.prototype.translate = function (axis, distance, space) {
  13529. var displacementVector = axis.scale(distance);
  13530. if (!space || space === BABYLON.Space.LOCAL) {
  13531. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13532. this.setPositionWithLocalVector(tempV3);
  13533. }
  13534. else {
  13535. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13536. }
  13537. return this;
  13538. };
  13539. /**
  13540. * Adds a rotation step to the mesh current rotation.
  13541. * x, y, z are Euler angles expressed in radians.
  13542. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13543. * This means this rotation is made in the mesh local space only.
  13544. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13545. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13546. * ```javascript
  13547. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13548. * ```
  13549. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13550. * 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.
  13551. * Returns the AbstractMesh.
  13552. */
  13553. TransformNode.prototype.addRotation = function (x, y, z) {
  13554. var rotationQuaternion;
  13555. if (this.rotationQuaternion) {
  13556. rotationQuaternion = this.rotationQuaternion;
  13557. }
  13558. else {
  13559. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13560. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13561. }
  13562. var accumulation = BABYLON.Tmp.Quaternion[0];
  13563. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13564. rotationQuaternion.multiplyInPlace(accumulation);
  13565. if (!this.rotationQuaternion) {
  13566. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13567. }
  13568. return this;
  13569. };
  13570. /**
  13571. * Computes the mesh World matrix and returns it.
  13572. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  13573. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  13574. * If the parameter `force`is set to `true`, the actual computation is done.
  13575. * Returns the mesh World Matrix.
  13576. */
  13577. TransformNode.prototype.computeWorldMatrix = function (force) {
  13578. if (this._isWorldMatrixFrozen) {
  13579. return this._worldMatrix;
  13580. }
  13581. if (!force && this.isSynchronized(true)) {
  13582. return this._worldMatrix;
  13583. }
  13584. this._cache.position.copyFrom(this.position);
  13585. this._cache.scaling.copyFrom(this.scaling);
  13586. this._cache.pivotMatrixUpdated = false;
  13587. this._cache.billboardMode = this.billboardMode;
  13588. this._currentRenderId = this.getScene().getRenderId();
  13589. this._isDirty = false;
  13590. // Scaling
  13591. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13592. // Rotation
  13593. //rotate, if quaternion is set and rotation was used
  13594. if (this.rotationQuaternion) {
  13595. var len = this.rotation.length();
  13596. if (len) {
  13597. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13598. this.rotation.copyFromFloats(0, 0, 0);
  13599. }
  13600. }
  13601. if (this.rotationQuaternion) {
  13602. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13603. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13604. }
  13605. else {
  13606. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13607. this._cache.rotation.copyFrom(this.rotation);
  13608. }
  13609. // Translation
  13610. var camera = this.getScene().activeCamera;
  13611. if (this.infiniteDistance && !this.parent && camera) {
  13612. var cameraWorldMatrix = camera.getWorldMatrix();
  13613. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13614. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13615. }
  13616. else {
  13617. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13618. }
  13619. // Composing transformations
  13620. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13621. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13622. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13623. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  13624. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  13625. // Need to decompose each rotation here
  13626. var currentPosition = BABYLON.Tmp.Vector3[3];
  13627. if (this.parent && this.parent.getWorldMatrix) {
  13628. if (this._transformToBoneReferal) {
  13629. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13630. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13631. }
  13632. else {
  13633. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13634. }
  13635. }
  13636. else {
  13637. currentPosition.copyFrom(this.position);
  13638. }
  13639. currentPosition.subtractInPlace(camera.globalPosition);
  13640. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13641. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  13642. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13643. }
  13644. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  13645. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13646. }
  13647. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  13648. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13649. }
  13650. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13651. }
  13652. else {
  13653. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  13654. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13655. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13656. }
  13657. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13658. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13659. }
  13660. // Local world
  13661. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13662. // Parent
  13663. if (this.parent && this.parent.getWorldMatrix) {
  13664. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  13665. if (this._transformToBoneReferal) {
  13666. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13667. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13668. }
  13669. else {
  13670. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13671. }
  13672. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13673. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13674. this._worldMatrix.copyFrom(this._localWorld);
  13675. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13676. }
  13677. else {
  13678. if (this._transformToBoneReferal) {
  13679. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13680. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13681. }
  13682. else {
  13683. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13684. }
  13685. }
  13686. this._markSyncedWithParent();
  13687. }
  13688. else {
  13689. this._worldMatrix.copyFrom(this._localWorld);
  13690. }
  13691. // Post multiply inverse of pivotMatrix
  13692. if (this._postMultiplyPivotMatrix) {
  13693. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  13694. }
  13695. // Normal matrix
  13696. if (this.scaling.isNonUniform) {
  13697. this._updateNonUniformScalingState(true);
  13698. }
  13699. else if (this.parent && this.parent._nonUniformScaling) {
  13700. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  13701. }
  13702. else {
  13703. this._updateNonUniformScalingState(false);
  13704. }
  13705. this._afterComputeWorldMatrix();
  13706. // Absolute position
  13707. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13708. // Callbacks
  13709. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13710. if (!this._poseMatrix) {
  13711. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13712. }
  13713. return this._worldMatrix;
  13714. };
  13715. TransformNode.prototype._afterComputeWorldMatrix = function () {
  13716. };
  13717. /**
  13718. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13719. * @param func: callback function to add
  13720. *
  13721. * Returns the TransformNode.
  13722. */
  13723. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13724. this.onAfterWorldMatrixUpdateObservable.add(func);
  13725. return this;
  13726. };
  13727. /**
  13728. * Removes a registered callback function.
  13729. * Returns the TransformNode.
  13730. */
  13731. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13732. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13733. return this;
  13734. };
  13735. TransformNode.prototype.clone = function (name, newParent) {
  13736. var _this = this;
  13737. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  13738. result.name = name;
  13739. result.id = name;
  13740. if (newParent) {
  13741. result.parent = newParent;
  13742. }
  13743. return result;
  13744. };
  13745. TransformNode.prototype.serialize = function (serializationObject) {
  13746. if (serializationObject === void 0) { serializationObject = null; }
  13747. if (!serializationObject) {
  13748. serializationObject = {};
  13749. }
  13750. serializationObject.name = this.name;
  13751. serializationObject.id = this.id;
  13752. serializationObject.type = this.getClassName();
  13753. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  13754. serializationObject.tags = BABYLON.Tags.GetTags(this);
  13755. }
  13756. serializationObject.position = this.position.asArray();
  13757. if (this.rotationQuaternion) {
  13758. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  13759. }
  13760. else if (this.rotation) {
  13761. serializationObject.rotation = this.rotation.asArray();
  13762. }
  13763. serializationObject.scaling = this.scaling.asArray();
  13764. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  13765. serializationObject.isEnabled = this.isEnabled();
  13766. serializationObject.infiniteDistance = this.infiniteDistance;
  13767. serializationObject.billboardMode = this.billboardMode;
  13768. // Parent
  13769. if (this.parent) {
  13770. serializationObject.parentId = this.parent.id;
  13771. }
  13772. // Metadata
  13773. if (this.metadata) {
  13774. serializationObject.metadata = this.metadata;
  13775. }
  13776. return serializationObject;
  13777. };
  13778. // Statics
  13779. /**
  13780. * Returns a new TransformNode object parsed from the source provided.
  13781. * The parameter `parsedMesh` is the source.
  13782. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  13783. */
  13784. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  13785. var transformNode = new TransformNode(parsedTransformNode.name, scene);
  13786. transformNode.id = parsedTransformNode.id;
  13787. if (BABYLON.Tags) {
  13788. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  13789. }
  13790. transformNode.position = BABYLON.Vector3.FromArray(parsedTransformNode.position);
  13791. if (parsedTransformNode.metadata !== undefined) {
  13792. transformNode.metadata = parsedTransformNode.metadata;
  13793. }
  13794. if (parsedTransformNode.rotationQuaternion) {
  13795. transformNode.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedTransformNode.rotationQuaternion);
  13796. }
  13797. else if (parsedTransformNode.rotation) {
  13798. transformNode.rotation = BABYLON.Vector3.FromArray(parsedTransformNode.rotation);
  13799. }
  13800. transformNode.scaling = BABYLON.Vector3.FromArray(parsedTransformNode.scaling);
  13801. if (parsedTransformNode.localMatrix) {
  13802. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  13803. }
  13804. else if (parsedTransformNode.pivotMatrix) {
  13805. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  13806. }
  13807. transformNode.setEnabled(parsedTransformNode.isEnabled);
  13808. transformNode.infiniteDistance = parsedTransformNode.infiniteDistance;
  13809. transformNode.billboardMode = parsedTransformNode.billboardMode;
  13810. // Parent
  13811. if (parsedTransformNode.parentId) {
  13812. transformNode._waitingParentId = parsedTransformNode.parentId;
  13813. }
  13814. return transformNode;
  13815. };
  13816. // Statics
  13817. TransformNode.BILLBOARDMODE_NONE = 0;
  13818. TransformNode.BILLBOARDMODE_X = 1;
  13819. TransformNode.BILLBOARDMODE_Y = 2;
  13820. TransformNode.BILLBOARDMODE_Z = 4;
  13821. TransformNode.BILLBOARDMODE_ALL = 7;
  13822. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13823. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  13824. return TransformNode;
  13825. }(BABYLON.Node));
  13826. BABYLON.TransformNode = TransformNode;
  13827. })(BABYLON || (BABYLON = {}));
  13828. //# sourceMappingURL=babylon.transformNode.js.map
  13829. var BABYLON;
  13830. (function (BABYLON) {
  13831. var AbstractMesh = /** @class */ (function (_super) {
  13832. __extends(AbstractMesh, _super);
  13833. // Constructor
  13834. function AbstractMesh(name, scene) {
  13835. if (scene === void 0) { scene = null; }
  13836. var _this = _super.call(this, name, scene, false) || this;
  13837. _this._facetNb = 0; // facet number
  13838. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  13839. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  13840. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  13841. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  13842. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  13843. _this._subDiv = {
  13844. max: 1,
  13845. X: 1,
  13846. Y: 1,
  13847. Z: 1
  13848. };
  13849. _this._facetDepthSort = false; // is the facet depth sort enabled
  13850. // Events
  13851. /**
  13852. * An event triggered when this mesh collides with another one
  13853. * @type {BABYLON.Observable}
  13854. */
  13855. _this.onCollideObservable = new BABYLON.Observable();
  13856. /**
  13857. * An event triggered when the collision's position changes
  13858. * @type {BABYLON.Observable}
  13859. */
  13860. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  13861. /**
  13862. * An event triggered when material is changed
  13863. * @type {BABYLON.Observable}
  13864. */
  13865. _this.onMaterialChangedObservable = new BABYLON.Observable();
  13866. // Properties
  13867. _this.definedFacingForward = true; // orientation for POV movement & rotation
  13868. /**
  13869. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  13870. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  13871. * or
  13872. * 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.
  13873. * for more info check WebGl documentations
  13874. */
  13875. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  13876. /**
  13877. * 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:
  13878. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  13879. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  13880. * 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.
  13881. */
  13882. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  13883. /**
  13884. * 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.
  13885. * The default value is -1 which means don't break the query and wait till the result.
  13886. */
  13887. _this.occlusionRetryCount = -1;
  13888. _this._occlusionInternalRetryCounter = 0;
  13889. _this._isOccluded = false;
  13890. _this._isOcclusionQueryInProgress = false;
  13891. _this.visibility = 1.0;
  13892. _this.alphaIndex = Number.MAX_VALUE;
  13893. _this.isVisible = true;
  13894. _this.isPickable = true;
  13895. _this.showBoundingBox = false;
  13896. _this.showSubMeshesBoundingBox = false;
  13897. _this.isBlocker = false;
  13898. _this.enablePointerMoveEvents = false;
  13899. _this.renderingGroupId = 0;
  13900. _this._receiveShadows = false;
  13901. _this.renderOutline = false;
  13902. _this.outlineColor = BABYLON.Color3.Red();
  13903. _this.outlineWidth = 0.02;
  13904. _this.renderOverlay = false;
  13905. _this.overlayColor = BABYLON.Color3.Red();
  13906. _this.overlayAlpha = 0.5;
  13907. _this._hasVertexAlpha = false;
  13908. _this._useVertexColors = true;
  13909. _this._computeBonesUsingShaders = true;
  13910. _this._numBoneInfluencers = 4;
  13911. _this._applyFog = true;
  13912. _this.useOctreeForRenderingSelection = true;
  13913. _this.useOctreeForPicking = true;
  13914. _this.useOctreeForCollisions = true;
  13915. _this._layerMask = 0x0FFFFFFF;
  13916. /**
  13917. * True if the mesh must be rendered in any case.
  13918. */
  13919. _this.alwaysSelectAsActiveMesh = false;
  13920. // Collisions
  13921. _this._checkCollisions = false;
  13922. _this._collisionMask = -1;
  13923. _this._collisionGroup = -1;
  13924. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  13925. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  13926. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  13927. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  13928. // Edges
  13929. _this.edgesWidth = 1;
  13930. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  13931. // Cache
  13932. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  13933. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  13934. _this._isDisposed = false;
  13935. _this._renderId = 0;
  13936. _this._intersectionsInProgress = new Array();
  13937. _this._unIndexed = false;
  13938. _this._lightSources = new Array();
  13939. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13940. if (collidedMesh === void 0) { collidedMesh = null; }
  13941. //TODO move this to the collision coordinator!
  13942. if (_this.getScene().workerCollisions)
  13943. newPosition.multiplyInPlace(_this._collider.radius);
  13944. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  13945. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  13946. _this.position.addInPlace(_this._diffPositionForCollisions);
  13947. }
  13948. if (collidedMesh) {
  13949. _this.onCollideObservable.notifyObservers(collidedMesh);
  13950. }
  13951. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  13952. };
  13953. _this.getScene().addMesh(_this);
  13954. _this._resyncLightSources();
  13955. return _this;
  13956. }
  13957. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  13958. get: function () {
  13959. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  13960. },
  13961. enumerable: true,
  13962. configurable: true
  13963. });
  13964. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  13965. get: function () {
  13966. return BABYLON.TransformNode.BILLBOARDMODE_X;
  13967. },
  13968. enumerable: true,
  13969. configurable: true
  13970. });
  13971. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  13972. get: function () {
  13973. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  13974. },
  13975. enumerable: true,
  13976. configurable: true
  13977. });
  13978. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  13979. get: function () {
  13980. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  13981. },
  13982. enumerable: true,
  13983. configurable: true
  13984. });
  13985. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  13986. get: function () {
  13987. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  13988. },
  13989. enumerable: true,
  13990. configurable: true
  13991. });
  13992. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  13993. /**
  13994. * Read-only : the number of facets in the mesh
  13995. */
  13996. get: function () {
  13997. return this._facetNb;
  13998. },
  13999. enumerable: true,
  14000. configurable: true
  14001. });
  14002. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  14003. /**
  14004. * The number (integer) of subdivisions per axis in the partioning space
  14005. */
  14006. get: function () {
  14007. return this._partitioningSubdivisions;
  14008. },
  14009. set: function (nb) {
  14010. this._partitioningSubdivisions = nb;
  14011. },
  14012. enumerable: true,
  14013. configurable: true
  14014. });
  14015. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  14016. /**
  14017. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  14018. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  14019. */
  14020. get: function () {
  14021. return this._partitioningBBoxRatio;
  14022. },
  14023. set: function (ratio) {
  14024. this._partitioningBBoxRatio = ratio;
  14025. },
  14026. enumerable: true,
  14027. configurable: true
  14028. });
  14029. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  14030. /**
  14031. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  14032. * Works only for updatable meshes.
  14033. */
  14034. get: function () {
  14035. return this._facetDepthSort;
  14036. },
  14037. set: function (sort) {
  14038. this._facetDepthSort = sort;
  14039. },
  14040. enumerable: true,
  14041. configurable: true
  14042. });
  14043. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  14044. /**
  14045. * The location (Vector3) where the facet depth sort must be computed from.
  14046. * By default, the active camera position.
  14047. * Used only when facet depth sort is enabled.
  14048. */
  14049. get: function () {
  14050. return this._facetDepthSortFrom;
  14051. },
  14052. set: function (location) {
  14053. this._facetDepthSortFrom = location;
  14054. },
  14055. enumerable: true,
  14056. configurable: true
  14057. });
  14058. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  14059. /**
  14060. * Read-only boolean : is the feature facetData enabled ?
  14061. */
  14062. get: function () {
  14063. return this._facetDataEnabled;
  14064. },
  14065. enumerable: true,
  14066. configurable: true
  14067. });
  14068. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  14069. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  14070. return false;
  14071. }
  14072. this._markSubMeshesAsMiscDirty();
  14073. return true;
  14074. };
  14075. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  14076. set: function (callback) {
  14077. if (this._onCollideObserver) {
  14078. this.onCollideObservable.remove(this._onCollideObserver);
  14079. }
  14080. this._onCollideObserver = this.onCollideObservable.add(callback);
  14081. },
  14082. enumerable: true,
  14083. configurable: true
  14084. });
  14085. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  14086. set: function (callback) {
  14087. if (this._onCollisionPositionChangeObserver) {
  14088. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  14089. }
  14090. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  14091. },
  14092. enumerable: true,
  14093. configurable: true
  14094. });
  14095. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  14096. /**
  14097. * 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.
  14098. */
  14099. get: function () {
  14100. return this._isOccluded;
  14101. },
  14102. set: function (value) {
  14103. this._isOccluded = value;
  14104. },
  14105. enumerable: true,
  14106. configurable: true
  14107. });
  14108. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  14109. /**
  14110. * Flag to check the progress status of the query
  14111. */
  14112. get: function () {
  14113. return this._isOcclusionQueryInProgress;
  14114. },
  14115. enumerable: true,
  14116. configurable: true
  14117. });
  14118. Object.defineProperty(AbstractMesh.prototype, "material", {
  14119. get: function () {
  14120. return this._material;
  14121. },
  14122. set: function (value) {
  14123. if (this._material === value) {
  14124. return;
  14125. }
  14126. this._material = value;
  14127. if (this.onMaterialChangedObservable.hasObservers) {
  14128. this.onMaterialChangedObservable.notifyObservers(this);
  14129. }
  14130. if (!this.subMeshes) {
  14131. return;
  14132. }
  14133. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14134. var subMesh = _a[_i];
  14135. subMesh.setEffect(null);
  14136. }
  14137. },
  14138. enumerable: true,
  14139. configurable: true
  14140. });
  14141. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  14142. get: function () {
  14143. return this._receiveShadows;
  14144. },
  14145. set: function (value) {
  14146. if (this._receiveShadows === value) {
  14147. return;
  14148. }
  14149. this._receiveShadows = value;
  14150. this._markSubMeshesAsLightDirty();
  14151. },
  14152. enumerable: true,
  14153. configurable: true
  14154. });
  14155. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  14156. get: function () {
  14157. return this._hasVertexAlpha;
  14158. },
  14159. set: function (value) {
  14160. if (this._hasVertexAlpha === value) {
  14161. return;
  14162. }
  14163. this._hasVertexAlpha = value;
  14164. this._markSubMeshesAsAttributesDirty();
  14165. },
  14166. enumerable: true,
  14167. configurable: true
  14168. });
  14169. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  14170. get: function () {
  14171. return this._useVertexColors;
  14172. },
  14173. set: function (value) {
  14174. if (this._useVertexColors === value) {
  14175. return;
  14176. }
  14177. this._useVertexColors = value;
  14178. this._markSubMeshesAsAttributesDirty();
  14179. },
  14180. enumerable: true,
  14181. configurable: true
  14182. });
  14183. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  14184. get: function () {
  14185. return this._computeBonesUsingShaders;
  14186. },
  14187. set: function (value) {
  14188. if (this._computeBonesUsingShaders === value) {
  14189. return;
  14190. }
  14191. this._computeBonesUsingShaders = value;
  14192. this._markSubMeshesAsAttributesDirty();
  14193. },
  14194. enumerable: true,
  14195. configurable: true
  14196. });
  14197. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  14198. get: function () {
  14199. return this._numBoneInfluencers;
  14200. },
  14201. set: function (value) {
  14202. if (this._numBoneInfluencers === value) {
  14203. return;
  14204. }
  14205. this._numBoneInfluencers = value;
  14206. this._markSubMeshesAsAttributesDirty();
  14207. },
  14208. enumerable: true,
  14209. configurable: true
  14210. });
  14211. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  14212. get: function () {
  14213. return this._applyFog;
  14214. },
  14215. set: function (value) {
  14216. if (this._applyFog === value) {
  14217. return;
  14218. }
  14219. this._applyFog = value;
  14220. this._markSubMeshesAsMiscDirty();
  14221. },
  14222. enumerable: true,
  14223. configurable: true
  14224. });
  14225. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  14226. get: function () {
  14227. return this._layerMask;
  14228. },
  14229. set: function (value) {
  14230. if (value === this._layerMask) {
  14231. return;
  14232. }
  14233. this._layerMask = value;
  14234. this._resyncLightSources();
  14235. },
  14236. enumerable: true,
  14237. configurable: true
  14238. });
  14239. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  14240. get: function () {
  14241. return this._collisionMask;
  14242. },
  14243. set: function (mask) {
  14244. this._collisionMask = !isNaN(mask) ? mask : -1;
  14245. },
  14246. enumerable: true,
  14247. configurable: true
  14248. });
  14249. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  14250. get: function () {
  14251. return this._collisionGroup;
  14252. },
  14253. set: function (mask) {
  14254. this._collisionGroup = !isNaN(mask) ? mask : -1;
  14255. },
  14256. enumerable: true,
  14257. configurable: true
  14258. });
  14259. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  14260. get: function () {
  14261. return null;
  14262. },
  14263. enumerable: true,
  14264. configurable: true
  14265. });
  14266. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  14267. get: function () {
  14268. return this._skeleton;
  14269. },
  14270. set: function (value) {
  14271. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  14272. this._skeleton._unregisterMeshWithPoseMatrix(this);
  14273. }
  14274. if (value && value.needInitialSkinMatrix) {
  14275. value._registerMeshWithPoseMatrix(this);
  14276. }
  14277. this._skeleton = value;
  14278. if (!this._skeleton) {
  14279. this._bonesTransformMatrices = null;
  14280. }
  14281. this._markSubMeshesAsAttributesDirty();
  14282. },
  14283. enumerable: true,
  14284. configurable: true
  14285. });
  14286. /**
  14287. * Boolean : true if the mesh has been disposed.
  14288. */
  14289. AbstractMesh.prototype.isDisposed = function () {
  14290. return this._isDisposed;
  14291. };
  14292. /**
  14293. * Returns the string "AbstractMesh"
  14294. */
  14295. AbstractMesh.prototype.getClassName = function () {
  14296. return "AbstractMesh";
  14297. };
  14298. /**
  14299. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14300. */
  14301. AbstractMesh.prototype.toString = function (fullDetails) {
  14302. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  14303. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  14304. if (this._skeleton) {
  14305. ret += ", skeleton: " + this._skeleton.name;
  14306. }
  14307. if (fullDetails) {
  14308. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  14309. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  14310. }
  14311. return ret;
  14312. };
  14313. AbstractMesh.prototype._rebuild = function () {
  14314. if (this._occlusionQuery) {
  14315. this._occlusionQuery = null;
  14316. }
  14317. if (this._edgesRenderer) {
  14318. this._edgesRenderer._rebuild();
  14319. }
  14320. if (!this.subMeshes) {
  14321. return;
  14322. }
  14323. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14324. var subMesh = _a[_i];
  14325. subMesh._rebuild();
  14326. }
  14327. };
  14328. AbstractMesh.prototype._resyncLightSources = function () {
  14329. this._lightSources.length = 0;
  14330. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  14331. var light = _a[_i];
  14332. if (!light.isEnabled()) {
  14333. continue;
  14334. }
  14335. if (light.canAffectMesh(this)) {
  14336. this._lightSources.push(light);
  14337. }
  14338. }
  14339. this._markSubMeshesAsLightDirty();
  14340. };
  14341. AbstractMesh.prototype._resyncLighSource = function (light) {
  14342. var isIn = light.isEnabled() && light.canAffectMesh(this);
  14343. var index = this._lightSources.indexOf(light);
  14344. if (index === -1) {
  14345. if (!isIn) {
  14346. return;
  14347. }
  14348. this._lightSources.push(light);
  14349. }
  14350. else {
  14351. if (isIn) {
  14352. return;
  14353. }
  14354. this._lightSources.splice(index, 1);
  14355. }
  14356. this._markSubMeshesAsLightDirty();
  14357. };
  14358. AbstractMesh.prototype._removeLightSource = function (light) {
  14359. var index = this._lightSources.indexOf(light);
  14360. if (index === -1) {
  14361. return;
  14362. }
  14363. this._lightSources.splice(index, 1);
  14364. };
  14365. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  14366. if (!this.subMeshes) {
  14367. return;
  14368. }
  14369. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14370. var subMesh = _a[_i];
  14371. if (subMesh._materialDefines) {
  14372. func(subMesh._materialDefines);
  14373. }
  14374. }
  14375. };
  14376. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  14377. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  14378. };
  14379. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  14380. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  14381. };
  14382. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  14383. if (!this.subMeshes) {
  14384. return;
  14385. }
  14386. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14387. var subMesh = _a[_i];
  14388. var material = subMesh.getMaterial();
  14389. if (material) {
  14390. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  14391. }
  14392. }
  14393. };
  14394. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  14395. /**
  14396. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14397. * Default : (1.0, 1.0, 1.0)
  14398. */
  14399. get: function () {
  14400. return this._scaling;
  14401. },
  14402. /**
  14403. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14404. * Default : (1.0, 1.0, 1.0)
  14405. */
  14406. set: function (newScaling) {
  14407. this._scaling = newScaling;
  14408. if (this.physicsImpostor) {
  14409. this.physicsImpostor.forceUpdate();
  14410. }
  14411. },
  14412. enumerable: true,
  14413. configurable: true
  14414. });
  14415. // Methods
  14416. /**
  14417. * Disables the mesh edger rendering mode.
  14418. * Returns the AbstractMesh.
  14419. */
  14420. AbstractMesh.prototype.disableEdgesRendering = function () {
  14421. if (this._edgesRenderer) {
  14422. this._edgesRenderer.dispose();
  14423. this._edgesRenderer = null;
  14424. }
  14425. return this;
  14426. };
  14427. /**
  14428. * Enables the edge rendering mode on the mesh.
  14429. * This mode makes the mesh edges visible.
  14430. * Returns the AbstractMesh.
  14431. */
  14432. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  14433. if (epsilon === void 0) { epsilon = 0.95; }
  14434. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  14435. this.disableEdgesRendering();
  14436. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  14437. return this;
  14438. };
  14439. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  14440. /**
  14441. * Returns true if the mesh is blocked. Used by the class Mesh.
  14442. * Returns the boolean `false` by default.
  14443. */
  14444. get: function () {
  14445. return false;
  14446. },
  14447. enumerable: true,
  14448. configurable: true
  14449. });
  14450. /**
  14451. * Returns the mesh itself by default, used by the class Mesh.
  14452. * Returned type : AbstractMesh
  14453. */
  14454. AbstractMesh.prototype.getLOD = function (camera) {
  14455. return this;
  14456. };
  14457. /**
  14458. * Returns 0 by default, used by the class Mesh.
  14459. * Returns an integer.
  14460. */
  14461. AbstractMesh.prototype.getTotalVertices = function () {
  14462. return 0;
  14463. };
  14464. /**
  14465. * Returns null by default, used by the class Mesh.
  14466. * Returned type : integer array
  14467. */
  14468. AbstractMesh.prototype.getIndices = function () {
  14469. return null;
  14470. };
  14471. /**
  14472. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  14473. * Returned type : float array or Float32Array
  14474. */
  14475. AbstractMesh.prototype.getVerticesData = function (kind) {
  14476. return null;
  14477. };
  14478. /**
  14479. * Sets the vertex data of the mesh geometry for the requested `kind`.
  14480. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  14481. * The `data` are either a numeric array either a Float32Array.
  14482. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  14483. * 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).
  14484. * Note that a new underlying VertexBuffer object is created each call.
  14485. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  14486. *
  14487. * Possible `kind` values :
  14488. * - BABYLON.VertexBuffer.PositionKind
  14489. * - BABYLON.VertexBuffer.UVKind
  14490. * - BABYLON.VertexBuffer.UV2Kind
  14491. * - BABYLON.VertexBuffer.UV3Kind
  14492. * - BABYLON.VertexBuffer.UV4Kind
  14493. * - BABYLON.VertexBuffer.UV5Kind
  14494. * - BABYLON.VertexBuffer.UV6Kind
  14495. * - BABYLON.VertexBuffer.ColorKind
  14496. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14497. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14498. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14499. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14500. *
  14501. * Returns the Mesh.
  14502. */
  14503. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14504. return this;
  14505. };
  14506. /**
  14507. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  14508. * If the mesh has no geometry, it is simply returned as it is.
  14509. * The `data` are either a numeric array either a Float32Array.
  14510. * No new underlying VertexBuffer object is created.
  14511. * 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.
  14512. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  14513. *
  14514. * Possible `kind` values :
  14515. * - BABYLON.VertexBuffer.PositionKind
  14516. * - BABYLON.VertexBuffer.UVKind
  14517. * - BABYLON.VertexBuffer.UV2Kind
  14518. * - BABYLON.VertexBuffer.UV3Kind
  14519. * - BABYLON.VertexBuffer.UV4Kind
  14520. * - BABYLON.VertexBuffer.UV5Kind
  14521. * - BABYLON.VertexBuffer.UV6Kind
  14522. * - BABYLON.VertexBuffer.ColorKind
  14523. * - BABYLON.VertexBuffer.MatricesIndicesKind
  14524. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  14525. * - BABYLON.VertexBuffer.MatricesWeightsKind
  14526. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  14527. *
  14528. * Returns the Mesh.
  14529. */
  14530. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14531. return this;
  14532. };
  14533. /**
  14534. * Sets the mesh indices.
  14535. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  14536. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  14537. * This method creates a new index buffer each call.
  14538. * Returns the Mesh.
  14539. */
  14540. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  14541. return this;
  14542. };
  14543. /** Returns false by default, used by the class Mesh.
  14544. * Returns a boolean
  14545. */
  14546. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  14547. return false;
  14548. };
  14549. /**
  14550. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  14551. * Returns a BoundingInfo
  14552. */
  14553. AbstractMesh.prototype.getBoundingInfo = function () {
  14554. if (this._masterMesh) {
  14555. return this._masterMesh.getBoundingInfo();
  14556. }
  14557. if (!this._boundingInfo) {
  14558. this._updateBoundingInfo();
  14559. }
  14560. return this._boundingInfo;
  14561. };
  14562. /**
  14563. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  14564. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  14565. */
  14566. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  14567. if (includeDescendants === void 0) { includeDescendants = true; }
  14568. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  14569. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  14570. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  14571. if (maxDimension === 0) {
  14572. return this;
  14573. }
  14574. var scale = 1 / maxDimension;
  14575. this.scaling.scaleInPlace(scale);
  14576. return this;
  14577. };
  14578. /**
  14579. * Sets a mesh new object BoundingInfo.
  14580. * Returns the AbstractMesh.
  14581. */
  14582. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  14583. this._boundingInfo = boundingInfo;
  14584. return this;
  14585. };
  14586. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  14587. get: function () {
  14588. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  14589. },
  14590. enumerable: true,
  14591. configurable: true
  14592. });
  14593. AbstractMesh.prototype._preActivate = function () {
  14594. };
  14595. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  14596. };
  14597. AbstractMesh.prototype._activate = function (renderId) {
  14598. this._renderId = renderId;
  14599. };
  14600. /**
  14601. * Returns the latest update of the World matrix
  14602. * Returns a Matrix.
  14603. */
  14604. AbstractMesh.prototype.getWorldMatrix = function () {
  14605. if (this._masterMesh) {
  14606. return this._masterMesh.getWorldMatrix();
  14607. }
  14608. return _super.prototype.getWorldMatrix.call(this);
  14609. };
  14610. // ================================== Point of View Movement =================================
  14611. /**
  14612. * Perform relative position change from the point of view of behind the front of the mesh.
  14613. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14614. * Supports definition of mesh facing forward or backward.
  14615. * @param {number} amountRight
  14616. * @param {number} amountUp
  14617. * @param {number} amountForward
  14618. *
  14619. * Returns the AbstractMesh.
  14620. */
  14621. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  14622. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  14623. return this;
  14624. };
  14625. /**
  14626. * Calculate relative position change from the point of view of behind the front of the mesh.
  14627. * This is performed taking into account the meshes current rotation, so you do not have to care.
  14628. * Supports definition of mesh facing forward or backward.
  14629. * @param {number} amountRight
  14630. * @param {number} amountUp
  14631. * @param {number} amountForward
  14632. *
  14633. * Returns a new Vector3.
  14634. */
  14635. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  14636. var rotMatrix = new BABYLON.Matrix();
  14637. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14638. rotQuaternion.toRotationMatrix(rotMatrix);
  14639. var translationDelta = BABYLON.Vector3.Zero();
  14640. var defForwardMult = this.definedFacingForward ? -1 : 1;
  14641. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  14642. return translationDelta;
  14643. };
  14644. // ================================== Point of View Rotation =================================
  14645. /**
  14646. * Perform relative rotation change from the point of view of behind the front of the mesh.
  14647. * Supports definition of mesh facing forward or backward.
  14648. * @param {number} flipBack
  14649. * @param {number} twirlClockwise
  14650. * @param {number} tiltRight
  14651. *
  14652. * Returns the AbstractMesh.
  14653. */
  14654. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14655. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  14656. return this;
  14657. };
  14658. /**
  14659. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  14660. * Supports definition of mesh facing forward or backward.
  14661. * @param {number} flipBack
  14662. * @param {number} twirlClockwise
  14663. * @param {number} tiltRight
  14664. *
  14665. * Returns a new Vector3.
  14666. */
  14667. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  14668. var defForwardMult = this.definedFacingForward ? 1 : -1;
  14669. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  14670. };
  14671. /**
  14672. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  14673. * @param includeDescendants Include bounding info from descendants as well (true by default).
  14674. */
  14675. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  14676. if (includeDescendants === void 0) { includeDescendants = true; }
  14677. this.computeWorldMatrix(true);
  14678. var min;
  14679. var max;
  14680. var boundingInfo = this.getBoundingInfo();
  14681. if (!this.subMeshes || !boundingInfo) {
  14682. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14683. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14684. }
  14685. else {
  14686. min = boundingInfo.boundingBox.minimumWorld;
  14687. max = boundingInfo.boundingBox.maximumWorld;
  14688. }
  14689. if (includeDescendants) {
  14690. var descendants = this.getDescendants(false);
  14691. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14692. var descendant = descendants_1[_i];
  14693. var childMesh = descendant;
  14694. childMesh.computeWorldMatrix(true);
  14695. var childBoundingInfo = childMesh.getBoundingInfo();
  14696. if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) {
  14697. continue;
  14698. }
  14699. var boundingBox = childBoundingInfo.boundingBox;
  14700. var minBox = boundingBox.minimumWorld;
  14701. var maxBox = boundingBox.maximumWorld;
  14702. BABYLON.Tools.CheckExtends(minBox, min, max);
  14703. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14704. }
  14705. }
  14706. return {
  14707. min: min,
  14708. max: max
  14709. };
  14710. };
  14711. /**
  14712. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  14713. * Returns the AbstractMesh.
  14714. */
  14715. AbstractMesh.prototype._updateBoundingInfo = function () {
  14716. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  14717. this._boundingInfo.update(this.worldMatrixFromCache);
  14718. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14719. return this;
  14720. };
  14721. /**
  14722. * Update a mesh's children BoundingInfo objects only.
  14723. * Returns the AbstractMesh.
  14724. */
  14725. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  14726. if (!this.subMeshes) {
  14727. return this;
  14728. }
  14729. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  14730. var subMesh = this.subMeshes[subIndex];
  14731. if (!subMesh.IsGlobal) {
  14732. subMesh.updateBoundingInfo(matrix);
  14733. }
  14734. }
  14735. return this;
  14736. };
  14737. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  14738. // Bounding info
  14739. this._updateBoundingInfo();
  14740. };
  14741. /**
  14742. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14743. * A mesh is in the frustum if its bounding box intersects the frustum.
  14744. * Boolean returned.
  14745. */
  14746. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14747. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14748. };
  14749. /**
  14750. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14751. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14752. * Boolean returned.
  14753. */
  14754. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14755. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14756. ;
  14757. };
  14758. /**
  14759. * True if the mesh intersects another mesh or a SolidParticle object.
  14760. * 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)
  14761. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14762. * Returns a boolean.
  14763. */
  14764. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14765. if (precise === void 0) { precise = false; }
  14766. if (!this._boundingInfo || !mesh._boundingInfo) {
  14767. return false;
  14768. }
  14769. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14770. return true;
  14771. }
  14772. if (includeDescendants) {
  14773. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14774. var child = _a[_i];
  14775. if (child.intersectsMesh(mesh, precise, true)) {
  14776. return true;
  14777. }
  14778. }
  14779. }
  14780. return false;
  14781. };
  14782. /**
  14783. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14784. * Returns a boolean.
  14785. */
  14786. AbstractMesh.prototype.intersectsPoint = function (point) {
  14787. if (!this._boundingInfo) {
  14788. return false;
  14789. }
  14790. return this._boundingInfo.intersectsPoint(point);
  14791. };
  14792. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14793. return this.physicsImpostor;
  14794. };
  14795. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14796. if (camera === void 0) { camera = null; }
  14797. if (!camera) {
  14798. camera = this.getScene().activeCamera;
  14799. }
  14800. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14801. };
  14802. /**
  14803. * Returns the distance from the mesh to the active camera.
  14804. * Returns a float.
  14805. */
  14806. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14807. if (camera === void 0) { camera = null; }
  14808. if (!camera) {
  14809. camera = this.getScene().activeCamera;
  14810. }
  14811. return this.absolutePosition.subtract(camera.position).length();
  14812. };
  14813. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14814. if (!this.physicsImpostor) {
  14815. return this;
  14816. }
  14817. this.physicsImpostor.applyImpulse(force, contactPoint);
  14818. return this;
  14819. };
  14820. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14821. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14822. return this;
  14823. }
  14824. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14825. mainPivot: pivot1,
  14826. connectedPivot: pivot2,
  14827. nativeParams: options
  14828. });
  14829. return this;
  14830. };
  14831. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14832. // Collisions
  14833. /**
  14834. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14835. * Default `false`.
  14836. */
  14837. get: function () {
  14838. return this._checkCollisions;
  14839. },
  14840. set: function (collisionEnabled) {
  14841. this._checkCollisions = collisionEnabled;
  14842. if (this.getScene().workerCollisions) {
  14843. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14844. }
  14845. },
  14846. enumerable: true,
  14847. configurable: true
  14848. });
  14849. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14850. var globalPosition = this.getAbsolutePosition();
  14851. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14852. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14853. if (!this._collider) {
  14854. this._collider = new BABYLON.Collider();
  14855. }
  14856. this._collider.radius = this.ellipsoid;
  14857. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14858. return this;
  14859. };
  14860. // Submeshes octree
  14861. /**
  14862. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14863. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14864. * Returns an Octree of submeshes.
  14865. */
  14866. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14867. if (maxCapacity === void 0) { maxCapacity = 64; }
  14868. if (maxDepth === void 0) { maxDepth = 2; }
  14869. if (!this._submeshesOctree) {
  14870. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14871. }
  14872. this.computeWorldMatrix(true);
  14873. var boundingInfo = this.getBoundingInfo();
  14874. // Update octree
  14875. if (boundingInfo) {
  14876. var bbox = boundingInfo.boundingBox;
  14877. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14878. }
  14879. return this._submeshesOctree;
  14880. };
  14881. // Collisions
  14882. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14883. this._generatePointsArray();
  14884. if (!this._positions) {
  14885. return this;
  14886. }
  14887. // Transformation
  14888. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14889. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14890. subMesh._lastColliderWorldVertices = [];
  14891. subMesh._trianglePlanes = [];
  14892. var start = subMesh.verticesStart;
  14893. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14894. for (var i = start; i < end; i++) {
  14895. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14896. }
  14897. }
  14898. // Collide
  14899. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14900. if (collider.collisionFound) {
  14901. collider.collidedMesh = this;
  14902. }
  14903. return this;
  14904. };
  14905. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14906. var subMeshes;
  14907. var len;
  14908. // Octrees
  14909. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14910. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14911. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14912. len = intersections.length;
  14913. subMeshes = intersections.data;
  14914. }
  14915. else {
  14916. subMeshes = this.subMeshes;
  14917. len = subMeshes.length;
  14918. }
  14919. for (var index = 0; index < len; index++) {
  14920. var subMesh = subMeshes[index];
  14921. // Bounding test
  14922. if (len > 1 && !subMesh._checkCollision(collider))
  14923. continue;
  14924. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14925. }
  14926. return this;
  14927. };
  14928. AbstractMesh.prototype._checkCollision = function (collider) {
  14929. // Bounding box test
  14930. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14931. return this;
  14932. // Transformation matrix
  14933. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14934. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14935. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14936. return this;
  14937. };
  14938. // Picking
  14939. AbstractMesh.prototype._generatePointsArray = function () {
  14940. return false;
  14941. };
  14942. /**
  14943. * Checks if the passed Ray intersects with the mesh.
  14944. * Returns an object PickingInfo.
  14945. */
  14946. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14947. var pickingInfo = new BABYLON.PickingInfo();
  14948. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14949. return pickingInfo;
  14950. }
  14951. if (!this._generatePointsArray()) {
  14952. return pickingInfo;
  14953. }
  14954. var intersectInfo = null;
  14955. // Octrees
  14956. var subMeshes;
  14957. var len;
  14958. if (this._submeshesOctree && this.useOctreeForPicking) {
  14959. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14960. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14961. len = intersections.length;
  14962. subMeshes = intersections.data;
  14963. }
  14964. else {
  14965. subMeshes = this.subMeshes;
  14966. len = subMeshes.length;
  14967. }
  14968. for (var index = 0; index < len; index++) {
  14969. var subMesh = subMeshes[index];
  14970. // Bounding test
  14971. if (len > 1 && !subMesh.canIntersects(ray))
  14972. continue;
  14973. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  14974. if (currentIntersectInfo) {
  14975. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14976. intersectInfo = currentIntersectInfo;
  14977. intersectInfo.subMeshId = index;
  14978. if (fastCheck) {
  14979. break;
  14980. }
  14981. }
  14982. }
  14983. }
  14984. if (intersectInfo) {
  14985. // Get picked point
  14986. var world = this.getWorldMatrix();
  14987. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14988. var direction = ray.direction.clone();
  14989. direction = direction.scale(intersectInfo.distance);
  14990. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14991. var pickedPoint = worldOrigin.add(worldDirection);
  14992. // Return result
  14993. pickingInfo.hit = true;
  14994. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14995. pickingInfo.pickedPoint = pickedPoint;
  14996. pickingInfo.pickedMesh = this;
  14997. pickingInfo.bu = intersectInfo.bu || 0;
  14998. pickingInfo.bv = intersectInfo.bv || 0;
  14999. pickingInfo.faceId = intersectInfo.faceId;
  15000. pickingInfo.subMeshId = intersectInfo.subMeshId;
  15001. return pickingInfo;
  15002. }
  15003. return pickingInfo;
  15004. };
  15005. /**
  15006. * Clones the mesh, used by the class Mesh.
  15007. * Just returns `null` for an AbstractMesh.
  15008. */
  15009. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15010. return null;
  15011. };
  15012. /**
  15013. * Disposes all the mesh submeshes.
  15014. * Returns the AbstractMesh.
  15015. */
  15016. AbstractMesh.prototype.releaseSubMeshes = function () {
  15017. if (this.subMeshes) {
  15018. while (this.subMeshes.length) {
  15019. this.subMeshes[0].dispose();
  15020. }
  15021. }
  15022. else {
  15023. this.subMeshes = new Array();
  15024. }
  15025. return this;
  15026. };
  15027. /**
  15028. * Disposes the AbstractMesh.
  15029. * Some internal references are kept for further use.
  15030. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15031. * Returns nothing.
  15032. */
  15033. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15034. var _this = this;
  15035. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15036. var index;
  15037. // Action manager
  15038. if (this.actionManager) {
  15039. this.actionManager.dispose();
  15040. this.actionManager = null;
  15041. }
  15042. // Skeleton
  15043. this.skeleton = null;
  15044. // Animations
  15045. this.getScene().stopAnimation(this);
  15046. // Physics
  15047. if (this.physicsImpostor) {
  15048. this.physicsImpostor.dispose();
  15049. }
  15050. // Intersections in progress
  15051. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  15052. var other = this._intersectionsInProgress[index];
  15053. var pos = other._intersectionsInProgress.indexOf(this);
  15054. other._intersectionsInProgress.splice(pos, 1);
  15055. }
  15056. this._intersectionsInProgress = [];
  15057. // Lights
  15058. var lights = this.getScene().lights;
  15059. lights.forEach(function (light) {
  15060. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  15061. if (meshIndex !== -1) {
  15062. light.includedOnlyMeshes.splice(meshIndex, 1);
  15063. }
  15064. meshIndex = light.excludedMeshes.indexOf(_this);
  15065. if (meshIndex !== -1) {
  15066. light.excludedMeshes.splice(meshIndex, 1);
  15067. }
  15068. // Shadow generators
  15069. var generator = light.getShadowGenerator();
  15070. if (generator) {
  15071. var shadowMap = generator.getShadowMap();
  15072. if (shadowMap && shadowMap.renderList) {
  15073. meshIndex = shadowMap.renderList.indexOf(_this);
  15074. if (meshIndex !== -1) {
  15075. shadowMap.renderList.splice(meshIndex, 1);
  15076. }
  15077. }
  15078. }
  15079. });
  15080. // Edges
  15081. if (this._edgesRenderer) {
  15082. this._edgesRenderer.dispose();
  15083. this._edgesRenderer = null;
  15084. }
  15085. // SubMeshes
  15086. if (this.getClassName() !== "InstancedMesh") {
  15087. this.releaseSubMeshes();
  15088. }
  15089. // Octree
  15090. var sceneOctree = this.getScene().selectionOctree;
  15091. if (sceneOctree) {
  15092. var index = sceneOctree.dynamicContent.indexOf(this);
  15093. if (index !== -1) {
  15094. sceneOctree.dynamicContent.splice(index, 1);
  15095. }
  15096. }
  15097. // Query
  15098. var engine = this.getScene().getEngine();
  15099. if (this._occlusionQuery) {
  15100. this._isOcclusionQueryInProgress = false;
  15101. engine.deleteQuery(this._occlusionQuery);
  15102. this._occlusionQuery = null;
  15103. }
  15104. // Engine
  15105. engine.wipeCaches();
  15106. // Remove from scene
  15107. this.getScene().removeMesh(this);
  15108. this._cache = null;
  15109. if (disposeMaterialAndTextures) {
  15110. if (this.material) {
  15111. this.material.dispose(false, true);
  15112. }
  15113. }
  15114. if (!doNotRecurse) {
  15115. // Particles
  15116. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  15117. if (this.getScene().particleSystems[index].emitter === this) {
  15118. this.getScene().particleSystems[index].dispose();
  15119. index--;
  15120. }
  15121. }
  15122. // Children
  15123. var objects = this.getDescendants(true);
  15124. for (index = 0; index < objects.length; index++) {
  15125. objects[index].dispose();
  15126. }
  15127. }
  15128. else {
  15129. var childMeshes = this.getChildMeshes(true);
  15130. for (index = 0; index < childMeshes.length; index++) {
  15131. var child = childMeshes[index];
  15132. child.parent = null;
  15133. child.computeWorldMatrix(true);
  15134. }
  15135. }
  15136. // facet data
  15137. if (this._facetDataEnabled) {
  15138. this.disableFacetData();
  15139. }
  15140. this.onAfterWorldMatrixUpdateObservable.clear();
  15141. this.onCollideObservable.clear();
  15142. this.onCollisionPositionChangeObservable.clear();
  15143. this._isDisposed = true;
  15144. _super.prototype.dispose.call(this);
  15145. };
  15146. /**
  15147. * Adds the passed mesh as a child to the current mesh.
  15148. * Returns the AbstractMesh.
  15149. */
  15150. AbstractMesh.prototype.addChild = function (mesh) {
  15151. mesh.setParent(this);
  15152. return this;
  15153. };
  15154. /**
  15155. * Removes the passed mesh from the current mesh children list.
  15156. * Returns the AbstractMesh.
  15157. */
  15158. AbstractMesh.prototype.removeChild = function (mesh) {
  15159. mesh.setParent(null);
  15160. return this;
  15161. };
  15162. // Facet data
  15163. /**
  15164. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  15165. * Returns the AbstractMesh.
  15166. */
  15167. AbstractMesh.prototype._initFacetData = function () {
  15168. if (!this._facetNormals) {
  15169. this._facetNormals = new Array();
  15170. }
  15171. if (!this._facetPositions) {
  15172. this._facetPositions = new Array();
  15173. }
  15174. if (!this._facetPartitioning) {
  15175. this._facetPartitioning = new Array();
  15176. }
  15177. this._facetNb = (this.getIndices().length / 3) | 0;
  15178. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  15179. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  15180. for (var f = 0; f < this._facetNb; f++) {
  15181. this._facetNormals[f] = BABYLON.Vector3.Zero();
  15182. this._facetPositions[f] = BABYLON.Vector3.Zero();
  15183. }
  15184. this._facetDataEnabled = true;
  15185. return this;
  15186. };
  15187. /**
  15188. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  15189. * This method can be called within the render loop.
  15190. * 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.
  15191. * Returns the AbstractMesh.
  15192. */
  15193. AbstractMesh.prototype.updateFacetData = function () {
  15194. if (!this._facetDataEnabled) {
  15195. this._initFacetData();
  15196. }
  15197. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15198. var indices = this.getIndices();
  15199. var indicesForComputeNormals = indices;
  15200. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15201. var bInfo = this.getBoundingInfo();
  15202. if (!bInfo) {
  15203. return this;
  15204. }
  15205. if (this._facetDepthSort && !this._originalIndices) {
  15206. // init arrays, matrix and sort function on first call
  15207. this._originalIndices = new Uint32Array(indices);
  15208. this._facetDepthSortFunction = function (f1, f2) {
  15209. return (f2.sqDistance - f1.sqDistance);
  15210. };
  15211. if (!this._facetDepthSortFrom) {
  15212. var camera = this.getScene().activeCamera;
  15213. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  15214. }
  15215. this._depthSortedFacets = [];
  15216. for (var f = 0; f < this._facetNb; f++) {
  15217. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  15218. this._depthSortedFacets.push(depthSortedFacet);
  15219. }
  15220. this._invertedMatrix = BABYLON.Matrix.Identity();
  15221. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  15222. }
  15223. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  15224. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  15225. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  15226. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  15227. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  15228. this._subDiv.max = this._partitioningSubdivisions;
  15229. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  15230. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  15231. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  15232. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  15233. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  15234. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  15235. // set the parameters for ComputeNormals()
  15236. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  15237. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  15238. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  15239. this._facetParameters.bInfo = bInfo;
  15240. this._facetParameters.bbSize = this._bbSize;
  15241. this._facetParameters.subDiv = this._subDiv;
  15242. this._facetParameters.ratio = this.partitioningBBoxRatio;
  15243. this._facetParameters.depthSort = this._facetDepthSort;
  15244. if (this._facetDepthSort) {
  15245. this.computeWorldMatrix(true);
  15246. this._worldMatrix.invertToRef(this._invertedMatrix);
  15247. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  15248. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  15249. indicesForComputeNormals = this._originalIndices;
  15250. }
  15251. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  15252. BABYLON.VertexData.ComputeNormals(positions, indicesForComputeNormals, normals, this._facetParameters);
  15253. if (this._facetDepthSort) {
  15254. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  15255. for (var sorted = 0; sorted < this._facetNb; sorted++) {
  15256. var sind = this._depthSortedFacets[sorted].ind;
  15257. indices[sorted * 3] = this._originalIndices[sind];
  15258. indices[sorted * 3 + 1] = this._originalIndices[sind + 1];
  15259. indices[sorted * 3 + 2] = this._originalIndices[sind + 2];
  15260. }
  15261. this.updateIndices(indices);
  15262. }
  15263. return this;
  15264. };
  15265. /**
  15266. * Returns the facetLocalNormals array.
  15267. * The normals are expressed in the mesh local space.
  15268. */
  15269. AbstractMesh.prototype.getFacetLocalNormals = function () {
  15270. if (!this._facetNormals) {
  15271. this.updateFacetData();
  15272. }
  15273. return this._facetNormals;
  15274. };
  15275. /**
  15276. * Returns the facetLocalPositions array.
  15277. * The facet positions are expressed in the mesh local space.
  15278. */
  15279. AbstractMesh.prototype.getFacetLocalPositions = function () {
  15280. if (!this._facetPositions) {
  15281. this.updateFacetData();
  15282. }
  15283. return this._facetPositions;
  15284. };
  15285. /**
  15286. * Returns the facetLocalPartioning array.
  15287. */
  15288. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  15289. if (!this._facetPartitioning) {
  15290. this.updateFacetData();
  15291. }
  15292. return this._facetPartitioning;
  15293. };
  15294. /**
  15295. * Returns the i-th facet position in the world system.
  15296. * This method allocates a new Vector3 per call.
  15297. */
  15298. AbstractMesh.prototype.getFacetPosition = function (i) {
  15299. var pos = BABYLON.Vector3.Zero();
  15300. this.getFacetPositionToRef(i, pos);
  15301. return pos;
  15302. };
  15303. /**
  15304. * Sets the reference Vector3 with the i-th facet position in the world system.
  15305. * Returns the AbstractMesh.
  15306. */
  15307. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  15308. var localPos = (this.getFacetLocalPositions())[i];
  15309. var world = this.getWorldMatrix();
  15310. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  15311. return this;
  15312. };
  15313. /**
  15314. * Returns the i-th facet normal in the world system.
  15315. * This method allocates a new Vector3 per call.
  15316. */
  15317. AbstractMesh.prototype.getFacetNormal = function (i) {
  15318. var norm = BABYLON.Vector3.Zero();
  15319. this.getFacetNormalToRef(i, norm);
  15320. return norm;
  15321. };
  15322. /**
  15323. * Sets the reference Vector3 with the i-th facet normal in the world system.
  15324. * Returns the AbstractMesh.
  15325. */
  15326. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  15327. var localNorm = (this.getFacetLocalNormals())[i];
  15328. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  15329. return this;
  15330. };
  15331. /**
  15332. * 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).
  15333. */
  15334. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  15335. var bInfo = this.getBoundingInfo();
  15336. if (!bInfo) {
  15337. return null;
  15338. }
  15339. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  15340. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  15341. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  15342. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  15343. return null;
  15344. }
  15345. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  15346. };
  15347. /**
  15348. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  15349. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  15350. * 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.
  15351. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15352. * 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.
  15353. */
  15354. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  15355. if (checkFace === void 0) { checkFace = false; }
  15356. if (facing === void 0) { facing = true; }
  15357. var world = this.getWorldMatrix();
  15358. var invMat = BABYLON.Tmp.Matrix[5];
  15359. world.invertToRef(invMat);
  15360. var invVect = BABYLON.Tmp.Vector3[8];
  15361. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  15362. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  15363. if (projected) {
  15364. // tranform the local computed projected vector to world coordinates
  15365. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15366. }
  15367. return closest;
  15368. };
  15369. /**
  15370. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15371. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15372. * 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.
  15373. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15374. * 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.
  15375. */
  15376. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15377. if (checkFace === void 0) { checkFace = false; }
  15378. if (facing === void 0) { facing = true; }
  15379. var closest = null;
  15380. var tmpx = 0.0;
  15381. var tmpy = 0.0;
  15382. var tmpz = 0.0;
  15383. var d = 0.0; // tmp dot facet normal * facet position
  15384. var t0 = 0.0;
  15385. var projx = 0.0;
  15386. var projy = 0.0;
  15387. var projz = 0.0;
  15388. // Get all the facets in the same partitioning block than (x, y, z)
  15389. var facetPositions = this.getFacetLocalPositions();
  15390. var facetNormals = this.getFacetLocalNormals();
  15391. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15392. if (!facetsInBlock) {
  15393. return null;
  15394. }
  15395. // Get the closest facet to (x, y, z)
  15396. var shortest = Number.MAX_VALUE; // init distance vars
  15397. var tmpDistance = shortest;
  15398. var fib; // current facet in the block
  15399. var norm; // current facet normal
  15400. var p0; // current facet barycenter position
  15401. // loop on all the facets in the current partitioning block
  15402. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15403. fib = facetsInBlock[idx];
  15404. norm = facetNormals[fib];
  15405. p0 = facetPositions[fib];
  15406. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15407. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15408. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15409. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15410. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15411. projx = x + norm.x * t0;
  15412. projy = y + norm.y * t0;
  15413. projz = z + norm.z * t0;
  15414. tmpx = projx - x;
  15415. tmpy = projy - y;
  15416. tmpz = projz - z;
  15417. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15418. if (tmpDistance < shortest) {
  15419. shortest = tmpDistance;
  15420. closest = fib;
  15421. if (projected) {
  15422. projected.x = projx;
  15423. projected.y = projy;
  15424. projected.z = projz;
  15425. }
  15426. }
  15427. }
  15428. }
  15429. return closest;
  15430. };
  15431. /**
  15432. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15433. */
  15434. AbstractMesh.prototype.getFacetDataParameters = function () {
  15435. return this._facetParameters;
  15436. };
  15437. /**
  15438. * Disables the feature FacetData and frees the related memory.
  15439. * Returns the AbstractMesh.
  15440. */
  15441. AbstractMesh.prototype.disableFacetData = function () {
  15442. if (this._facetDataEnabled) {
  15443. this._facetDataEnabled = false;
  15444. this._facetPositions = new Array();
  15445. this._facetNormals = new Array();
  15446. this._facetPartitioning = new Array();
  15447. this._facetParameters = null;
  15448. this._originalIndices = new Uint32Array(0);
  15449. }
  15450. return this;
  15451. };
  15452. /**
  15453. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  15454. * Returns the mesh.
  15455. */
  15456. AbstractMesh.prototype.updateIndices = function (indices) {
  15457. return this;
  15458. };
  15459. /**
  15460. * Creates new normals data for the mesh.
  15461. * @param updatable.
  15462. */
  15463. AbstractMesh.prototype.createNormals = function (updatable) {
  15464. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15465. var indices = this.getIndices();
  15466. var normals;
  15467. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15468. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15469. }
  15470. else {
  15471. normals = [];
  15472. }
  15473. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15474. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15475. };
  15476. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15477. var engine = this.getEngine();
  15478. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15479. this._isOccluded = false;
  15480. return;
  15481. }
  15482. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15483. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15484. if (isOcclusionQueryAvailable) {
  15485. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15486. this._isOcclusionQueryInProgress = false;
  15487. this._occlusionInternalRetryCounter = 0;
  15488. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15489. }
  15490. else {
  15491. this._occlusionInternalRetryCounter++;
  15492. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15493. this._isOcclusionQueryInProgress = false;
  15494. this._occlusionInternalRetryCounter = 0;
  15495. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15496. // if strict continue the last state of the object.
  15497. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15498. }
  15499. else {
  15500. return;
  15501. }
  15502. }
  15503. }
  15504. var scene = this.getScene();
  15505. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15506. if (!this._occlusionQuery) {
  15507. this._occlusionQuery = engine.createQuery();
  15508. }
  15509. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15510. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15511. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15512. this._isOcclusionQueryInProgress = true;
  15513. };
  15514. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15515. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15516. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15517. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15518. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15519. return AbstractMesh;
  15520. }(BABYLON.TransformNode));
  15521. BABYLON.AbstractMesh = AbstractMesh;
  15522. })(BABYLON || (BABYLON = {}));
  15523. //# sourceMappingURL=babylon.abstractMesh.js.map
  15524. var BABYLON;
  15525. (function (BABYLON) {
  15526. var Light = /** @class */ (function (_super) {
  15527. __extends(Light, _super);
  15528. /**
  15529. * Creates a Light object in the scene.
  15530. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15531. */
  15532. function Light(name, scene) {
  15533. var _this = _super.call(this, name, scene) || this;
  15534. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15535. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15536. _this.intensity = 1.0;
  15537. _this.range = Number.MAX_VALUE;
  15538. /**
  15539. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15540. * of light.
  15541. */
  15542. _this._photometricScale = 1.0;
  15543. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15544. _this._radius = 0.00001;
  15545. _this.renderPriority = 0;
  15546. /**
  15547. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15548. * the current shadow generator.
  15549. */
  15550. _this.shadowEnabled = true;
  15551. _this._excludeWithLayerMask = 0;
  15552. _this._includeOnlyWithLayerMask = 0;
  15553. _this._lightmapMode = 0;
  15554. _this._excludedMeshesIds = new Array();
  15555. _this._includedOnlyMeshesIds = new Array();
  15556. _this.getScene().addLight(_this);
  15557. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15558. _this._buildUniformLayout();
  15559. _this.includedOnlyMeshes = new Array();
  15560. _this.excludedMeshes = new Array();
  15561. _this._resyncMeshes();
  15562. return _this;
  15563. }
  15564. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15565. /**
  15566. * If every light affecting the material is in this lightmapMode,
  15567. * material.lightmapTexture adds or multiplies
  15568. * (depends on material.useLightmapAsShadowmap)
  15569. * after every other light calculations.
  15570. */
  15571. get: function () {
  15572. return Light._LIGHTMAP_DEFAULT;
  15573. },
  15574. enumerable: true,
  15575. configurable: true
  15576. });
  15577. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15578. /**
  15579. * material.lightmapTexture as only diffuse lighting from this light
  15580. * adds pnly specular lighting from this light
  15581. * adds dynamic shadows
  15582. */
  15583. get: function () {
  15584. return Light._LIGHTMAP_SPECULAR;
  15585. },
  15586. enumerable: true,
  15587. configurable: true
  15588. });
  15589. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15590. /**
  15591. * material.lightmapTexture as only lighting
  15592. * no light calculation from this light
  15593. * only adds dynamic shadows from this light
  15594. */
  15595. get: function () {
  15596. return Light._LIGHTMAP_SHADOWSONLY;
  15597. },
  15598. enumerable: true,
  15599. configurable: true
  15600. });
  15601. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15602. /**
  15603. * Each light type uses the default quantity according to its type:
  15604. * point/spot lights use luminous intensity
  15605. * directional lights use illuminance
  15606. */
  15607. get: function () {
  15608. return Light._INTENSITYMODE_AUTOMATIC;
  15609. },
  15610. enumerable: true,
  15611. configurable: true
  15612. });
  15613. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15614. /**
  15615. * lumen (lm)
  15616. */
  15617. get: function () {
  15618. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15619. },
  15620. enumerable: true,
  15621. configurable: true
  15622. });
  15623. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15624. /**
  15625. * candela (lm/sr)
  15626. */
  15627. get: function () {
  15628. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15629. },
  15630. enumerable: true,
  15631. configurable: true
  15632. });
  15633. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15634. /**
  15635. * lux (lm/m^2)
  15636. */
  15637. get: function () {
  15638. return Light._INTENSITYMODE_ILLUMINANCE;
  15639. },
  15640. enumerable: true,
  15641. configurable: true
  15642. });
  15643. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15644. /**
  15645. * nit (cd/m^2)
  15646. */
  15647. get: function () {
  15648. return Light._INTENSITYMODE_LUMINANCE;
  15649. },
  15650. enumerable: true,
  15651. configurable: true
  15652. });
  15653. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15654. /**
  15655. * Light type const id of the point light.
  15656. */
  15657. get: function () {
  15658. return Light._LIGHTTYPEID_POINTLIGHT;
  15659. },
  15660. enumerable: true,
  15661. configurable: true
  15662. });
  15663. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15664. /**
  15665. * Light type const id of the directional light.
  15666. */
  15667. get: function () {
  15668. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15669. },
  15670. enumerable: true,
  15671. configurable: true
  15672. });
  15673. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15674. /**
  15675. * Light type const id of the spot light.
  15676. */
  15677. get: function () {
  15678. return Light._LIGHTTYPEID_SPOTLIGHT;
  15679. },
  15680. enumerable: true,
  15681. configurable: true
  15682. });
  15683. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15684. /**
  15685. * Light type const id of the hemispheric light.
  15686. */
  15687. get: function () {
  15688. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15689. },
  15690. enumerable: true,
  15691. configurable: true
  15692. });
  15693. Object.defineProperty(Light.prototype, "intensityMode", {
  15694. /**
  15695. * Gets the photometric scale used to interpret the intensity.
  15696. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15697. */
  15698. get: function () {
  15699. return this._intensityMode;
  15700. },
  15701. /**
  15702. * Sets the photometric scale used to interpret the intensity.
  15703. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15704. */
  15705. set: function (value) {
  15706. this._intensityMode = value;
  15707. this._computePhotometricScale();
  15708. },
  15709. enumerable: true,
  15710. configurable: true
  15711. });
  15712. ;
  15713. ;
  15714. Object.defineProperty(Light.prototype, "radius", {
  15715. /**
  15716. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15717. */
  15718. get: function () {
  15719. return this._radius;
  15720. },
  15721. /**
  15722. * sets the light radius used by PBR Materials to simulate soft area lights.
  15723. */
  15724. set: function (value) {
  15725. this._radius = value;
  15726. this._computePhotometricScale();
  15727. },
  15728. enumerable: true,
  15729. configurable: true
  15730. });
  15731. ;
  15732. ;
  15733. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15734. get: function () {
  15735. return this._includedOnlyMeshes;
  15736. },
  15737. set: function (value) {
  15738. this._includedOnlyMeshes = value;
  15739. this._hookArrayForIncludedOnly(value);
  15740. },
  15741. enumerable: true,
  15742. configurable: true
  15743. });
  15744. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15745. get: function () {
  15746. return this._excludedMeshes;
  15747. },
  15748. set: function (value) {
  15749. this._excludedMeshes = value;
  15750. this._hookArrayForExcluded(value);
  15751. },
  15752. enumerable: true,
  15753. configurable: true
  15754. });
  15755. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15756. get: function () {
  15757. return this._excludeWithLayerMask;
  15758. },
  15759. set: function (value) {
  15760. this._excludeWithLayerMask = value;
  15761. this._resyncMeshes();
  15762. },
  15763. enumerable: true,
  15764. configurable: true
  15765. });
  15766. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15767. get: function () {
  15768. return this._includeOnlyWithLayerMask;
  15769. },
  15770. set: function (value) {
  15771. this._includeOnlyWithLayerMask = value;
  15772. this._resyncMeshes();
  15773. },
  15774. enumerable: true,
  15775. configurable: true
  15776. });
  15777. Object.defineProperty(Light.prototype, "lightmapMode", {
  15778. get: function () {
  15779. return this._lightmapMode;
  15780. },
  15781. set: function (value) {
  15782. if (this._lightmapMode === value) {
  15783. return;
  15784. }
  15785. this._lightmapMode = value;
  15786. this._markMeshesAsLightDirty();
  15787. },
  15788. enumerable: true,
  15789. configurable: true
  15790. });
  15791. Light.prototype._buildUniformLayout = function () {
  15792. // Overridden
  15793. };
  15794. /**
  15795. * Returns the string "Light".
  15796. */
  15797. Light.prototype.getClassName = function () {
  15798. return "Light";
  15799. };
  15800. /**
  15801. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15802. */
  15803. Light.prototype.toString = function (fullDetails) {
  15804. var ret = "Name: " + this.name;
  15805. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15806. if (this.animations) {
  15807. for (var i = 0; i < this.animations.length; i++) {
  15808. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15809. }
  15810. }
  15811. if (fullDetails) {
  15812. }
  15813. return ret;
  15814. };
  15815. /**
  15816. * Set the enabled state of this node.
  15817. * @param {boolean} value - the new enabled state
  15818. * @see isEnabled
  15819. */
  15820. Light.prototype.setEnabled = function (value) {
  15821. _super.prototype.setEnabled.call(this, value);
  15822. this._resyncMeshes();
  15823. };
  15824. /**
  15825. * Returns the Light associated shadow generator.
  15826. */
  15827. Light.prototype.getShadowGenerator = function () {
  15828. return this._shadowGenerator;
  15829. };
  15830. /**
  15831. * Returns a Vector3, the absolute light position in the World.
  15832. */
  15833. Light.prototype.getAbsolutePosition = function () {
  15834. return BABYLON.Vector3.Zero();
  15835. };
  15836. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15837. };
  15838. Light.prototype._getWorldMatrix = function () {
  15839. return BABYLON.Matrix.Identity();
  15840. };
  15841. /**
  15842. * Boolean : True if the light will affect the passed mesh.
  15843. */
  15844. Light.prototype.canAffectMesh = function (mesh) {
  15845. if (!mesh) {
  15846. return true;
  15847. }
  15848. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15849. return false;
  15850. }
  15851. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15852. return false;
  15853. }
  15854. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15855. return false;
  15856. }
  15857. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15858. return false;
  15859. }
  15860. return true;
  15861. };
  15862. /**
  15863. * Returns the light World matrix.
  15864. */
  15865. Light.prototype.getWorldMatrix = function () {
  15866. this._currentRenderId = this.getScene().getRenderId();
  15867. var worldMatrix = this._getWorldMatrix();
  15868. if (this.parent && this.parent.getWorldMatrix) {
  15869. if (!this._parentedWorldMatrix) {
  15870. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15871. }
  15872. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15873. this._markSyncedWithParent();
  15874. return this._parentedWorldMatrix;
  15875. }
  15876. return worldMatrix;
  15877. };
  15878. /**
  15879. * Sort function to order lights for rendering.
  15880. * @param a First Light object to compare to second.
  15881. * @param b Second Light object to compare first.
  15882. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15883. */
  15884. Light.compareLightsPriority = function (a, b) {
  15885. //shadow-casting lights have priority over non-shadow-casting lights
  15886. //the renderPrioirty is a secondary sort criterion
  15887. if (a.shadowEnabled !== b.shadowEnabled) {
  15888. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15889. }
  15890. return b.renderPriority - a.renderPriority;
  15891. };
  15892. /**
  15893. * Disposes the light.
  15894. */
  15895. Light.prototype.dispose = function () {
  15896. if (this._shadowGenerator) {
  15897. this._shadowGenerator.dispose();
  15898. this._shadowGenerator = null;
  15899. }
  15900. // Animations
  15901. this.getScene().stopAnimation(this);
  15902. // Remove from meshes
  15903. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15904. var mesh = _a[_i];
  15905. mesh._removeLightSource(this);
  15906. }
  15907. this._uniformBuffer.dispose();
  15908. // Remove from scene
  15909. this.getScene().removeLight(this);
  15910. _super.prototype.dispose.call(this);
  15911. };
  15912. /**
  15913. * Returns the light type ID (integer).
  15914. */
  15915. Light.prototype.getTypeID = function () {
  15916. return 0;
  15917. };
  15918. /**
  15919. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15920. */
  15921. Light.prototype.getScaledIntensity = function () {
  15922. return this._photometricScale * this.intensity;
  15923. };
  15924. /**
  15925. * Returns a new Light object, named "name", from the current one.
  15926. */
  15927. Light.prototype.clone = function (name) {
  15928. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15929. if (!constructor) {
  15930. return null;
  15931. }
  15932. return BABYLON.SerializationHelper.Clone(constructor, this);
  15933. };
  15934. /**
  15935. * Serializes the current light into a Serialization object.
  15936. * Returns the serialized object.
  15937. */
  15938. Light.prototype.serialize = function () {
  15939. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15940. // Type
  15941. serializationObject.type = this.getTypeID();
  15942. // Parent
  15943. if (this.parent) {
  15944. serializationObject.parentId = this.parent.id;
  15945. }
  15946. // Inclusion / exclusions
  15947. if (this.excludedMeshes.length > 0) {
  15948. serializationObject.excludedMeshesIds = [];
  15949. this.excludedMeshes.forEach(function (mesh) {
  15950. serializationObject.excludedMeshesIds.push(mesh.id);
  15951. });
  15952. }
  15953. if (this.includedOnlyMeshes.length > 0) {
  15954. serializationObject.includedOnlyMeshesIds = [];
  15955. this.includedOnlyMeshes.forEach(function (mesh) {
  15956. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15957. });
  15958. }
  15959. // Animations
  15960. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15961. serializationObject.ranges = this.serializeAnimationRanges();
  15962. return serializationObject;
  15963. };
  15964. /**
  15965. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15966. * This new light is named "name" and added to the passed scene.
  15967. */
  15968. Light.GetConstructorFromName = function (type, name, scene) {
  15969. switch (type) {
  15970. case 0:
  15971. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15972. case 1:
  15973. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15974. case 2:
  15975. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15976. case 3:
  15977. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15978. }
  15979. return null;
  15980. };
  15981. /**
  15982. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15983. */
  15984. Light.Parse = function (parsedLight, scene) {
  15985. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  15986. if (!constructor) {
  15987. return null;
  15988. }
  15989. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  15990. // Inclusion / exclusions
  15991. if (parsedLight.excludedMeshesIds) {
  15992. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15993. }
  15994. if (parsedLight.includedOnlyMeshesIds) {
  15995. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15996. }
  15997. // Parent
  15998. if (parsedLight.parentId) {
  15999. light._waitingParentId = parsedLight.parentId;
  16000. }
  16001. // Animations
  16002. if (parsedLight.animations) {
  16003. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16004. var parsedAnimation = parsedLight.animations[animationIndex];
  16005. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16006. }
  16007. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  16008. }
  16009. if (parsedLight.autoAnimate) {
  16010. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  16011. }
  16012. return light;
  16013. };
  16014. Light.prototype._hookArrayForExcluded = function (array) {
  16015. var _this = this;
  16016. var oldPush = array.push;
  16017. array.push = function () {
  16018. var items = [];
  16019. for (var _i = 0; _i < arguments.length; _i++) {
  16020. items[_i] = arguments[_i];
  16021. }
  16022. var result = oldPush.apply(array, items);
  16023. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  16024. var item = items_1[_a];
  16025. item._resyncLighSource(_this);
  16026. }
  16027. return result;
  16028. };
  16029. var oldSplice = array.splice;
  16030. array.splice = function (index, deleteCount) {
  16031. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16032. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  16033. var item = deleted_1[_i];
  16034. item._resyncLighSource(_this);
  16035. }
  16036. return deleted;
  16037. };
  16038. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  16039. var item = array_1[_i];
  16040. item._resyncLighSource(this);
  16041. }
  16042. };
  16043. Light.prototype._hookArrayForIncludedOnly = function (array) {
  16044. var _this = this;
  16045. var oldPush = array.push;
  16046. array.push = function () {
  16047. var items = [];
  16048. for (var _i = 0; _i < arguments.length; _i++) {
  16049. items[_i] = arguments[_i];
  16050. }
  16051. var result = oldPush.apply(array, items);
  16052. _this._resyncMeshes();
  16053. return result;
  16054. };
  16055. var oldSplice = array.splice;
  16056. array.splice = function (index, deleteCount) {
  16057. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16058. _this._resyncMeshes();
  16059. return deleted;
  16060. };
  16061. this._resyncMeshes();
  16062. };
  16063. Light.prototype._resyncMeshes = function () {
  16064. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16065. var mesh = _a[_i];
  16066. mesh._resyncLighSource(this);
  16067. }
  16068. };
  16069. Light.prototype._markMeshesAsLightDirty = function () {
  16070. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16071. var mesh = _a[_i];
  16072. if (mesh._lightSources.indexOf(this) !== -1) {
  16073. mesh._markSubMeshesAsLightDirty();
  16074. }
  16075. }
  16076. };
  16077. /**
  16078. * Recomputes the cached photometric scale if needed.
  16079. */
  16080. Light.prototype._computePhotometricScale = function () {
  16081. this._photometricScale = this._getPhotometricScale();
  16082. this.getScene().resetCachedMaterial();
  16083. };
  16084. /**
  16085. * Returns the Photometric Scale according to the light type and intensity mode.
  16086. */
  16087. Light.prototype._getPhotometricScale = function () {
  16088. var photometricScale = 0.0;
  16089. var lightTypeID = this.getTypeID();
  16090. //get photometric mode
  16091. var photometricMode = this.intensityMode;
  16092. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  16093. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  16094. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  16095. }
  16096. else {
  16097. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  16098. }
  16099. }
  16100. //compute photometric scale
  16101. switch (lightTypeID) {
  16102. case Light.LIGHTTYPEID_POINTLIGHT:
  16103. case Light.LIGHTTYPEID_SPOTLIGHT:
  16104. switch (photometricMode) {
  16105. case Light.INTENSITYMODE_LUMINOUSPOWER:
  16106. photometricScale = 1.0 / (4.0 * Math.PI);
  16107. break;
  16108. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  16109. photometricScale = 1.0;
  16110. break;
  16111. case Light.INTENSITYMODE_LUMINANCE:
  16112. photometricScale = this.radius * this.radius;
  16113. break;
  16114. }
  16115. break;
  16116. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  16117. switch (photometricMode) {
  16118. case Light.INTENSITYMODE_ILLUMINANCE:
  16119. photometricScale = 1.0;
  16120. break;
  16121. case Light.INTENSITYMODE_LUMINANCE:
  16122. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  16123. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  16124. var apexAngleRadians = this.radius;
  16125. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  16126. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  16127. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  16128. photometricScale = solidAngle;
  16129. break;
  16130. }
  16131. break;
  16132. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  16133. // No fall off in hemisperic light.
  16134. photometricScale = 1.0;
  16135. break;
  16136. }
  16137. return photometricScale;
  16138. };
  16139. Light.prototype._reorderLightsInScene = function () {
  16140. var scene = this.getScene();
  16141. if (this._renderPriority != 0) {
  16142. scene.requireLightSorting = true;
  16143. }
  16144. this.getScene().sortLightsByPriority();
  16145. };
  16146. //lightmapMode Consts
  16147. Light._LIGHTMAP_DEFAULT = 0;
  16148. Light._LIGHTMAP_SPECULAR = 1;
  16149. Light._LIGHTMAP_SHADOWSONLY = 2;
  16150. // Intensity Mode Consts
  16151. Light._INTENSITYMODE_AUTOMATIC = 0;
  16152. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  16153. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  16154. Light._INTENSITYMODE_ILLUMINANCE = 3;
  16155. Light._INTENSITYMODE_LUMINANCE = 4;
  16156. // Light types ids const.
  16157. Light._LIGHTTYPEID_POINTLIGHT = 0;
  16158. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  16159. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  16160. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  16161. __decorate([
  16162. BABYLON.serializeAsColor3()
  16163. ], Light.prototype, "diffuse", void 0);
  16164. __decorate([
  16165. BABYLON.serializeAsColor3()
  16166. ], Light.prototype, "specular", void 0);
  16167. __decorate([
  16168. BABYLON.serialize()
  16169. ], Light.prototype, "intensity", void 0);
  16170. __decorate([
  16171. BABYLON.serialize()
  16172. ], Light.prototype, "range", void 0);
  16173. __decorate([
  16174. BABYLON.serialize()
  16175. ], Light.prototype, "intensityMode", null);
  16176. __decorate([
  16177. BABYLON.serialize()
  16178. ], Light.prototype, "radius", null);
  16179. __decorate([
  16180. BABYLON.serialize()
  16181. ], Light.prototype, "_renderPriority", void 0);
  16182. __decorate([
  16183. BABYLON.expandToProperty("_reorderLightsInScene")
  16184. ], Light.prototype, "renderPriority", void 0);
  16185. __decorate([
  16186. BABYLON.serialize()
  16187. ], Light.prototype, "shadowEnabled", void 0);
  16188. __decorate([
  16189. BABYLON.serialize("excludeWithLayerMask")
  16190. ], Light.prototype, "_excludeWithLayerMask", void 0);
  16191. __decorate([
  16192. BABYLON.serialize("includeOnlyWithLayerMask")
  16193. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  16194. __decorate([
  16195. BABYLON.serialize("lightmapMode")
  16196. ], Light.prototype, "_lightmapMode", void 0);
  16197. return Light;
  16198. }(BABYLON.Node));
  16199. BABYLON.Light = Light;
  16200. })(BABYLON || (BABYLON = {}));
  16201. //# sourceMappingURL=babylon.light.js.map
  16202. var BABYLON;
  16203. (function (BABYLON) {
  16204. var Camera = /** @class */ (function (_super) {
  16205. __extends(Camera, _super);
  16206. function Camera(name, position, scene) {
  16207. var _this = _super.call(this, name, scene) || this;
  16208. _this.upVector = BABYLON.Vector3.Up();
  16209. _this.orthoLeft = null;
  16210. _this.orthoRight = null;
  16211. _this.orthoBottom = null;
  16212. _this.orthoTop = null;
  16213. _this.fov = 0.8;
  16214. _this.minZ = 1;
  16215. _this.maxZ = 10000.0;
  16216. _this.inertia = 0.9;
  16217. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16218. _this.isIntermediate = false;
  16219. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16220. _this.layerMask = 0x0FFFFFFF;
  16221. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16222. // Camera rig members
  16223. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16224. _this._rigCameras = new Array();
  16225. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16226. _this._skipRendering = false;
  16227. _this.customRenderTargets = new Array();
  16228. // Observables
  16229. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  16230. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  16231. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  16232. _this.onRestoreStateObservable = new BABYLON.Observable();
  16233. // Cache
  16234. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16235. _this._projectionMatrix = new BABYLON.Matrix();
  16236. _this._doNotComputeProjectionMatrix = false;
  16237. _this._postProcesses = new Array();
  16238. _this._transformMatrix = BABYLON.Matrix.Zero();
  16239. _this._activeMeshes = new BABYLON.SmartArray(256);
  16240. _this._globalPosition = BABYLON.Vector3.Zero();
  16241. _this._refreshFrustumPlanes = true;
  16242. _this.getScene().addCamera(_this);
  16243. if (!_this.getScene().activeCamera) {
  16244. _this.getScene().activeCamera = _this;
  16245. }
  16246. _this.position = position;
  16247. return _this;
  16248. }
  16249. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16250. get: function () {
  16251. return Camera._PERSPECTIVE_CAMERA;
  16252. },
  16253. enumerable: true,
  16254. configurable: true
  16255. });
  16256. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16257. get: function () {
  16258. return Camera._ORTHOGRAPHIC_CAMERA;
  16259. },
  16260. enumerable: true,
  16261. configurable: true
  16262. });
  16263. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16264. get: function () {
  16265. return Camera._FOVMODE_VERTICAL_FIXED;
  16266. },
  16267. enumerable: true,
  16268. configurable: true
  16269. });
  16270. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16271. get: function () {
  16272. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16273. },
  16274. enumerable: true,
  16275. configurable: true
  16276. });
  16277. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16278. get: function () {
  16279. return Camera._RIG_MODE_NONE;
  16280. },
  16281. enumerable: true,
  16282. configurable: true
  16283. });
  16284. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16285. get: function () {
  16286. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16287. },
  16288. enumerable: true,
  16289. configurable: true
  16290. });
  16291. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16292. get: function () {
  16293. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16294. },
  16295. enumerable: true,
  16296. configurable: true
  16297. });
  16298. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16299. get: function () {
  16300. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16301. },
  16302. enumerable: true,
  16303. configurable: true
  16304. });
  16305. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16306. get: function () {
  16307. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16308. },
  16309. enumerable: true,
  16310. configurable: true
  16311. });
  16312. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16313. get: function () {
  16314. return Camera._RIG_MODE_VR;
  16315. },
  16316. enumerable: true,
  16317. configurable: true
  16318. });
  16319. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16320. get: function () {
  16321. return Camera._RIG_MODE_WEBVR;
  16322. },
  16323. enumerable: true,
  16324. configurable: true
  16325. });
  16326. /**
  16327. * Store current camera state (fov, position, etc..)
  16328. */
  16329. Camera.prototype.storeState = function () {
  16330. this._stateStored = true;
  16331. this._storedFov = this.fov;
  16332. return this;
  16333. };
  16334. /**
  16335. * Restores the camera state values if it has been stored. You must call storeState() first
  16336. */
  16337. Camera.prototype._restoreStateValues = function () {
  16338. if (!this._stateStored) {
  16339. return false;
  16340. }
  16341. this.fov = this._storedFov;
  16342. return true;
  16343. };
  16344. /**
  16345. * Restored camera state. You must call storeState() first
  16346. */
  16347. Camera.prototype.restoreState = function () {
  16348. if (this._restoreStateValues()) {
  16349. this.onRestoreStateObservable.notifyObservers(this);
  16350. return true;
  16351. }
  16352. return false;
  16353. };
  16354. Camera.prototype.getClassName = function () {
  16355. return "Camera";
  16356. };
  16357. /**
  16358. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16359. */
  16360. Camera.prototype.toString = function (fullDetails) {
  16361. var ret = "Name: " + this.name;
  16362. ret += ", type: " + this.getClassName();
  16363. if (this.animations) {
  16364. for (var i = 0; i < this.animations.length; i++) {
  16365. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16366. }
  16367. }
  16368. if (fullDetails) {
  16369. }
  16370. return ret;
  16371. };
  16372. Object.defineProperty(Camera.prototype, "globalPosition", {
  16373. get: function () {
  16374. return this._globalPosition;
  16375. },
  16376. enumerable: true,
  16377. configurable: true
  16378. });
  16379. Camera.prototype.getActiveMeshes = function () {
  16380. return this._activeMeshes;
  16381. };
  16382. Camera.prototype.isActiveMesh = function (mesh) {
  16383. return (this._activeMeshes.indexOf(mesh) !== -1);
  16384. };
  16385. //Cache
  16386. Camera.prototype._initCache = function () {
  16387. _super.prototype._initCache.call(this);
  16388. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16389. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16390. this._cache.mode = undefined;
  16391. this._cache.minZ = undefined;
  16392. this._cache.maxZ = undefined;
  16393. this._cache.fov = undefined;
  16394. this._cache.fovMode = undefined;
  16395. this._cache.aspectRatio = undefined;
  16396. this._cache.orthoLeft = undefined;
  16397. this._cache.orthoRight = undefined;
  16398. this._cache.orthoBottom = undefined;
  16399. this._cache.orthoTop = undefined;
  16400. this._cache.renderWidth = undefined;
  16401. this._cache.renderHeight = undefined;
  16402. };
  16403. Camera.prototype._updateCache = function (ignoreParentClass) {
  16404. if (!ignoreParentClass) {
  16405. _super.prototype._updateCache.call(this);
  16406. }
  16407. this._cache.position.copyFrom(this.position);
  16408. this._cache.upVector.copyFrom(this.upVector);
  16409. };
  16410. // Synchronized
  16411. Camera.prototype._isSynchronized = function () {
  16412. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16413. };
  16414. Camera.prototype._isSynchronizedViewMatrix = function () {
  16415. if (!_super.prototype._isSynchronized.call(this))
  16416. return false;
  16417. return this._cache.position.equals(this.position)
  16418. && this._cache.upVector.equals(this.upVector)
  16419. && this.isSynchronizedWithParent();
  16420. };
  16421. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16422. var check = this._cache.mode === this.mode
  16423. && this._cache.minZ === this.minZ
  16424. && this._cache.maxZ === this.maxZ;
  16425. if (!check) {
  16426. return false;
  16427. }
  16428. var engine = this.getEngine();
  16429. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16430. check = this._cache.fov === this.fov
  16431. && this._cache.fovMode === this.fovMode
  16432. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16433. }
  16434. else {
  16435. check = this._cache.orthoLeft === this.orthoLeft
  16436. && this._cache.orthoRight === this.orthoRight
  16437. && this._cache.orthoBottom === this.orthoBottom
  16438. && this._cache.orthoTop === this.orthoTop
  16439. && this._cache.renderWidth === engine.getRenderWidth()
  16440. && this._cache.renderHeight === engine.getRenderHeight();
  16441. }
  16442. return check;
  16443. };
  16444. // Controls
  16445. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16446. };
  16447. Camera.prototype.detachControl = function (element) {
  16448. };
  16449. Camera.prototype.update = function () {
  16450. this._checkInputs();
  16451. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16452. this._updateRigCameras();
  16453. }
  16454. };
  16455. Camera.prototype._checkInputs = function () {
  16456. this.onAfterCheckInputsObservable.notifyObservers(this);
  16457. };
  16458. Object.defineProperty(Camera.prototype, "rigCameras", {
  16459. get: function () {
  16460. return this._rigCameras;
  16461. },
  16462. enumerable: true,
  16463. configurable: true
  16464. });
  16465. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16466. get: function () {
  16467. return this._rigPostProcess;
  16468. },
  16469. enumerable: true,
  16470. configurable: true
  16471. });
  16472. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16473. // invalidate framebuffer
  16474. if (this._postProcesses.length > 0) {
  16475. this._postProcesses[0].markTextureDirty();
  16476. }
  16477. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16478. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16479. var cam = this._rigCameras[i];
  16480. var rigPostProcess = cam._rigPostProcess;
  16481. // for VR rig, there does not have to be a post process
  16482. if (rigPostProcess) {
  16483. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16484. if (isPass) {
  16485. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16486. cam.isIntermediate = this._postProcesses.length === 0;
  16487. }
  16488. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16489. rigPostProcess.markTextureDirty();
  16490. }
  16491. else {
  16492. cam._postProcesses = this._postProcesses.slice(0);
  16493. }
  16494. }
  16495. };
  16496. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16497. if (insertAt === void 0) { insertAt = null; }
  16498. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16499. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16500. return 0;
  16501. }
  16502. if (insertAt == null || insertAt < 0) {
  16503. this._postProcesses.push(postProcess);
  16504. }
  16505. else {
  16506. this._postProcesses.splice(insertAt, 0, postProcess);
  16507. }
  16508. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16509. return this._postProcesses.indexOf(postProcess);
  16510. };
  16511. Camera.prototype.detachPostProcess = function (postProcess) {
  16512. var idx = this._postProcesses.indexOf(postProcess);
  16513. if (idx !== -1) {
  16514. this._postProcesses.splice(idx, 1);
  16515. }
  16516. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16517. };
  16518. Camera.prototype.getWorldMatrix = function () {
  16519. if (!this._worldMatrix) {
  16520. this._worldMatrix = BABYLON.Matrix.Identity();
  16521. }
  16522. var viewMatrix = this.getViewMatrix();
  16523. viewMatrix.invertToRef(this._worldMatrix);
  16524. return this._worldMatrix;
  16525. };
  16526. Camera.prototype._getViewMatrix = function () {
  16527. return BABYLON.Matrix.Identity();
  16528. };
  16529. Camera.prototype.getViewMatrix = function (force) {
  16530. if (!force && this._isSynchronizedViewMatrix()) {
  16531. return this._computedViewMatrix;
  16532. }
  16533. this.updateCache();
  16534. this._computedViewMatrix = this._getViewMatrix();
  16535. this._currentRenderId = this.getScene().getRenderId();
  16536. this._refreshFrustumPlanes = true;
  16537. if (!this.parent || !this.parent.getWorldMatrix) {
  16538. this._globalPosition.copyFrom(this.position);
  16539. }
  16540. else {
  16541. if (!this._worldMatrix) {
  16542. this._worldMatrix = BABYLON.Matrix.Identity();
  16543. }
  16544. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16545. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16546. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16547. this._computedViewMatrix.invert();
  16548. this._markSyncedWithParent();
  16549. }
  16550. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16551. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16552. }
  16553. this.onViewMatrixChangedObservable.notifyObservers(this);
  16554. return this._computedViewMatrix;
  16555. };
  16556. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16557. this._doNotComputeProjectionMatrix = true;
  16558. if (projection !== undefined) {
  16559. this._projectionMatrix = projection;
  16560. }
  16561. };
  16562. ;
  16563. Camera.prototype.unfreezeProjectionMatrix = function () {
  16564. this._doNotComputeProjectionMatrix = false;
  16565. };
  16566. ;
  16567. Camera.prototype.getProjectionMatrix = function (force) {
  16568. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16569. return this._projectionMatrix;
  16570. }
  16571. // Cache
  16572. this._cache.mode = this.mode;
  16573. this._cache.minZ = this.minZ;
  16574. this._cache.maxZ = this.maxZ;
  16575. // Matrix
  16576. this._refreshFrustumPlanes = true;
  16577. var engine = this.getEngine();
  16578. var scene = this.getScene();
  16579. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16580. this._cache.fov = this.fov;
  16581. this._cache.fovMode = this.fovMode;
  16582. this._cache.aspectRatio = engine.getAspectRatio(this);
  16583. if (this.minZ <= 0) {
  16584. this.minZ = 0.1;
  16585. }
  16586. if (scene.useRightHandedSystem) {
  16587. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16588. }
  16589. else {
  16590. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16591. }
  16592. }
  16593. else {
  16594. var halfWidth = engine.getRenderWidth() / 2.0;
  16595. var halfHeight = engine.getRenderHeight() / 2.0;
  16596. if (scene.useRightHandedSystem) {
  16597. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16598. }
  16599. else {
  16600. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16601. }
  16602. this._cache.orthoLeft = this.orthoLeft;
  16603. this._cache.orthoRight = this.orthoRight;
  16604. this._cache.orthoBottom = this.orthoBottom;
  16605. this._cache.orthoTop = this.orthoTop;
  16606. this._cache.renderWidth = engine.getRenderWidth();
  16607. this._cache.renderHeight = engine.getRenderHeight();
  16608. }
  16609. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16610. return this._projectionMatrix;
  16611. };
  16612. Camera.prototype.getTranformationMatrix = function () {
  16613. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16614. return this._transformMatrix;
  16615. };
  16616. Camera.prototype.updateFrustumPlanes = function () {
  16617. if (!this._refreshFrustumPlanes) {
  16618. return;
  16619. }
  16620. this.getTranformationMatrix();
  16621. if (!this._frustumPlanes) {
  16622. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16623. }
  16624. else {
  16625. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16626. }
  16627. this._refreshFrustumPlanes = false;
  16628. };
  16629. Camera.prototype.isInFrustum = function (target) {
  16630. this.updateFrustumPlanes();
  16631. return target.isInFrustum(this._frustumPlanes);
  16632. };
  16633. Camera.prototype.isCompletelyInFrustum = function (target) {
  16634. this.updateFrustumPlanes();
  16635. return target.isCompletelyInFrustum(this._frustumPlanes);
  16636. };
  16637. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16638. if (length === void 0) { length = 100; }
  16639. if (!transform) {
  16640. transform = this.getWorldMatrix();
  16641. }
  16642. if (!origin) {
  16643. origin = this.position;
  16644. }
  16645. var forward = new BABYLON.Vector3(0, 0, 1);
  16646. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16647. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16648. return new BABYLON.Ray(origin, direction, length);
  16649. };
  16650. Camera.prototype.dispose = function () {
  16651. // Observables
  16652. this.onViewMatrixChangedObservable.clear();
  16653. this.onProjectionMatrixChangedObservable.clear();
  16654. this.onAfterCheckInputsObservable.clear();
  16655. this.onRestoreStateObservable.clear();
  16656. // Inputs
  16657. if (this.inputs) {
  16658. this.inputs.clear();
  16659. }
  16660. // Animations
  16661. this.getScene().stopAnimation(this);
  16662. // Remove from scene
  16663. this.getScene().removeCamera(this);
  16664. while (this._rigCameras.length > 0) {
  16665. var camera = this._rigCameras.pop();
  16666. if (camera) {
  16667. camera.dispose();
  16668. }
  16669. }
  16670. // Postprocesses
  16671. if (this._rigPostProcess) {
  16672. this._rigPostProcess.dispose(this);
  16673. this._rigPostProcess = null;
  16674. this._postProcesses = [];
  16675. }
  16676. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16677. this._rigPostProcess = null;
  16678. this._postProcesses = [];
  16679. }
  16680. else {
  16681. var i = this._postProcesses.length;
  16682. while (--i >= 0) {
  16683. this._postProcesses[i].dispose(this);
  16684. }
  16685. }
  16686. // Render targets
  16687. var i = this.customRenderTargets.length;
  16688. while (--i >= 0) {
  16689. this.customRenderTargets[i].dispose();
  16690. }
  16691. this.customRenderTargets = [];
  16692. // Active Meshes
  16693. this._activeMeshes.dispose();
  16694. _super.prototype.dispose.call(this);
  16695. };
  16696. Object.defineProperty(Camera.prototype, "leftCamera", {
  16697. // ---- Camera rigs section ----
  16698. get: function () {
  16699. if (this._rigCameras.length < 1) {
  16700. return null;
  16701. }
  16702. return this._rigCameras[0];
  16703. },
  16704. enumerable: true,
  16705. configurable: true
  16706. });
  16707. Object.defineProperty(Camera.prototype, "rightCamera", {
  16708. get: function () {
  16709. if (this._rigCameras.length < 2) {
  16710. return null;
  16711. }
  16712. return this._rigCameras[1];
  16713. },
  16714. enumerable: true,
  16715. configurable: true
  16716. });
  16717. Camera.prototype.getLeftTarget = function () {
  16718. if (this._rigCameras.length < 1) {
  16719. return null;
  16720. }
  16721. return this._rigCameras[0].getTarget();
  16722. };
  16723. Camera.prototype.getRightTarget = function () {
  16724. if (this._rigCameras.length < 2) {
  16725. return null;
  16726. }
  16727. return this._rigCameras[1].getTarget();
  16728. };
  16729. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16730. if (this.cameraRigMode === mode) {
  16731. return;
  16732. }
  16733. while (this._rigCameras.length > 0) {
  16734. var camera = this._rigCameras.pop();
  16735. if (camera) {
  16736. camera.dispose();
  16737. }
  16738. }
  16739. this.cameraRigMode = mode;
  16740. this._cameraRigParams = {};
  16741. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16742. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16743. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16744. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16745. // create the rig cameras, unless none
  16746. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16747. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16748. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16749. if (leftCamera && rightCamera) {
  16750. this._rigCameras.push(leftCamera);
  16751. this._rigCameras.push(rightCamera);
  16752. }
  16753. }
  16754. switch (this.cameraRigMode) {
  16755. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16756. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16757. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16758. break;
  16759. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16760. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16761. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16762. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16763. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16764. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16765. break;
  16766. case Camera.RIG_MODE_VR:
  16767. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16768. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16769. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16770. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16771. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16772. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16773. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16774. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16775. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16776. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16777. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16778. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16779. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16780. if (metrics.compensateDistortion) {
  16781. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16782. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16783. }
  16784. break;
  16785. case Camera.RIG_MODE_WEBVR:
  16786. if (rigParams.vrDisplay) {
  16787. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16788. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16789. //Left eye
  16790. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16791. this._rigCameras[0].setCameraRigParameter("left", true);
  16792. //leaving this for future reference
  16793. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16794. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16795. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16796. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16797. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16798. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16799. this._rigCameras[0].parent = this;
  16800. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16801. //Right eye
  16802. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16803. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16804. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16805. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16806. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16807. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16808. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16809. this._rigCameras[1].parent = this;
  16810. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16811. if (Camera.UseAlternateWebVRRendering) {
  16812. this._rigCameras[1]._skipRendering = true;
  16813. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16814. }
  16815. }
  16816. break;
  16817. }
  16818. this._cascadePostProcessesToRigCams();
  16819. this.update();
  16820. };
  16821. Camera.prototype._getVRProjectionMatrix = function () {
  16822. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16823. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16824. return this._projectionMatrix;
  16825. };
  16826. Camera.prototype._updateCameraRotationMatrix = function () {
  16827. //Here for WebVR
  16828. };
  16829. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16830. //Here for WebVR
  16831. };
  16832. /**
  16833. * This function MUST be overwritten by the different WebVR cameras available.
  16834. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16835. */
  16836. Camera.prototype._getWebVRProjectionMatrix = function () {
  16837. return BABYLON.Matrix.Identity();
  16838. };
  16839. /**
  16840. * This function MUST be overwritten by the different WebVR cameras available.
  16841. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16842. */
  16843. Camera.prototype._getWebVRViewMatrix = function () {
  16844. return BABYLON.Matrix.Identity();
  16845. };
  16846. Camera.prototype.setCameraRigParameter = function (name, value) {
  16847. if (!this._cameraRigParams) {
  16848. this._cameraRigParams = {};
  16849. }
  16850. this._cameraRigParams[name] = value;
  16851. //provisionnally:
  16852. if (name === "interaxialDistance") {
  16853. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16854. }
  16855. };
  16856. /**
  16857. * needs to be overridden by children so sub has required properties to be copied
  16858. */
  16859. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16860. return null;
  16861. };
  16862. /**
  16863. * May need to be overridden by children
  16864. */
  16865. Camera.prototype._updateRigCameras = function () {
  16866. for (var i = 0; i < this._rigCameras.length; i++) {
  16867. this._rigCameras[i].minZ = this.minZ;
  16868. this._rigCameras[i].maxZ = this.maxZ;
  16869. this._rigCameras[i].fov = this.fov;
  16870. }
  16871. // only update viewport when ANAGLYPH
  16872. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16873. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16874. }
  16875. };
  16876. Camera.prototype._setupInputs = function () {
  16877. };
  16878. Camera.prototype.serialize = function () {
  16879. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16880. // Type
  16881. serializationObject.type = this.getClassName();
  16882. // Parent
  16883. if (this.parent) {
  16884. serializationObject.parentId = this.parent.id;
  16885. }
  16886. if (this.inputs) {
  16887. this.inputs.serialize(serializationObject);
  16888. }
  16889. // Animations
  16890. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16891. serializationObject.ranges = this.serializeAnimationRanges();
  16892. return serializationObject;
  16893. };
  16894. Camera.prototype.clone = function (name) {
  16895. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16896. };
  16897. Camera.prototype.getDirection = function (localAxis) {
  16898. var result = BABYLON.Vector3.Zero();
  16899. this.getDirectionToRef(localAxis, result);
  16900. return result;
  16901. };
  16902. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16903. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16904. };
  16905. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16906. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16907. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16908. switch (type) {
  16909. case "ArcRotateCamera":
  16910. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16911. case "DeviceOrientationCamera":
  16912. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16913. case "FollowCamera":
  16914. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16915. case "ArcFollowCamera":
  16916. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16917. case "GamepadCamera":
  16918. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16919. case "TouchCamera":
  16920. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16921. case "VirtualJoysticksCamera":
  16922. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16923. case "WebVRFreeCamera":
  16924. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16925. case "WebVRGamepadCamera":
  16926. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16927. case "VRDeviceOrientationFreeCamera":
  16928. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16929. case "VRDeviceOrientationGamepadCamera":
  16930. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16931. case "AnaglyphArcRotateCamera":
  16932. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16933. case "AnaglyphFreeCamera":
  16934. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16935. case "AnaglyphGamepadCamera":
  16936. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16937. case "AnaglyphUniversalCamera":
  16938. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16939. case "StereoscopicArcRotateCamera":
  16940. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16941. case "StereoscopicFreeCamera":
  16942. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16943. case "StereoscopicGamepadCamera":
  16944. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16945. case "StereoscopicUniversalCamera":
  16946. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16947. case "FreeCamera":// Forcing Universal here
  16948. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16949. default:// Universal Camera is the default value
  16950. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16951. }
  16952. };
  16953. Camera.Parse = function (parsedCamera, scene) {
  16954. var type = parsedCamera.type;
  16955. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16956. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16957. // Parent
  16958. if (parsedCamera.parentId) {
  16959. camera._waitingParentId = parsedCamera.parentId;
  16960. }
  16961. //If camera has an input manager, let it parse inputs settings
  16962. if (camera.inputs) {
  16963. camera.inputs.parse(parsedCamera);
  16964. camera._setupInputs();
  16965. }
  16966. if (camera.setPosition) {
  16967. camera.position.copyFromFloats(0, 0, 0);
  16968. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16969. }
  16970. // Target
  16971. if (parsedCamera.target) {
  16972. if (camera.setTarget) {
  16973. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16974. }
  16975. }
  16976. // Apply 3d rig, when found
  16977. if (parsedCamera.cameraRigMode) {
  16978. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16979. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16980. }
  16981. // Animations
  16982. if (parsedCamera.animations) {
  16983. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16984. var parsedAnimation = parsedCamera.animations[animationIndex];
  16985. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16986. }
  16987. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16988. }
  16989. if (parsedCamera.autoAnimate) {
  16990. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16991. }
  16992. return camera;
  16993. };
  16994. // Statics
  16995. Camera._PERSPECTIVE_CAMERA = 0;
  16996. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16997. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16998. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16999. Camera._RIG_MODE_NONE = 0;
  17000. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  17001. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  17002. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  17003. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  17004. Camera._RIG_MODE_VR = 20;
  17005. Camera._RIG_MODE_WEBVR = 21;
  17006. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  17007. Camera.UseAlternateWebVRRendering = false;
  17008. __decorate([
  17009. BABYLON.serializeAsVector3()
  17010. ], Camera.prototype, "position", void 0);
  17011. __decorate([
  17012. BABYLON.serializeAsVector3()
  17013. ], Camera.prototype, "upVector", void 0);
  17014. __decorate([
  17015. BABYLON.serialize()
  17016. ], Camera.prototype, "orthoLeft", void 0);
  17017. __decorate([
  17018. BABYLON.serialize()
  17019. ], Camera.prototype, "orthoRight", void 0);
  17020. __decorate([
  17021. BABYLON.serialize()
  17022. ], Camera.prototype, "orthoBottom", void 0);
  17023. __decorate([
  17024. BABYLON.serialize()
  17025. ], Camera.prototype, "orthoTop", void 0);
  17026. __decorate([
  17027. BABYLON.serialize()
  17028. ], Camera.prototype, "fov", void 0);
  17029. __decorate([
  17030. BABYLON.serialize()
  17031. ], Camera.prototype, "minZ", void 0);
  17032. __decorate([
  17033. BABYLON.serialize()
  17034. ], Camera.prototype, "maxZ", void 0);
  17035. __decorate([
  17036. BABYLON.serialize()
  17037. ], Camera.prototype, "inertia", void 0);
  17038. __decorate([
  17039. BABYLON.serialize()
  17040. ], Camera.prototype, "mode", void 0);
  17041. __decorate([
  17042. BABYLON.serialize()
  17043. ], Camera.prototype, "layerMask", void 0);
  17044. __decorate([
  17045. BABYLON.serialize()
  17046. ], Camera.prototype, "fovMode", void 0);
  17047. __decorate([
  17048. BABYLON.serialize()
  17049. ], Camera.prototype, "cameraRigMode", void 0);
  17050. __decorate([
  17051. BABYLON.serialize()
  17052. ], Camera.prototype, "interaxialDistance", void 0);
  17053. __decorate([
  17054. BABYLON.serialize()
  17055. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  17056. return Camera;
  17057. }(BABYLON.Node));
  17058. BABYLON.Camera = Camera;
  17059. })(BABYLON || (BABYLON = {}));
  17060. //# sourceMappingURL=babylon.camera.js.map
  17061. var BABYLON;
  17062. (function (BABYLON) {
  17063. var RenderingManager = /** @class */ (function () {
  17064. function RenderingManager(scene) {
  17065. this._renderingGroups = new Array();
  17066. this._autoClearDepthStencil = {};
  17067. this._customOpaqueSortCompareFn = {};
  17068. this._customAlphaTestSortCompareFn = {};
  17069. this._customTransparentSortCompareFn = {};
  17070. this._renderinGroupInfo = null;
  17071. this._scene = scene;
  17072. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  17073. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  17074. }
  17075. }
  17076. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  17077. if (depth === void 0) { depth = true; }
  17078. if (stencil === void 0) { stencil = true; }
  17079. if (this._depthStencilBufferAlreadyCleaned) {
  17080. return;
  17081. }
  17082. this._scene.getEngine().clear(null, false, depth, stencil);
  17083. this._depthStencilBufferAlreadyCleaned = true;
  17084. };
  17085. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  17086. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  17087. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  17088. var info = null;
  17089. if (observable) {
  17090. if (!this._renderinGroupInfo) {
  17091. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  17092. }
  17093. info = this._renderinGroupInfo;
  17094. info.scene = this._scene;
  17095. info.camera = this._scene.activeCamera;
  17096. }
  17097. // Dispatch sprites
  17098. if (renderSprites) {
  17099. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  17100. var manager = this._scene.spriteManagers[index];
  17101. this.dispatchSprites(manager);
  17102. }
  17103. }
  17104. // Render
  17105. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17106. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  17107. var renderingGroup = this._renderingGroups[index];
  17108. if (!renderingGroup && !observable)
  17109. continue;
  17110. this._currentIndex = index;
  17111. var renderingGroupMask = 0;
  17112. // Fire PRECLEAR stage
  17113. if (observable && info) {
  17114. renderingGroupMask = Math.pow(2, index);
  17115. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  17116. info.renderingGroupId = index;
  17117. observable.notifyObservers(info, renderingGroupMask);
  17118. }
  17119. // Clear depth/stencil if needed
  17120. if (RenderingManager.AUTOCLEAR) {
  17121. var autoClear = this._autoClearDepthStencil[index];
  17122. if (autoClear && autoClear.autoClear) {
  17123. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  17124. }
  17125. }
  17126. if (observable && info) {
  17127. // Fire PREOPAQUE stage
  17128. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  17129. observable.notifyObservers(info, renderingGroupMask);
  17130. // Fire PRETRANSPARENT stage
  17131. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  17132. observable.notifyObservers(info, renderingGroupMask);
  17133. }
  17134. if (renderingGroup)
  17135. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  17136. // Fire POSTTRANSPARENT stage
  17137. if (observable && info) {
  17138. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  17139. observable.notifyObservers(info, renderingGroupMask);
  17140. }
  17141. }
  17142. };
  17143. RenderingManager.prototype.reset = function () {
  17144. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17145. var renderingGroup = this._renderingGroups[index];
  17146. if (renderingGroup) {
  17147. renderingGroup.prepare();
  17148. }
  17149. }
  17150. };
  17151. RenderingManager.prototype.dispose = function () {
  17152. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17153. var renderingGroup = this._renderingGroups[index];
  17154. if (renderingGroup) {
  17155. renderingGroup.dispose();
  17156. }
  17157. }
  17158. this._renderingGroups.length = 0;
  17159. };
  17160. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  17161. if (!this._renderingGroups[renderingGroupId]) {
  17162. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  17163. }
  17164. };
  17165. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  17166. var renderingGroupId = spriteManager.renderingGroupId || 0;
  17167. this._prepareRenderingGroup(renderingGroupId);
  17168. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  17169. };
  17170. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  17171. var renderingGroupId = particleSystem.renderingGroupId || 0;
  17172. this._prepareRenderingGroup(renderingGroupId);
  17173. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  17174. };
  17175. RenderingManager.prototype.dispatch = function (subMesh) {
  17176. var mesh = subMesh.getMesh();
  17177. var renderingGroupId = mesh.renderingGroupId || 0;
  17178. this._prepareRenderingGroup(renderingGroupId);
  17179. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  17180. };
  17181. /**
  17182. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17183. * This allowed control for front to back rendering or reversly depending of the special needs.
  17184. *
  17185. * @param renderingGroupId The rendering group id corresponding to its index
  17186. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17187. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17188. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17189. */
  17190. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17191. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17192. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17193. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17194. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  17195. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  17196. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  17197. if (this._renderingGroups[renderingGroupId]) {
  17198. var group = this._renderingGroups[renderingGroupId];
  17199. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  17200. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  17201. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  17202. }
  17203. };
  17204. /**
  17205. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17206. *
  17207. * @param renderingGroupId The rendering group id corresponding to its index
  17208. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17209. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17210. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17211. */
  17212. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17213. if (depth === void 0) { depth = true; }
  17214. if (stencil === void 0) { stencil = true; }
  17215. this._autoClearDepthStencil[renderingGroupId] = {
  17216. autoClear: autoClearDepthStencil,
  17217. depth: depth,
  17218. stencil: stencil
  17219. };
  17220. };
  17221. /**
  17222. * The max id used for rendering groups (not included)
  17223. */
  17224. RenderingManager.MAX_RENDERINGGROUPS = 4;
  17225. /**
  17226. * The min id used for rendering groups (included)
  17227. */
  17228. RenderingManager.MIN_RENDERINGGROUPS = 0;
  17229. /**
  17230. * Used to globally prevent autoclearing scenes.
  17231. */
  17232. RenderingManager.AUTOCLEAR = true;
  17233. return RenderingManager;
  17234. }());
  17235. BABYLON.RenderingManager = RenderingManager;
  17236. })(BABYLON || (BABYLON = {}));
  17237. //# sourceMappingURL=babylon.renderingManager.js.map
  17238. var BABYLON;
  17239. (function (BABYLON) {
  17240. var RenderingGroup = /** @class */ (function () {
  17241. /**
  17242. * Creates a new rendering group.
  17243. * @param index The rendering group index
  17244. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  17245. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  17246. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  17247. */
  17248. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17249. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17250. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17251. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17252. this.index = index;
  17253. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  17254. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  17255. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  17256. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  17257. this._particleSystems = new BABYLON.SmartArray(256);
  17258. this._spriteManagers = new BABYLON.SmartArray(256);
  17259. this._edgesRenderers = new BABYLON.SmartArray(16);
  17260. this._scene = scene;
  17261. this.opaqueSortCompareFn = opaqueSortCompareFn;
  17262. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  17263. this.transparentSortCompareFn = transparentSortCompareFn;
  17264. }
  17265. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  17266. /**
  17267. * Set the opaque sort comparison function.
  17268. * If null the sub meshes will be render in the order they were created
  17269. */
  17270. set: function (value) {
  17271. this._opaqueSortCompareFn = value;
  17272. if (value) {
  17273. this._renderOpaque = this.renderOpaqueSorted;
  17274. }
  17275. else {
  17276. this._renderOpaque = RenderingGroup.renderUnsorted;
  17277. }
  17278. },
  17279. enumerable: true,
  17280. configurable: true
  17281. });
  17282. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  17283. /**
  17284. * Set the alpha test sort comparison function.
  17285. * If null the sub meshes will be render in the order they were created
  17286. */
  17287. set: function (value) {
  17288. this._alphaTestSortCompareFn = value;
  17289. if (value) {
  17290. this._renderAlphaTest = this.renderAlphaTestSorted;
  17291. }
  17292. else {
  17293. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  17294. }
  17295. },
  17296. enumerable: true,
  17297. configurable: true
  17298. });
  17299. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  17300. /**
  17301. * Set the transparent sort comparison function.
  17302. * If null the sub meshes will be render in the order they were created
  17303. */
  17304. set: function (value) {
  17305. if (value) {
  17306. this._transparentSortCompareFn = value;
  17307. }
  17308. else {
  17309. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17310. }
  17311. this._renderTransparent = this.renderTransparentSorted;
  17312. },
  17313. enumerable: true,
  17314. configurable: true
  17315. });
  17316. /**
  17317. * Render all the sub meshes contained in the group.
  17318. * @param customRenderFunction Used to override the default render behaviour of the group.
  17319. * @returns true if rendered some submeshes.
  17320. */
  17321. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17322. if (customRenderFunction) {
  17323. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  17324. return;
  17325. }
  17326. var engine = this._scene.getEngine();
  17327. // Depth only
  17328. if (this._depthOnlySubMeshes.length !== 0) {
  17329. engine.setAlphaTesting(true);
  17330. engine.setColorWrite(false);
  17331. this._renderAlphaTest(this._depthOnlySubMeshes);
  17332. engine.setAlphaTesting(false);
  17333. engine.setColorWrite(true);
  17334. }
  17335. // Opaque
  17336. if (this._opaqueSubMeshes.length !== 0) {
  17337. this._renderOpaque(this._opaqueSubMeshes);
  17338. }
  17339. // Alpha test
  17340. if (this._alphaTestSubMeshes.length !== 0) {
  17341. engine.setAlphaTesting(true);
  17342. this._renderAlphaTest(this._alphaTestSubMeshes);
  17343. engine.setAlphaTesting(false);
  17344. }
  17345. var stencilState = engine.getStencilBuffer();
  17346. engine.setStencilBuffer(false);
  17347. // Sprites
  17348. if (renderSprites) {
  17349. this._renderSprites();
  17350. }
  17351. // Particles
  17352. if (renderParticles) {
  17353. this._renderParticles(activeMeshes);
  17354. }
  17355. if (this.onBeforeTransparentRendering) {
  17356. this.onBeforeTransparentRendering();
  17357. }
  17358. // Transparent
  17359. if (this._transparentSubMeshes.length !== 0) {
  17360. this._renderTransparent(this._transparentSubMeshes);
  17361. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17362. }
  17363. // Set back stencil to false in case it changes before the edge renderer.
  17364. engine.setStencilBuffer(false);
  17365. // Edges
  17366. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17367. this._edgesRenderers.data[edgesRendererIndex].render();
  17368. }
  17369. // Restore Stencil state.
  17370. engine.setStencilBuffer(stencilState);
  17371. };
  17372. /**
  17373. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17374. * @param subMeshes The submeshes to render
  17375. */
  17376. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17377. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17378. };
  17379. /**
  17380. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17381. * @param subMeshes The submeshes to render
  17382. */
  17383. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17384. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17385. };
  17386. /**
  17387. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17388. * @param subMeshes The submeshes to render
  17389. */
  17390. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17391. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17392. };
  17393. /**
  17394. * Renders the submeshes in a specified order.
  17395. * @param subMeshes The submeshes to sort before render
  17396. * @param sortCompareFn The comparison function use to sort
  17397. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17398. * @param transparent Specifies to activate blending if true
  17399. */
  17400. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17401. var subIndex = 0;
  17402. var subMesh;
  17403. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17404. for (; subIndex < subMeshes.length; subIndex++) {
  17405. subMesh = subMeshes.data[subIndex];
  17406. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17407. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17408. }
  17409. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17410. if (sortCompareFn) {
  17411. sortedArray.sort(sortCompareFn);
  17412. }
  17413. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17414. subMesh = sortedArray[subIndex];
  17415. if (transparent) {
  17416. var material = subMesh.getMaterial();
  17417. if (material && material.needDepthPrePass) {
  17418. var engine = material.getScene().getEngine();
  17419. engine.setColorWrite(false);
  17420. engine.setAlphaTesting(true);
  17421. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17422. subMesh.render(false);
  17423. engine.setAlphaTesting(false);
  17424. engine.setColorWrite(true);
  17425. }
  17426. }
  17427. subMesh.render(transparent);
  17428. }
  17429. };
  17430. /**
  17431. * Renders the submeshes in the order they were dispatched (no sort applied).
  17432. * @param subMeshes The submeshes to render
  17433. */
  17434. RenderingGroup.renderUnsorted = function (subMeshes) {
  17435. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17436. var submesh = subMeshes.data[subIndex];
  17437. submesh.render(false);
  17438. }
  17439. };
  17440. /**
  17441. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17442. * are rendered back to front if in the same alpha index.
  17443. *
  17444. * @param a The first submesh
  17445. * @param b The second submesh
  17446. * @returns The result of the comparison
  17447. */
  17448. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17449. // Alpha index first
  17450. if (a._alphaIndex > b._alphaIndex) {
  17451. return 1;
  17452. }
  17453. if (a._alphaIndex < b._alphaIndex) {
  17454. return -1;
  17455. }
  17456. // Then distance to camera
  17457. return RenderingGroup.backToFrontSortCompare(a, b);
  17458. };
  17459. /**
  17460. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17461. * are rendered back to front.
  17462. *
  17463. * @param a The first submesh
  17464. * @param b The second submesh
  17465. * @returns The result of the comparison
  17466. */
  17467. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17468. // Then distance to camera
  17469. if (a._distanceToCamera < b._distanceToCamera) {
  17470. return 1;
  17471. }
  17472. if (a._distanceToCamera > b._distanceToCamera) {
  17473. return -1;
  17474. }
  17475. return 0;
  17476. };
  17477. /**
  17478. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17479. * are rendered front to back (prevent overdraw).
  17480. *
  17481. * @param a The first submesh
  17482. * @param b The second submesh
  17483. * @returns The result of the comparison
  17484. */
  17485. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17486. // Then distance to camera
  17487. if (a._distanceToCamera < b._distanceToCamera) {
  17488. return -1;
  17489. }
  17490. if (a._distanceToCamera > b._distanceToCamera) {
  17491. return 1;
  17492. }
  17493. return 0;
  17494. };
  17495. /**
  17496. * Resets the different lists of submeshes to prepare a new frame.
  17497. */
  17498. RenderingGroup.prototype.prepare = function () {
  17499. this._opaqueSubMeshes.reset();
  17500. this._transparentSubMeshes.reset();
  17501. this._alphaTestSubMeshes.reset();
  17502. this._depthOnlySubMeshes.reset();
  17503. this._particleSystems.reset();
  17504. this._spriteManagers.reset();
  17505. this._edgesRenderers.reset();
  17506. };
  17507. RenderingGroup.prototype.dispose = function () {
  17508. this._opaqueSubMeshes.dispose();
  17509. this._transparentSubMeshes.dispose();
  17510. this._alphaTestSubMeshes.dispose();
  17511. this._depthOnlySubMeshes.dispose();
  17512. this._particleSystems.dispose();
  17513. this._spriteManagers.dispose();
  17514. this._edgesRenderers.dispose();
  17515. };
  17516. /**
  17517. * Inserts the submesh in its correct queue depending on its material.
  17518. * @param subMesh The submesh to dispatch
  17519. */
  17520. RenderingGroup.prototype.dispatch = function (subMesh) {
  17521. var material = subMesh.getMaterial();
  17522. var mesh = subMesh.getMesh();
  17523. if (!material) {
  17524. return;
  17525. }
  17526. if (material.needAlphaBlendingForMesh(mesh)) {
  17527. this._transparentSubMeshes.push(subMesh);
  17528. }
  17529. else if (material.needAlphaTesting()) {
  17530. if (material.needDepthPrePass) {
  17531. this._depthOnlySubMeshes.push(subMesh);
  17532. }
  17533. this._alphaTestSubMeshes.push(subMesh);
  17534. }
  17535. else {
  17536. if (material.needDepthPrePass) {
  17537. this._depthOnlySubMeshes.push(subMesh);
  17538. }
  17539. this._opaqueSubMeshes.push(subMesh); // Opaque
  17540. }
  17541. if (mesh._edgesRenderer) {
  17542. this._edgesRenderers.push(mesh._edgesRenderer);
  17543. }
  17544. };
  17545. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17546. this._spriteManagers.push(spriteManager);
  17547. };
  17548. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17549. this._particleSystems.push(particleSystem);
  17550. };
  17551. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17552. if (this._particleSystems.length === 0) {
  17553. return;
  17554. }
  17555. // Particles
  17556. var activeCamera = this._scene.activeCamera;
  17557. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17558. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17559. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17560. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17561. continue;
  17562. }
  17563. var emitter = particleSystem.emitter;
  17564. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17565. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17566. }
  17567. }
  17568. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17569. };
  17570. RenderingGroup.prototype._renderSprites = function () {
  17571. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17572. return;
  17573. }
  17574. // Sprites
  17575. var activeCamera = this._scene.activeCamera;
  17576. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17577. for (var id = 0; id < this._spriteManagers.length; id++) {
  17578. var spriteManager = this._spriteManagers.data[id];
  17579. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17580. spriteManager.render();
  17581. }
  17582. }
  17583. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17584. };
  17585. return RenderingGroup;
  17586. }());
  17587. BABYLON.RenderingGroup = RenderingGroup;
  17588. })(BABYLON || (BABYLON = {}));
  17589. //# sourceMappingURL=babylon.renderingGroup.js.map
  17590. var BABYLON;
  17591. (function (BABYLON) {
  17592. var ClickInfo = /** @class */ (function () {
  17593. function ClickInfo() {
  17594. this._singleClick = false;
  17595. this._doubleClick = false;
  17596. this._hasSwiped = false;
  17597. this._ignore = false;
  17598. }
  17599. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17600. get: function () {
  17601. return this._singleClick;
  17602. },
  17603. set: function (b) {
  17604. this._singleClick = b;
  17605. },
  17606. enumerable: true,
  17607. configurable: true
  17608. });
  17609. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17610. get: function () {
  17611. return this._doubleClick;
  17612. },
  17613. set: function (b) {
  17614. this._doubleClick = b;
  17615. },
  17616. enumerable: true,
  17617. configurable: true
  17618. });
  17619. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17620. get: function () {
  17621. return this._hasSwiped;
  17622. },
  17623. set: function (b) {
  17624. this._hasSwiped = b;
  17625. },
  17626. enumerable: true,
  17627. configurable: true
  17628. });
  17629. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17630. get: function () {
  17631. return this._ignore;
  17632. },
  17633. set: function (b) {
  17634. this._ignore = b;
  17635. },
  17636. enumerable: true,
  17637. configurable: true
  17638. });
  17639. return ClickInfo;
  17640. }());
  17641. /**
  17642. * This class is used by the onRenderingGroupObservable
  17643. */
  17644. var RenderingGroupInfo = /** @class */ (function () {
  17645. function RenderingGroupInfo() {
  17646. }
  17647. /**
  17648. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17649. * This stage will be fired no matter what
  17650. */
  17651. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17652. /**
  17653. * Called before opaque object are rendered.
  17654. * This stage will be fired only if there's 3D Opaque content to render
  17655. */
  17656. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17657. /**
  17658. * Called after the opaque objects are rendered and before the transparent ones
  17659. * This stage will be fired only if there's 3D transparent content to render
  17660. */
  17661. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17662. /**
  17663. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17664. * This stage will be fired no matter what
  17665. */
  17666. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17667. return RenderingGroupInfo;
  17668. }());
  17669. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17670. /**
  17671. * Represents a scene to be rendered by the engine.
  17672. * @see http://doc.babylonjs.com/page.php?p=21911
  17673. */
  17674. var Scene = /** @class */ (function () {
  17675. /**
  17676. * @constructor
  17677. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17678. */
  17679. function Scene(engine) {
  17680. // Members
  17681. this.autoClear = true;
  17682. this.autoClearDepthAndStencil = true;
  17683. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17684. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17685. this.forceWireframe = false;
  17686. this._forcePointsCloud = false;
  17687. this.forceShowBoundingBoxes = false;
  17688. this.animationsEnabled = true;
  17689. this.constantlyUpdateMeshUnderPointer = false;
  17690. this.hoverCursor = "pointer";
  17691. this.defaultCursor = "";
  17692. /**
  17693. * This is used to call preventDefault() on pointer down
  17694. * in order to block unwanted artifacts like system double clicks
  17695. */
  17696. this.preventDefaultOnPointerDown = true;
  17697. // Metadata
  17698. this.metadata = null;
  17699. /**
  17700. * An event triggered when the scene is disposed.
  17701. * @type {BABYLON.Observable}
  17702. */
  17703. this.onDisposeObservable = new BABYLON.Observable();
  17704. /**
  17705. * An event triggered before rendering the scene (right after animations and physics)
  17706. * @type {BABYLON.Observable}
  17707. */
  17708. this.onBeforeRenderObservable = new BABYLON.Observable();
  17709. /**
  17710. * An event triggered after rendering the scene
  17711. * @type {BABYLON.Observable}
  17712. */
  17713. this.onAfterRenderObservable = new BABYLON.Observable();
  17714. /**
  17715. * An event triggered before animating the scene
  17716. * @type {BABYLON.Observable}
  17717. */
  17718. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  17719. /**
  17720. * An event triggered after animations processing
  17721. * @type {BABYLON.Observable}
  17722. */
  17723. this.onAfterAnimationsObservable = new BABYLON.Observable();
  17724. /**
  17725. * An event triggered before draw calls are ready to be sent
  17726. * @type {BABYLON.Observable}
  17727. */
  17728. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  17729. /**
  17730. * An event triggered after draw calls have been sent
  17731. * @type {BABYLON.Observable}
  17732. */
  17733. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  17734. /**
  17735. * An event triggered when physic simulation is about to be run
  17736. * @type {BABYLON.Observable}
  17737. */
  17738. this.onBeforePhysicsObservable = new BABYLON.Observable();
  17739. /**
  17740. * An event triggered when physic simulation has been done
  17741. * @type {BABYLON.Observable}
  17742. */
  17743. this.onAfterPhysicsObservable = new BABYLON.Observable();
  17744. /**
  17745. * An event triggered when the scene is ready
  17746. * @type {BABYLON.Observable}
  17747. */
  17748. this.onReadyObservable = new BABYLON.Observable();
  17749. /**
  17750. * An event triggered before rendering a camera
  17751. * @type {BABYLON.Observable}
  17752. */
  17753. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17754. /**
  17755. * An event triggered after rendering a camera
  17756. * @type {BABYLON.Observable}
  17757. */
  17758. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17759. /**
  17760. * An event triggered when active meshes evaluation is about to start
  17761. * @type {BABYLON.Observable}
  17762. */
  17763. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17764. /**
  17765. * An event triggered when active meshes evaluation is done
  17766. * @type {BABYLON.Observable}
  17767. */
  17768. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17769. /**
  17770. * An event triggered when particles rendering is about to start
  17771. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17772. * @type {BABYLON.Observable}
  17773. */
  17774. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  17775. /**
  17776. * An event triggered when particles rendering is done
  17777. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17778. * @type {BABYLON.Observable}
  17779. */
  17780. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  17781. /**
  17782. * An event triggered when sprites rendering is about to start
  17783. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17784. * @type {BABYLON.Observable}
  17785. */
  17786. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  17787. /**
  17788. * An event triggered when sprites rendering is done
  17789. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17790. * @type {BABYLON.Observable}
  17791. */
  17792. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  17793. /**
  17794. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  17795. * @type {BABYLON.Observable}
  17796. */
  17797. this.onDataLoadedObservable = new BABYLON.Observable();
  17798. /**
  17799. * An event triggered when a camera is created
  17800. * @type {BABYLON.Observable}
  17801. */
  17802. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17803. /**
  17804. * An event triggered when a camera is removed
  17805. * @type {BABYLON.Observable}
  17806. */
  17807. this.onCameraRemovedObservable = new BABYLON.Observable();
  17808. /**
  17809. * An event triggered when a light is created
  17810. * @type {BABYLON.Observable}
  17811. */
  17812. this.onNewLightAddedObservable = new BABYLON.Observable();
  17813. /**
  17814. * An event triggered when a light is removed
  17815. * @type {BABYLON.Observable}
  17816. */
  17817. this.onLightRemovedObservable = new BABYLON.Observable();
  17818. /**
  17819. * An event triggered when a geometry is created
  17820. * @type {BABYLON.Observable}
  17821. */
  17822. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17823. /**
  17824. * An event triggered when a geometry is removed
  17825. * @type {BABYLON.Observable}
  17826. */
  17827. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17828. /**
  17829. * An event triggered when a transform node is created
  17830. * @type {BABYLON.Observable}
  17831. */
  17832. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  17833. /**
  17834. * An event triggered when a transform node is removed
  17835. * @type {BABYLON.Observable}
  17836. */
  17837. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  17838. /**
  17839. * An event triggered when a mesh is created
  17840. * @type {BABYLON.Observable}
  17841. */
  17842. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17843. /**
  17844. * An event triggered when a mesh is removed
  17845. * @type {BABYLON.Observable}
  17846. */
  17847. this.onMeshRemovedObservable = new BABYLON.Observable();
  17848. /**
  17849. * An event triggered when render targets are about to be rendered
  17850. * Can happen multiple times per frame.
  17851. * @type {BABYLON.Observable}
  17852. */
  17853. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17854. /**
  17855. * An event triggered when render targets were rendered.
  17856. * Can happen multiple times per frame.
  17857. * @type {BABYLON.Observable}
  17858. */
  17859. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17860. /**
  17861. * An event triggered before calculating deterministic simulation step
  17862. * @type {BABYLON.Observable}
  17863. */
  17864. this.onBeforeStepObservable = new BABYLON.Observable();
  17865. /**
  17866. * An event triggered after calculating deterministic simulation step
  17867. * @type {BABYLON.Observable}
  17868. */
  17869. this.onAfterStepObservable = new BABYLON.Observable();
  17870. /**
  17871. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17872. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17873. * 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)
  17874. */
  17875. this.onRenderingGroupObservable = new BABYLON.Observable();
  17876. // Animations
  17877. this.animations = [];
  17878. /**
  17879. * 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).
  17880. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17881. */
  17882. this.onPrePointerObservable = new BABYLON.Observable();
  17883. /**
  17884. * Observable event triggered each time an input event is received from the rendering canvas
  17885. */
  17886. this.onPointerObservable = new BABYLON.Observable();
  17887. this._meshPickProceed = false;
  17888. this._previousHasSwiped = false;
  17889. this._currentPickResult = null;
  17890. this._previousPickResult = null;
  17891. this._totalPointersPressed = 0;
  17892. this._doubleClickOccured = false;
  17893. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17894. this.cameraToUseForPointers = null;
  17895. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17896. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17897. this._startingPointerTime = 0;
  17898. this._previousStartingPointerTime = 0;
  17899. // Deterministic lockstep
  17900. this._timeAccumulator = 0;
  17901. this._currentStepId = 0;
  17902. this._currentInternalStep = 0;
  17903. // Keyboard
  17904. /**
  17905. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17906. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17907. */
  17908. this.onPreKeyboardObservable = new BABYLON.Observable();
  17909. /**
  17910. * Observable event triggered each time an keyboard event is received from the hosting window
  17911. */
  17912. this.onKeyboardObservable = new BABYLON.Observable();
  17913. // Coordinate system
  17914. /**
  17915. * use right-handed coordinate system on this scene.
  17916. * @type {boolean}
  17917. */
  17918. this._useRightHandedSystem = false;
  17919. // Fog
  17920. this._fogEnabled = true;
  17921. this._fogMode = Scene.FOGMODE_NONE;
  17922. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17923. this.fogDensity = 0.1;
  17924. this.fogStart = 0;
  17925. this.fogEnd = 1000.0;
  17926. // Lights
  17927. /**
  17928. * is shadow enabled on this scene.
  17929. * @type {boolean}
  17930. */
  17931. this._shadowsEnabled = true;
  17932. /**
  17933. * is light enabled on this scene.
  17934. * @type {boolean}
  17935. */
  17936. this._lightsEnabled = true;
  17937. /**
  17938. * All of the lights added to this scene.
  17939. * @see BABYLON.Light
  17940. * @type {BABYLON.Light[]}
  17941. */
  17942. this.lights = new Array();
  17943. // Cameras
  17944. /** All of the cameras added to this scene. */
  17945. this.cameras = new Array();
  17946. /** All of the active cameras added to this scene. */
  17947. this.activeCameras = new Array();
  17948. // Meshes
  17949. /**
  17950. * All of the tranform nodes added to this scene.
  17951. * @see BABYLON.TransformNode
  17952. * @type {BABYLON.TransformNode[]}
  17953. */
  17954. this.transformNodes = new Array();
  17955. /**
  17956. * All of the (abstract) meshes added to this scene.
  17957. * @see BABYLON.AbstractMesh
  17958. * @type {BABYLON.AbstractMesh[]}
  17959. */
  17960. this.meshes = new Array();
  17961. // Geometries
  17962. this._geometries = new Array();
  17963. this.materials = new Array();
  17964. this.multiMaterials = new Array();
  17965. // Textures
  17966. this._texturesEnabled = true;
  17967. this.textures = new Array();
  17968. // Particles
  17969. this.particlesEnabled = true;
  17970. this.particleSystems = new Array();
  17971. // Sprites
  17972. this.spritesEnabled = true;
  17973. this.spriteManagers = new Array();
  17974. // Layers
  17975. this.layers = new Array();
  17976. this.highlightLayers = new Array();
  17977. // Skeletons
  17978. this._skeletonsEnabled = true;
  17979. this.skeletons = new Array();
  17980. // Morph targets
  17981. this.morphTargetManagers = new Array();
  17982. // Lens flares
  17983. this.lensFlaresEnabled = true;
  17984. this.lensFlareSystems = new Array();
  17985. // Collisions
  17986. this.collisionsEnabled = true;
  17987. /** Defines the gravity applied to this scene */
  17988. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17989. // Postprocesses
  17990. this.postProcesses = new Array();
  17991. this.postProcessesEnabled = true;
  17992. // Customs render targets
  17993. this.renderTargetsEnabled = true;
  17994. this.dumpNextRenderTargets = false;
  17995. this.customRenderTargets = new Array();
  17996. // Imported meshes
  17997. this.importedMeshesFiles = new Array();
  17998. // Probes
  17999. this.probesEnabled = true;
  18000. this.reflectionProbes = new Array();
  18001. this._actionManagers = new Array();
  18002. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  18003. // Procedural textures
  18004. this.proceduralTexturesEnabled = true;
  18005. this._proceduralTextures = new Array();
  18006. this.soundTracks = new Array();
  18007. this._audioEnabled = true;
  18008. this._headphone = false;
  18009. // Performance counters
  18010. this._totalVertices = new BABYLON.PerfCounter();
  18011. this._activeIndices = new BABYLON.PerfCounter();
  18012. this._activeParticles = new BABYLON.PerfCounter();
  18013. this._activeBones = new BABYLON.PerfCounter();
  18014. this._animationTime = 0;
  18015. this.animationTimeScale = 1;
  18016. this._renderId = 0;
  18017. this._executeWhenReadyTimeoutId = -1;
  18018. this._intermediateRendering = false;
  18019. this._viewUpdateFlag = -1;
  18020. this._projectionUpdateFlag = -1;
  18021. this._alternateViewUpdateFlag = -1;
  18022. this._alternateProjectionUpdateFlag = -1;
  18023. this._toBeDisposed = new BABYLON.SmartArray(256);
  18024. this._pendingData = new Array();
  18025. this._isDisposed = false;
  18026. this._activeMeshes = new BABYLON.SmartArray(256);
  18027. this._processedMaterials = new BABYLON.SmartArray(256);
  18028. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  18029. this._activeParticleSystems = new BABYLON.SmartArray(256);
  18030. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  18031. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  18032. this._activeAnimatables = new Array();
  18033. this._transformMatrix = BABYLON.Matrix.Zero();
  18034. this._useAlternateCameraConfiguration = false;
  18035. this._alternateRendering = false;
  18036. this.requireLightSorting = false;
  18037. this._activeMeshesFrozen = false;
  18038. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  18039. this._engine.scenes.push(this);
  18040. this._uid = null;
  18041. this._renderingManager = new BABYLON.RenderingManager(this);
  18042. this.postProcessManager = new BABYLON.PostProcessManager(this);
  18043. if (BABYLON.OutlineRenderer) {
  18044. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  18045. }
  18046. if (BABYLON.Tools.IsWindowObjectExist()) {
  18047. this.attachControl();
  18048. }
  18049. //simplification queue
  18050. if (BABYLON.SimplificationQueue) {
  18051. this.simplificationQueue = new BABYLON.SimplificationQueue();
  18052. }
  18053. //collision coordinator initialization. For now legacy per default.
  18054. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  18055. // Uniform Buffer
  18056. this._createUbo();
  18057. // Default Image processing definition.
  18058. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  18059. }
  18060. Object.defineProperty(Scene, "FOGMODE_NONE", {
  18061. /** The fog is deactivated */
  18062. get: function () {
  18063. return Scene._FOGMODE_NONE;
  18064. },
  18065. enumerable: true,
  18066. configurable: true
  18067. });
  18068. Object.defineProperty(Scene, "FOGMODE_EXP", {
  18069. /** The fog density is following an exponential function */
  18070. get: function () {
  18071. return Scene._FOGMODE_EXP;
  18072. },
  18073. enumerable: true,
  18074. configurable: true
  18075. });
  18076. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  18077. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  18078. get: function () {
  18079. return Scene._FOGMODE_EXP2;
  18080. },
  18081. enumerable: true,
  18082. configurable: true
  18083. });
  18084. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  18085. /** The fog density is following a linear function. */
  18086. get: function () {
  18087. return Scene._FOGMODE_LINEAR;
  18088. },
  18089. enumerable: true,
  18090. configurable: true
  18091. });
  18092. Object.defineProperty(Scene.prototype, "environmentTexture", {
  18093. /**
  18094. * Texture used in all pbr material as the reflection texture.
  18095. * As in the majority of the scene they are the same (exception for multi room and so on),
  18096. * this is easier to reference from here than from all the materials.
  18097. */
  18098. get: function () {
  18099. return this._environmentTexture;
  18100. },
  18101. /**
  18102. * Texture used in all pbr material as the reflection texture.
  18103. * As in the majority of the scene they are the same (exception for multi room and so on),
  18104. * this is easier to set here than in all the materials.
  18105. */
  18106. set: function (value) {
  18107. if (this._environmentTexture === value) {
  18108. return;
  18109. }
  18110. this._environmentTexture = value;
  18111. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18112. },
  18113. enumerable: true,
  18114. configurable: true
  18115. });
  18116. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  18117. /**
  18118. * Default image processing configuration used either in the rendering
  18119. * Forward main pass or through the imageProcessingPostProcess if present.
  18120. * As in the majority of the scene they are the same (exception for multi camera),
  18121. * this is easier to reference from here than from all the materials and post process.
  18122. *
  18123. * No setter as we it is a shared configuration, you can set the values instead.
  18124. */
  18125. get: function () {
  18126. return this._imageProcessingConfiguration;
  18127. },
  18128. enumerable: true,
  18129. configurable: true
  18130. });
  18131. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  18132. get: function () {
  18133. return this._forcePointsCloud;
  18134. },
  18135. set: function (value) {
  18136. if (this._forcePointsCloud === value) {
  18137. return;
  18138. }
  18139. this._forcePointsCloud = value;
  18140. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18141. },
  18142. enumerable: true,
  18143. configurable: true
  18144. });
  18145. Object.defineProperty(Scene.prototype, "onDispose", {
  18146. /** A function to be executed when this scene is disposed. */
  18147. set: function (callback) {
  18148. if (this._onDisposeObserver) {
  18149. this.onDisposeObservable.remove(this._onDisposeObserver);
  18150. }
  18151. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18152. },
  18153. enumerable: true,
  18154. configurable: true
  18155. });
  18156. Object.defineProperty(Scene.prototype, "beforeRender", {
  18157. /** A function to be executed before rendering this scene */
  18158. set: function (callback) {
  18159. if (this._onBeforeRenderObserver) {
  18160. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  18161. }
  18162. if (callback) {
  18163. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  18164. }
  18165. },
  18166. enumerable: true,
  18167. configurable: true
  18168. });
  18169. Object.defineProperty(Scene.prototype, "afterRender", {
  18170. /** A function to be executed after rendering this scene */
  18171. set: function (callback) {
  18172. if (this._onAfterRenderObserver) {
  18173. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  18174. }
  18175. if (callback) {
  18176. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  18177. }
  18178. },
  18179. enumerable: true,
  18180. configurable: true
  18181. });
  18182. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  18183. set: function (callback) {
  18184. if (this._onBeforeCameraRenderObserver) {
  18185. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  18186. }
  18187. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  18188. },
  18189. enumerable: true,
  18190. configurable: true
  18191. });
  18192. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  18193. set: function (callback) {
  18194. if (this._onAfterCameraRenderObserver) {
  18195. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  18196. }
  18197. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  18198. },
  18199. enumerable: true,
  18200. configurable: true
  18201. });
  18202. Object.defineProperty(Scene.prototype, "gamepadManager", {
  18203. get: function () {
  18204. if (!this._gamepadManager) {
  18205. this._gamepadManager = new BABYLON.GamepadManager();
  18206. }
  18207. return this._gamepadManager;
  18208. },
  18209. enumerable: true,
  18210. configurable: true
  18211. });
  18212. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  18213. get: function () {
  18214. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  18215. },
  18216. enumerable: true,
  18217. configurable: true
  18218. });
  18219. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  18220. get: function () {
  18221. return this._useRightHandedSystem;
  18222. },
  18223. set: function (value) {
  18224. if (this._useRightHandedSystem === value) {
  18225. return;
  18226. }
  18227. this._useRightHandedSystem = value;
  18228. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18229. },
  18230. enumerable: true,
  18231. configurable: true
  18232. });
  18233. Scene.prototype.setStepId = function (newStepId) {
  18234. this._currentStepId = newStepId;
  18235. };
  18236. ;
  18237. Scene.prototype.getStepId = function () {
  18238. return this._currentStepId;
  18239. };
  18240. ;
  18241. Scene.prototype.getInternalStep = function () {
  18242. return this._currentInternalStep;
  18243. };
  18244. ;
  18245. Object.defineProperty(Scene.prototype, "fogEnabled", {
  18246. get: function () {
  18247. return this._fogEnabled;
  18248. },
  18249. /**
  18250. * is fog enabled on this scene.
  18251. */
  18252. set: function (value) {
  18253. if (this._fogEnabled === value) {
  18254. return;
  18255. }
  18256. this._fogEnabled = value;
  18257. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18258. },
  18259. enumerable: true,
  18260. configurable: true
  18261. });
  18262. Object.defineProperty(Scene.prototype, "fogMode", {
  18263. get: function () {
  18264. return this._fogMode;
  18265. },
  18266. set: function (value) {
  18267. if (this._fogMode === value) {
  18268. return;
  18269. }
  18270. this._fogMode = value;
  18271. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18272. },
  18273. enumerable: true,
  18274. configurable: true
  18275. });
  18276. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  18277. get: function () {
  18278. return this._shadowsEnabled;
  18279. },
  18280. set: function (value) {
  18281. if (this._shadowsEnabled === value) {
  18282. return;
  18283. }
  18284. this._shadowsEnabled = value;
  18285. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18286. },
  18287. enumerable: true,
  18288. configurable: true
  18289. });
  18290. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  18291. get: function () {
  18292. return this._lightsEnabled;
  18293. },
  18294. set: function (value) {
  18295. if (this._lightsEnabled === value) {
  18296. return;
  18297. }
  18298. this._lightsEnabled = value;
  18299. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18300. },
  18301. enumerable: true,
  18302. configurable: true
  18303. });
  18304. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  18305. /** The default material used on meshes when no material is affected */
  18306. get: function () {
  18307. if (!this._defaultMaterial) {
  18308. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  18309. }
  18310. return this._defaultMaterial;
  18311. },
  18312. /** The default material used on meshes when no material is affected */
  18313. set: function (value) {
  18314. this._defaultMaterial = value;
  18315. },
  18316. enumerable: true,
  18317. configurable: true
  18318. });
  18319. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  18320. get: function () {
  18321. return this._texturesEnabled;
  18322. },
  18323. set: function (value) {
  18324. if (this._texturesEnabled === value) {
  18325. return;
  18326. }
  18327. this._texturesEnabled = value;
  18328. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18329. },
  18330. enumerable: true,
  18331. configurable: true
  18332. });
  18333. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  18334. get: function () {
  18335. return this._skeletonsEnabled;
  18336. },
  18337. set: function (value) {
  18338. if (this._skeletonsEnabled === value) {
  18339. return;
  18340. }
  18341. this._skeletonsEnabled = value;
  18342. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  18343. },
  18344. enumerable: true,
  18345. configurable: true
  18346. });
  18347. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  18348. get: function () {
  18349. if (!this._postProcessRenderPipelineManager) {
  18350. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  18351. }
  18352. return this._postProcessRenderPipelineManager;
  18353. },
  18354. enumerable: true,
  18355. configurable: true
  18356. });
  18357. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  18358. get: function () {
  18359. if (!this._mainSoundTrack) {
  18360. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  18361. }
  18362. return this._mainSoundTrack;
  18363. },
  18364. enumerable: true,
  18365. configurable: true
  18366. });
  18367. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  18368. get: function () {
  18369. return this._alternateRendering;
  18370. },
  18371. enumerable: true,
  18372. configurable: true
  18373. });
  18374. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  18375. get: function () {
  18376. return this._frustumPlanes;
  18377. },
  18378. enumerable: true,
  18379. configurable: true
  18380. });
  18381. Object.defineProperty(Scene.prototype, "debugLayer", {
  18382. // Properties
  18383. get: function () {
  18384. if (!this._debugLayer) {
  18385. this._debugLayer = new BABYLON.DebugLayer(this);
  18386. }
  18387. return this._debugLayer;
  18388. },
  18389. enumerable: true,
  18390. configurable: true
  18391. });
  18392. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18393. get: function () {
  18394. return this._workerCollisions;
  18395. },
  18396. set: function (enabled) {
  18397. if (!BABYLON.CollisionCoordinatorLegacy) {
  18398. return;
  18399. }
  18400. enabled = (enabled && !!Worker);
  18401. this._workerCollisions = enabled;
  18402. if (this.collisionCoordinator) {
  18403. this.collisionCoordinator.destroy();
  18404. }
  18405. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18406. this.collisionCoordinator.init(this);
  18407. },
  18408. enumerable: true,
  18409. configurable: true
  18410. });
  18411. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18412. get: function () {
  18413. return this._selectionOctree;
  18414. },
  18415. enumerable: true,
  18416. configurable: true
  18417. });
  18418. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18419. /**
  18420. * The mesh that is currently under the pointer.
  18421. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18422. */
  18423. get: function () {
  18424. return this._pointerOverMesh;
  18425. },
  18426. enumerable: true,
  18427. configurable: true
  18428. });
  18429. Object.defineProperty(Scene.prototype, "pointerX", {
  18430. /**
  18431. * Current on-screen X position of the pointer
  18432. * @return {number} X position of the pointer
  18433. */
  18434. get: function () {
  18435. return this._pointerX;
  18436. },
  18437. enumerable: true,
  18438. configurable: true
  18439. });
  18440. Object.defineProperty(Scene.prototype, "pointerY", {
  18441. /**
  18442. * Current on-screen Y position of the pointer
  18443. * @return {number} Y position of the pointer
  18444. */
  18445. get: function () {
  18446. return this._pointerY;
  18447. },
  18448. enumerable: true,
  18449. configurable: true
  18450. });
  18451. Scene.prototype.getCachedMaterial = function () {
  18452. return this._cachedMaterial;
  18453. };
  18454. Scene.prototype.getCachedEffect = function () {
  18455. return this._cachedEffect;
  18456. };
  18457. Scene.prototype.getCachedVisibility = function () {
  18458. return this._cachedVisibility;
  18459. };
  18460. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18461. if (visibility === void 0) { visibility = 1; }
  18462. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18463. };
  18464. Scene.prototype.getBoundingBoxRenderer = function () {
  18465. if (!this._boundingBoxRenderer) {
  18466. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18467. }
  18468. return this._boundingBoxRenderer;
  18469. };
  18470. Scene.prototype.getOutlineRenderer = function () {
  18471. return this._outlineRenderer;
  18472. };
  18473. Scene.prototype.getEngine = function () {
  18474. return this._engine;
  18475. };
  18476. Scene.prototype.getTotalVertices = function () {
  18477. return this._totalVertices.current;
  18478. };
  18479. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18480. get: function () {
  18481. return this._totalVertices;
  18482. },
  18483. enumerable: true,
  18484. configurable: true
  18485. });
  18486. Scene.prototype.getActiveIndices = function () {
  18487. return this._activeIndices.current;
  18488. };
  18489. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18490. get: function () {
  18491. return this._activeIndices;
  18492. },
  18493. enumerable: true,
  18494. configurable: true
  18495. });
  18496. Scene.prototype.getActiveParticles = function () {
  18497. return this._activeParticles.current;
  18498. };
  18499. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18500. get: function () {
  18501. return this._activeParticles;
  18502. },
  18503. enumerable: true,
  18504. configurable: true
  18505. });
  18506. Scene.prototype.getActiveBones = function () {
  18507. return this._activeBones.current;
  18508. };
  18509. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18510. get: function () {
  18511. return this._activeBones;
  18512. },
  18513. enumerable: true,
  18514. configurable: true
  18515. });
  18516. // Stats
  18517. Scene.prototype.getInterFramePerfCounter = function () {
  18518. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18519. return 0;
  18520. };
  18521. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18522. get: function () {
  18523. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18524. return null;
  18525. },
  18526. enumerable: true,
  18527. configurable: true
  18528. });
  18529. Scene.prototype.getLastFrameDuration = function () {
  18530. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18531. return 0;
  18532. };
  18533. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18534. get: function () {
  18535. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18536. return null;
  18537. },
  18538. enumerable: true,
  18539. configurable: true
  18540. });
  18541. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18542. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18543. return 0;
  18544. };
  18545. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18546. get: function () {
  18547. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18548. return null;
  18549. },
  18550. enumerable: true,
  18551. configurable: true
  18552. });
  18553. Scene.prototype.getActiveMeshes = function () {
  18554. return this._activeMeshes;
  18555. };
  18556. Scene.prototype.getRenderTargetsDuration = function () {
  18557. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18558. return 0;
  18559. };
  18560. Scene.prototype.getRenderDuration = function () {
  18561. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18562. return 0;
  18563. };
  18564. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18565. get: function () {
  18566. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18567. return null;
  18568. },
  18569. enumerable: true,
  18570. configurable: true
  18571. });
  18572. Scene.prototype.getParticlesDuration = function () {
  18573. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18574. return 0;
  18575. };
  18576. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18577. get: function () {
  18578. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18579. return null;
  18580. },
  18581. enumerable: true,
  18582. configurable: true
  18583. });
  18584. Scene.prototype.getSpritesDuration = function () {
  18585. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18586. return 0;
  18587. };
  18588. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18589. get: function () {
  18590. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18591. return null;
  18592. },
  18593. enumerable: true,
  18594. configurable: true
  18595. });
  18596. Scene.prototype.getAnimationRatio = function () {
  18597. return this._animationRatio;
  18598. };
  18599. Scene.prototype.getRenderId = function () {
  18600. return this._renderId;
  18601. };
  18602. Scene.prototype.incrementRenderId = function () {
  18603. this._renderId++;
  18604. };
  18605. Scene.prototype._updatePointerPosition = function (evt) {
  18606. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18607. if (!canvasRect) {
  18608. return;
  18609. }
  18610. this._pointerX = evt.clientX - canvasRect.left;
  18611. this._pointerY = evt.clientY - canvasRect.top;
  18612. this._unTranslatedPointerX = this._pointerX;
  18613. this._unTranslatedPointerY = this._pointerY;
  18614. };
  18615. Scene.prototype._createUbo = function () {
  18616. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18617. this._sceneUbo.addUniform("viewProjection", 16);
  18618. this._sceneUbo.addUniform("view", 16);
  18619. };
  18620. Scene.prototype._createAlternateUbo = function () {
  18621. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18622. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18623. this._alternateSceneUbo.addUniform("view", 16);
  18624. };
  18625. // Pointers handling
  18626. /**
  18627. * Use this method to simulate a pointer move on a mesh
  18628. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18629. */
  18630. Scene.prototype.simulatePointerMove = function (pickResult) {
  18631. var evt = new PointerEvent("pointermove");
  18632. return this._processPointerMove(pickResult, evt);
  18633. };
  18634. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18635. var canvas = this._engine.getRenderingCanvas();
  18636. if (!canvas) {
  18637. return this;
  18638. }
  18639. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18640. this.setPointerOverSprite(null);
  18641. this.setPointerOverMesh(pickResult.pickedMesh);
  18642. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18643. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18644. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18645. }
  18646. else {
  18647. canvas.style.cursor = this.hoverCursor;
  18648. }
  18649. }
  18650. else {
  18651. canvas.style.cursor = this.defaultCursor;
  18652. }
  18653. }
  18654. else {
  18655. this.setPointerOverMesh(null);
  18656. // Sprites
  18657. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18658. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18659. this.setPointerOverSprite(pickResult.pickedSprite);
  18660. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18661. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18662. }
  18663. else {
  18664. canvas.style.cursor = this.hoverCursor;
  18665. }
  18666. }
  18667. else {
  18668. this.setPointerOverSprite(null);
  18669. // Restore pointer
  18670. canvas.style.cursor = this.defaultCursor;
  18671. }
  18672. }
  18673. if (pickResult) {
  18674. if (this.onPointerMove) {
  18675. this.onPointerMove(evt, pickResult);
  18676. }
  18677. if (this.onPointerObservable.hasObservers()) {
  18678. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18679. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18680. this.onPointerObservable.notifyObservers(pi, type);
  18681. }
  18682. }
  18683. return this;
  18684. };
  18685. /**
  18686. * Use this method to simulate a pointer down on a mesh
  18687. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18688. */
  18689. Scene.prototype.simulatePointerDown = function (pickResult) {
  18690. var evt = new PointerEvent("pointerdown");
  18691. return this._processPointerDown(pickResult, evt);
  18692. };
  18693. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18694. var _this = this;
  18695. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18696. this._pickedDownMesh = pickResult.pickedMesh;
  18697. var actionManager = pickResult.pickedMesh.actionManager;
  18698. if (actionManager) {
  18699. if (actionManager.hasPickTriggers) {
  18700. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18701. switch (evt.button) {
  18702. case 0:
  18703. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18704. break;
  18705. case 1:
  18706. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18707. break;
  18708. case 2:
  18709. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18710. break;
  18711. }
  18712. }
  18713. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18714. window.setTimeout(function () {
  18715. 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);
  18716. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18717. if (_this._totalPointersPressed !== 0 &&
  18718. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18719. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18720. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18721. _this._startingPointerTime = 0;
  18722. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18723. }
  18724. }
  18725. }, Scene.LongPressDelay);
  18726. }
  18727. }
  18728. }
  18729. if (pickResult) {
  18730. if (this.onPointerDown) {
  18731. this.onPointerDown(evt, pickResult);
  18732. }
  18733. if (this.onPointerObservable.hasObservers()) {
  18734. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18735. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18736. this.onPointerObservable.notifyObservers(pi, type);
  18737. }
  18738. }
  18739. return this;
  18740. };
  18741. /**
  18742. * Use this method to simulate a pointer up on a mesh
  18743. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18744. */
  18745. Scene.prototype.simulatePointerUp = function (pickResult) {
  18746. var evt = new PointerEvent("pointerup");
  18747. var clickInfo = new ClickInfo();
  18748. clickInfo.singleClick = true;
  18749. return this._processPointerUp(pickResult, evt, clickInfo);
  18750. };
  18751. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18752. if (pickResult && pickResult && pickResult.pickedMesh) {
  18753. this._pickedUpMesh = pickResult.pickedMesh;
  18754. if (this._pickedDownMesh === this._pickedUpMesh) {
  18755. if (this.onPointerPick) {
  18756. this.onPointerPick(evt, pickResult);
  18757. }
  18758. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18759. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18760. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18761. this.onPointerObservable.notifyObservers(pi, type);
  18762. }
  18763. }
  18764. if (pickResult.pickedMesh.actionManager) {
  18765. if (clickInfo.ignore) {
  18766. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18767. }
  18768. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18769. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18770. }
  18771. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18772. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18773. }
  18774. }
  18775. }
  18776. if (this._pickedDownMesh &&
  18777. this._pickedDownMesh.actionManager &&
  18778. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18779. this._pickedDownMesh !== this._pickedUpMesh) {
  18780. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18781. }
  18782. if (this.onPointerUp) {
  18783. this.onPointerUp(evt, pickResult);
  18784. }
  18785. if (this.onPointerObservable.hasObservers()) {
  18786. if (!clickInfo.ignore) {
  18787. if (!clickInfo.hasSwiped) {
  18788. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18789. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18790. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18791. this.onPointerObservable.notifyObservers(pi, type);
  18792. }
  18793. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18794. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18795. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18796. this.onPointerObservable.notifyObservers(pi, type);
  18797. }
  18798. }
  18799. }
  18800. else {
  18801. var type = BABYLON.PointerEventTypes.POINTERUP;
  18802. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18803. this.onPointerObservable.notifyObservers(pi, type);
  18804. }
  18805. }
  18806. return this;
  18807. };
  18808. /**
  18809. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18810. * @param attachUp defines if you want to attach events to pointerup
  18811. * @param attachDown defines if you want to attach events to pointerdown
  18812. * @param attachMove defines if you want to attach events to pointermove
  18813. */
  18814. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18815. var _this = this;
  18816. if (attachUp === void 0) { attachUp = true; }
  18817. if (attachDown === void 0) { attachDown = true; }
  18818. if (attachMove === void 0) { attachMove = true; }
  18819. this._initActionManager = function (act, clickInfo) {
  18820. if (!_this._meshPickProceed) {
  18821. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18822. _this._currentPickResult = pickResult;
  18823. if (pickResult) {
  18824. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18825. }
  18826. _this._meshPickProceed = true;
  18827. }
  18828. return act;
  18829. };
  18830. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18831. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18832. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18833. btn !== _this._previousButtonPressed) {
  18834. _this._doubleClickOccured = false;
  18835. clickInfo.singleClick = true;
  18836. clickInfo.ignore = false;
  18837. cb(clickInfo, _this._currentPickResult);
  18838. }
  18839. };
  18840. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18841. var clickInfo = new ClickInfo();
  18842. _this._currentPickResult = null;
  18843. var act = null;
  18844. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18845. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18846. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18847. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18848. act = _this._initActionManager(act, clickInfo);
  18849. if (act)
  18850. checkPicking = act.hasPickTriggers;
  18851. }
  18852. if (checkPicking) {
  18853. var btn = evt.button;
  18854. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18855. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18856. if (!clickInfo.hasSwiped) {
  18857. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18858. if (!checkSingleClickImmediately) {
  18859. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18860. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18861. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18862. act = _this._initActionManager(act, clickInfo);
  18863. if (act)
  18864. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18865. }
  18866. }
  18867. if (checkSingleClickImmediately) {
  18868. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18869. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18870. btn !== _this._previousButtonPressed) {
  18871. clickInfo.singleClick = true;
  18872. cb(clickInfo, _this._currentPickResult);
  18873. }
  18874. }
  18875. else {
  18876. // wait that no double click has been raised during the double click delay
  18877. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18878. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18879. }
  18880. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18881. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18882. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18883. act = _this._initActionManager(act, clickInfo);
  18884. if (act)
  18885. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18886. }
  18887. if (checkDoubleClick) {
  18888. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18889. if (btn === _this._previousButtonPressed &&
  18890. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18891. !_this._doubleClickOccured) {
  18892. // pointer has not moved for 2 clicks, it's a double click
  18893. if (!clickInfo.hasSwiped &&
  18894. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18895. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18896. _this._previousStartingPointerTime = 0;
  18897. _this._doubleClickOccured = true;
  18898. clickInfo.doubleClick = true;
  18899. clickInfo.ignore = false;
  18900. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18901. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18902. }
  18903. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18904. cb(clickInfo, _this._currentPickResult);
  18905. }
  18906. else {
  18907. _this._doubleClickOccured = false;
  18908. _this._previousStartingPointerTime = _this._startingPointerTime;
  18909. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18910. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18911. _this._previousButtonPressed = btn;
  18912. _this._previousHasSwiped = clickInfo.hasSwiped;
  18913. if (Scene.ExclusiveDoubleClickMode) {
  18914. if (_this._previousDelayedSimpleClickTimeout) {
  18915. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18916. }
  18917. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18918. cb(clickInfo, _this._previousPickResult);
  18919. }
  18920. else {
  18921. cb(clickInfo, _this._currentPickResult);
  18922. }
  18923. }
  18924. }
  18925. else {
  18926. _this._doubleClickOccured = false;
  18927. _this._previousStartingPointerTime = _this._startingPointerTime;
  18928. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18929. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18930. _this._previousButtonPressed = btn;
  18931. _this._previousHasSwiped = clickInfo.hasSwiped;
  18932. }
  18933. }
  18934. }
  18935. }
  18936. clickInfo.ignore = true;
  18937. cb(clickInfo, _this._currentPickResult);
  18938. };
  18939. this._spritePredicate = function (sprite) {
  18940. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18941. };
  18942. this._onPointerMove = function (evt) {
  18943. _this._updatePointerPosition(evt);
  18944. // PreObservable support
  18945. if (_this.onPrePointerObservable.hasObservers()) {
  18946. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18947. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18948. _this.onPrePointerObservable.notifyObservers(pi, type);
  18949. if (pi.skipOnPointerObservable) {
  18950. return;
  18951. }
  18952. }
  18953. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18954. return;
  18955. }
  18956. if (!_this.pointerMovePredicate) {
  18957. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18958. }
  18959. // Meshes
  18960. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18961. _this._processPointerMove(pickResult, evt);
  18962. };
  18963. this._onPointerDown = function (evt) {
  18964. _this._totalPointersPressed++;
  18965. _this._pickedDownMesh = null;
  18966. _this._meshPickProceed = false;
  18967. _this._updatePointerPosition(evt);
  18968. if (_this.preventDefaultOnPointerDown && canvas) {
  18969. evt.preventDefault();
  18970. canvas.focus();
  18971. }
  18972. // PreObservable support
  18973. if (_this.onPrePointerObservable.hasObservers()) {
  18974. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18975. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18976. _this.onPrePointerObservable.notifyObservers(pi, type);
  18977. if (pi.skipOnPointerObservable) {
  18978. return;
  18979. }
  18980. }
  18981. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18982. return;
  18983. }
  18984. _this._startingPointerPosition.x = _this._pointerX;
  18985. _this._startingPointerPosition.y = _this._pointerY;
  18986. _this._startingPointerTime = new Date().getTime();
  18987. if (!_this.pointerDownPredicate) {
  18988. _this.pointerDownPredicate = function (mesh) {
  18989. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18990. };
  18991. }
  18992. // Meshes
  18993. _this._pickedDownMesh = null;
  18994. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18995. _this._processPointerDown(pickResult, evt);
  18996. // Sprites
  18997. _this._pickedDownSprite = null;
  18998. if (_this.spriteManagers.length > 0) {
  18999. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19000. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19001. if (pickResult.pickedSprite.actionManager) {
  19002. _this._pickedDownSprite = pickResult.pickedSprite;
  19003. switch (evt.button) {
  19004. case 0:
  19005. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19006. break;
  19007. case 1:
  19008. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19009. break;
  19010. case 2:
  19011. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19012. break;
  19013. }
  19014. if (pickResult.pickedSprite.actionManager) {
  19015. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19016. }
  19017. }
  19018. }
  19019. }
  19020. };
  19021. this._onPointerUp = function (evt) {
  19022. if (_this._totalPointersPressed === 0) {
  19023. return; // So we need to test it the pointer down was pressed before.
  19024. }
  19025. _this._totalPointersPressed--;
  19026. _this._pickedUpMesh = null;
  19027. _this._meshPickProceed = false;
  19028. _this._updatePointerPosition(evt);
  19029. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  19030. // PreObservable support
  19031. if (_this.onPrePointerObservable.hasObservers()) {
  19032. if (!clickInfo.ignore) {
  19033. if (!clickInfo.hasSwiped) {
  19034. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19035. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19036. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19037. _this.onPrePointerObservable.notifyObservers(pi, type);
  19038. if (pi.skipOnPointerObservable) {
  19039. return;
  19040. }
  19041. }
  19042. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19043. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19044. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19045. _this.onPrePointerObservable.notifyObservers(pi, type);
  19046. if (pi.skipOnPointerObservable) {
  19047. return;
  19048. }
  19049. }
  19050. }
  19051. }
  19052. else {
  19053. var type = BABYLON.PointerEventTypes.POINTERUP;
  19054. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19055. _this.onPrePointerObservable.notifyObservers(pi, type);
  19056. if (pi.skipOnPointerObservable) {
  19057. return;
  19058. }
  19059. }
  19060. }
  19061. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19062. return;
  19063. }
  19064. if (!_this.pointerUpPredicate) {
  19065. _this.pointerUpPredicate = function (mesh) {
  19066. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19067. };
  19068. }
  19069. // Meshes
  19070. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  19071. _this._initActionManager(null, clickInfo);
  19072. }
  19073. if (!pickResult) {
  19074. pickResult = _this._currentPickResult;
  19075. }
  19076. _this._processPointerUp(pickResult, evt, clickInfo);
  19077. // Sprites
  19078. if (_this.spriteManagers.length > 0) {
  19079. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19080. if (spritePickResult) {
  19081. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  19082. if (spritePickResult.pickedSprite.actionManager) {
  19083. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19084. if (spritePickResult.pickedSprite.actionManager) {
  19085. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  19086. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19087. }
  19088. }
  19089. }
  19090. }
  19091. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  19092. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19093. }
  19094. }
  19095. }
  19096. _this._previousPickResult = _this._currentPickResult;
  19097. });
  19098. };
  19099. this._onKeyDown = function (evt) {
  19100. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  19101. if (_this.onPreKeyboardObservable.hasObservers()) {
  19102. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19103. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19104. if (pi.skipOnPointerObservable) {
  19105. return;
  19106. }
  19107. }
  19108. if (_this.onKeyboardObservable.hasObservers()) {
  19109. var pi = new BABYLON.KeyboardInfo(type, evt);
  19110. _this.onKeyboardObservable.notifyObservers(pi, type);
  19111. }
  19112. if (_this.actionManager) {
  19113. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19114. }
  19115. };
  19116. this._onKeyUp = function (evt) {
  19117. var type = BABYLON.KeyboardEventTypes.KEYUP;
  19118. if (_this.onPreKeyboardObservable.hasObservers()) {
  19119. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19120. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19121. if (pi.skipOnPointerObservable) {
  19122. return;
  19123. }
  19124. }
  19125. if (_this.onKeyboardObservable.hasObservers()) {
  19126. var pi = new BABYLON.KeyboardInfo(type, evt);
  19127. _this.onKeyboardObservable.notifyObservers(pi, type);
  19128. }
  19129. if (_this.actionManager) {
  19130. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19131. }
  19132. };
  19133. var engine = this.getEngine();
  19134. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  19135. if (!canvas) {
  19136. return;
  19137. }
  19138. canvas.addEventListener("keydown", _this._onKeyDown, false);
  19139. canvas.addEventListener("keyup", _this._onKeyUp, false);
  19140. });
  19141. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  19142. if (!canvas) {
  19143. return;
  19144. }
  19145. canvas.removeEventListener("keydown", _this._onKeyDown);
  19146. canvas.removeEventListener("keyup", _this._onKeyUp);
  19147. });
  19148. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19149. var canvas = this._engine.getRenderingCanvas();
  19150. if (!canvas) {
  19151. return;
  19152. }
  19153. if (attachMove) {
  19154. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19155. // Wheel
  19156. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19157. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19158. }
  19159. if (attachDown) {
  19160. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19161. }
  19162. if (attachUp) {
  19163. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19164. }
  19165. canvas.tabIndex = 1;
  19166. };
  19167. Scene.prototype.detachControl = function () {
  19168. var engine = this.getEngine();
  19169. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19170. var canvas = engine.getRenderingCanvas();
  19171. if (!canvas) {
  19172. return;
  19173. }
  19174. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19175. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19176. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19177. if (this._onCanvasBlurObserver) {
  19178. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  19179. }
  19180. if (this._onCanvasFocusObserver) {
  19181. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  19182. }
  19183. // Wheel
  19184. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19185. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19186. // Keyboard
  19187. canvas.removeEventListener("keydown", this._onKeyDown);
  19188. canvas.removeEventListener("keyup", this._onKeyUp);
  19189. // Observables
  19190. this.onKeyboardObservable.clear();
  19191. this.onPreKeyboardObservable.clear();
  19192. this.onPointerObservable.clear();
  19193. this.onPrePointerObservable.clear();
  19194. };
  19195. // Ready
  19196. Scene.prototype.isReady = function () {
  19197. if (this._isDisposed) {
  19198. return false;
  19199. }
  19200. if (this._pendingData.length > 0) {
  19201. return false;
  19202. }
  19203. var index;
  19204. // Geometries
  19205. for (index = 0; index < this._geometries.length; index++) {
  19206. var geometry = this._geometries[index];
  19207. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19208. return false;
  19209. }
  19210. }
  19211. // Meshes
  19212. for (index = 0; index < this.meshes.length; index++) {
  19213. var mesh = this.meshes[index];
  19214. if (!mesh.isEnabled()) {
  19215. continue;
  19216. }
  19217. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19218. continue;
  19219. }
  19220. if (!mesh.isReady()) {
  19221. return false;
  19222. }
  19223. var mat = mesh.material;
  19224. if (mat) {
  19225. if (!mat.isReady(mesh)) {
  19226. return false;
  19227. }
  19228. }
  19229. }
  19230. return true;
  19231. };
  19232. Scene.prototype.resetCachedMaterial = function () {
  19233. this._cachedMaterial = null;
  19234. this._cachedEffect = null;
  19235. this._cachedVisibility = null;
  19236. };
  19237. Scene.prototype.registerBeforeRender = function (func) {
  19238. this.onBeforeRenderObservable.add(func);
  19239. };
  19240. Scene.prototype.unregisterBeforeRender = function (func) {
  19241. this.onBeforeRenderObservable.removeCallback(func);
  19242. };
  19243. Scene.prototype.registerAfterRender = function (func) {
  19244. this.onAfterRenderObservable.add(func);
  19245. };
  19246. Scene.prototype.unregisterAfterRender = function (func) {
  19247. this.onAfterRenderObservable.removeCallback(func);
  19248. };
  19249. Scene.prototype._addPendingData = function (data) {
  19250. this._pendingData.push(data);
  19251. };
  19252. Scene.prototype._removePendingData = function (data) {
  19253. var wasLoading = this.isLoading;
  19254. var index = this._pendingData.indexOf(data);
  19255. if (index !== -1) {
  19256. this._pendingData.splice(index, 1);
  19257. }
  19258. if (wasLoading && !this.isLoading) {
  19259. this.onDataLoadedObservable.notifyObservers(this);
  19260. }
  19261. };
  19262. Scene.prototype.getWaitingItemsCount = function () {
  19263. return this._pendingData.length;
  19264. };
  19265. Object.defineProperty(Scene.prototype, "isLoading", {
  19266. get: function () {
  19267. return this._pendingData.length > 0;
  19268. },
  19269. enumerable: true,
  19270. configurable: true
  19271. });
  19272. /**
  19273. * Registers a function to be executed when the scene is ready.
  19274. * @param {Function} func - the function to be executed.
  19275. */
  19276. Scene.prototype.executeWhenReady = function (func) {
  19277. var _this = this;
  19278. this.onReadyObservable.add(func);
  19279. if (this._executeWhenReadyTimeoutId !== -1) {
  19280. return;
  19281. }
  19282. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19283. _this._checkIsReady();
  19284. }, 150);
  19285. };
  19286. Scene.prototype._checkIsReady = function () {
  19287. var _this = this;
  19288. if (this.isReady()) {
  19289. this.onReadyObservable.notifyObservers(this);
  19290. this.onReadyObservable.clear();
  19291. this._executeWhenReadyTimeoutId = -1;
  19292. return;
  19293. }
  19294. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19295. _this._checkIsReady();
  19296. }, 150);
  19297. };
  19298. // Animations
  19299. /**
  19300. * Will start the animation sequence of a given target
  19301. * @param target - the target
  19302. * @param {number} from - from which frame should animation start
  19303. * @param {number} to - till which frame should animation run.
  19304. * @param {boolean} [loop] - should the animation loop
  19305. * @param {number} [speedRatio] - the speed in which to run the animation
  19306. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  19307. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  19308. * Returns {BABYLON.Animatable} the animatable object created for this animation
  19309. * See BABYLON.Animatable
  19310. */
  19311. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  19312. if (speedRatio === void 0) { speedRatio = 1.0; }
  19313. if (from > to && speedRatio > 0) {
  19314. speedRatio *= -1;
  19315. }
  19316. this.stopAnimation(target);
  19317. if (!animatable) {
  19318. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  19319. }
  19320. // Local animations
  19321. if (target.animations) {
  19322. animatable.appendAnimations(target, target.animations);
  19323. }
  19324. // Children animations
  19325. if (target.getAnimatables) {
  19326. var animatables = target.getAnimatables();
  19327. for (var index = 0; index < animatables.length; index++) {
  19328. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  19329. }
  19330. }
  19331. animatable.reset();
  19332. return animatable;
  19333. };
  19334. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19335. if (speedRatio === undefined) {
  19336. speedRatio = 1.0;
  19337. }
  19338. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  19339. return animatable;
  19340. };
  19341. Scene.prototype.getAnimatableByTarget = function (target) {
  19342. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19343. if (this._activeAnimatables[index].target === target) {
  19344. return this._activeAnimatables[index];
  19345. }
  19346. }
  19347. return null;
  19348. };
  19349. Object.defineProperty(Scene.prototype, "Animatables", {
  19350. get: function () {
  19351. return this._activeAnimatables;
  19352. },
  19353. enumerable: true,
  19354. configurable: true
  19355. });
  19356. /**
  19357. * Will stop the animation of the given target
  19358. * @param target - the target
  19359. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  19360. * @see beginAnimation
  19361. */
  19362. Scene.prototype.stopAnimation = function (target, animationName) {
  19363. var animatable = this.getAnimatableByTarget(target);
  19364. if (animatable) {
  19365. animatable.stop(animationName);
  19366. }
  19367. };
  19368. /**
  19369. * Stops and removes all animations that have been applied to the scene
  19370. */
  19371. Scene.prototype.stopAllAnimations = function () {
  19372. if (this._activeAnimatables) {
  19373. for (var i = 0; i < this._activeAnimatables.length; i++) {
  19374. this._activeAnimatables[i].stop();
  19375. }
  19376. this._activeAnimatables = [];
  19377. }
  19378. };
  19379. Scene.prototype._animate = function () {
  19380. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  19381. return;
  19382. }
  19383. // Getting time
  19384. var now = BABYLON.Tools.Now;
  19385. if (!this._animationTimeLast) {
  19386. if (this._pendingData.length > 0) {
  19387. return;
  19388. }
  19389. this._animationTimeLast = now;
  19390. }
  19391. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  19392. this._animationTime += deltaTime;
  19393. this._animationTimeLast = now;
  19394. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19395. this._activeAnimatables[index]._animate(this._animationTime);
  19396. }
  19397. };
  19398. // Matrix
  19399. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  19400. this._useAlternateCameraConfiguration = active;
  19401. };
  19402. Scene.prototype.getViewMatrix = function () {
  19403. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  19404. };
  19405. Scene.prototype.getProjectionMatrix = function () {
  19406. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  19407. };
  19408. Scene.prototype.getTransformMatrix = function () {
  19409. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  19410. };
  19411. Scene.prototype.setTransformMatrix = function (view, projection) {
  19412. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  19413. return;
  19414. }
  19415. this._viewUpdateFlag = view.updateFlag;
  19416. this._projectionUpdateFlag = projection.updateFlag;
  19417. this._viewMatrix = view;
  19418. this._projectionMatrix = projection;
  19419. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19420. // Update frustum
  19421. if (!this._frustumPlanes) {
  19422. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19423. }
  19424. else {
  19425. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19426. }
  19427. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19428. var otherCamera = this.activeCamera._alternateCamera;
  19429. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19430. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19431. }
  19432. if (this._sceneUbo.useUbo) {
  19433. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19434. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19435. this._sceneUbo.update();
  19436. }
  19437. };
  19438. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19439. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19440. return;
  19441. }
  19442. this._alternateViewUpdateFlag = view.updateFlag;
  19443. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19444. this._alternateViewMatrix = view;
  19445. this._alternateProjectionMatrix = projection;
  19446. if (!this._alternateTransformMatrix) {
  19447. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19448. }
  19449. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19450. if (!this._alternateSceneUbo) {
  19451. this._createAlternateUbo();
  19452. }
  19453. if (this._alternateSceneUbo.useUbo) {
  19454. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19455. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19456. this._alternateSceneUbo.update();
  19457. }
  19458. };
  19459. Scene.prototype.getSceneUniformBuffer = function () {
  19460. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19461. };
  19462. // Methods
  19463. Scene.prototype.getUniqueId = function () {
  19464. var result = Scene._uniqueIdCounter;
  19465. Scene._uniqueIdCounter++;
  19466. return result;
  19467. };
  19468. Scene.prototype.addMesh = function (newMesh) {
  19469. this.meshes.push(newMesh);
  19470. //notify the collision coordinator
  19471. if (this.collisionCoordinator) {
  19472. this.collisionCoordinator.onMeshAdded(newMesh);
  19473. }
  19474. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19475. };
  19476. Scene.prototype.removeMesh = function (toRemove) {
  19477. var index = this.meshes.indexOf(toRemove);
  19478. if (index !== -1) {
  19479. // Remove from the scene if mesh found
  19480. this.meshes.splice(index, 1);
  19481. }
  19482. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19483. return index;
  19484. };
  19485. Scene.prototype.addTransformNode = function (newTransformNode) {
  19486. this.transformNodes.push(newTransformNode);
  19487. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  19488. };
  19489. Scene.prototype.removeTransformNode = function (toRemove) {
  19490. var index = this.transformNodes.indexOf(toRemove);
  19491. if (index !== -1) {
  19492. // Remove from the scene if found
  19493. this.transformNodes.splice(index, 1);
  19494. }
  19495. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  19496. return index;
  19497. };
  19498. Scene.prototype.removeSkeleton = function (toRemove) {
  19499. var index = this.skeletons.indexOf(toRemove);
  19500. if (index !== -1) {
  19501. // Remove from the scene if found
  19502. this.skeletons.splice(index, 1);
  19503. }
  19504. return index;
  19505. };
  19506. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19507. var index = this.morphTargetManagers.indexOf(toRemove);
  19508. if (index !== -1) {
  19509. // Remove from the scene if found
  19510. this.morphTargetManagers.splice(index, 1);
  19511. }
  19512. return index;
  19513. };
  19514. Scene.prototype.removeLight = function (toRemove) {
  19515. var index = this.lights.indexOf(toRemove);
  19516. if (index !== -1) {
  19517. // Remove from the scene if mesh found
  19518. this.lights.splice(index, 1);
  19519. this.sortLightsByPriority();
  19520. }
  19521. this.onLightRemovedObservable.notifyObservers(toRemove);
  19522. return index;
  19523. };
  19524. Scene.prototype.removeCamera = function (toRemove) {
  19525. var index = this.cameras.indexOf(toRemove);
  19526. if (index !== -1) {
  19527. // Remove from the scene if mesh found
  19528. this.cameras.splice(index, 1);
  19529. }
  19530. // Remove from activeCameras
  19531. var index2 = this.activeCameras.indexOf(toRemove);
  19532. if (index2 !== -1) {
  19533. // Remove from the scene if mesh found
  19534. this.activeCameras.splice(index2, 1);
  19535. }
  19536. // Reset the activeCamera
  19537. if (this.activeCamera === toRemove) {
  19538. if (this.cameras.length > 0) {
  19539. this.activeCamera = this.cameras[0];
  19540. }
  19541. else {
  19542. this.activeCamera = null;
  19543. }
  19544. }
  19545. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19546. return index;
  19547. };
  19548. Scene.prototype.addLight = function (newLight) {
  19549. this.lights.push(newLight);
  19550. this.sortLightsByPriority();
  19551. this.onNewLightAddedObservable.notifyObservers(newLight);
  19552. };
  19553. Scene.prototype.sortLightsByPriority = function () {
  19554. if (this.requireLightSorting) {
  19555. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19556. }
  19557. };
  19558. Scene.prototype.addCamera = function (newCamera) {
  19559. this.cameras.push(newCamera);
  19560. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19561. };
  19562. /**
  19563. * Switch active camera
  19564. * @param {Camera} newCamera - new active camera
  19565. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19566. */
  19567. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19568. if (attachControl === void 0) { attachControl = true; }
  19569. var canvas = this._engine.getRenderingCanvas();
  19570. if (!canvas) {
  19571. return;
  19572. }
  19573. if (this.activeCamera) {
  19574. this.activeCamera.detachControl(canvas);
  19575. }
  19576. this.activeCamera = newCamera;
  19577. if (attachControl) {
  19578. newCamera.attachControl(canvas);
  19579. }
  19580. };
  19581. /**
  19582. * sets the active camera of the scene using its ID
  19583. * @param {string} id - the camera's ID
  19584. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19585. * @see activeCamera
  19586. */
  19587. Scene.prototype.setActiveCameraByID = function (id) {
  19588. var camera = this.getCameraByID(id);
  19589. if (camera) {
  19590. this.activeCamera = camera;
  19591. return camera;
  19592. }
  19593. return null;
  19594. };
  19595. /**
  19596. * sets the active camera of the scene using its name
  19597. * @param {string} name - the camera's name
  19598. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19599. * @see activeCamera
  19600. */
  19601. Scene.prototype.setActiveCameraByName = function (name) {
  19602. var camera = this.getCameraByName(name);
  19603. if (camera) {
  19604. this.activeCamera = camera;
  19605. return camera;
  19606. }
  19607. return null;
  19608. };
  19609. /**
  19610. * get a material using its id
  19611. * @param {string} the material's ID
  19612. * @return {BABYLON.Material|null} the material or null if none found.
  19613. */
  19614. Scene.prototype.getMaterialByID = function (id) {
  19615. for (var index = 0; index < this.materials.length; index++) {
  19616. if (this.materials[index].id === id) {
  19617. return this.materials[index];
  19618. }
  19619. }
  19620. return null;
  19621. };
  19622. /**
  19623. * get a material using its name
  19624. * @param {string} the material's name
  19625. * @return {BABYLON.Material|null} the material or null if none found.
  19626. */
  19627. Scene.prototype.getMaterialByName = function (name) {
  19628. for (var index = 0; index < this.materials.length; index++) {
  19629. if (this.materials[index].name === name) {
  19630. return this.materials[index];
  19631. }
  19632. }
  19633. return null;
  19634. };
  19635. Scene.prototype.getLensFlareSystemByName = function (name) {
  19636. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19637. if (this.lensFlareSystems[index].name === name) {
  19638. return this.lensFlareSystems[index];
  19639. }
  19640. }
  19641. return null;
  19642. };
  19643. Scene.prototype.getLensFlareSystemByID = function (id) {
  19644. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19645. if (this.lensFlareSystems[index].id === id) {
  19646. return this.lensFlareSystems[index];
  19647. }
  19648. }
  19649. return null;
  19650. };
  19651. Scene.prototype.getCameraByID = function (id) {
  19652. for (var index = 0; index < this.cameras.length; index++) {
  19653. if (this.cameras[index].id === id) {
  19654. return this.cameras[index];
  19655. }
  19656. }
  19657. return null;
  19658. };
  19659. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19660. for (var index = 0; index < this.cameras.length; index++) {
  19661. if (this.cameras[index].uniqueId === uniqueId) {
  19662. return this.cameras[index];
  19663. }
  19664. }
  19665. return null;
  19666. };
  19667. /**
  19668. * get a camera using its name
  19669. * @param {string} the camera's name
  19670. * @return {BABYLON.Camera|null} the camera or null if none found.
  19671. */
  19672. Scene.prototype.getCameraByName = function (name) {
  19673. for (var index = 0; index < this.cameras.length; index++) {
  19674. if (this.cameras[index].name === name) {
  19675. return this.cameras[index];
  19676. }
  19677. }
  19678. return null;
  19679. };
  19680. /**
  19681. * get a bone using its id
  19682. * @param {string} the bone's id
  19683. * @return {BABYLON.Bone|null} the bone or null if not found
  19684. */
  19685. Scene.prototype.getBoneByID = function (id) {
  19686. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19687. var skeleton = this.skeletons[skeletonIndex];
  19688. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19689. if (skeleton.bones[boneIndex].id === id) {
  19690. return skeleton.bones[boneIndex];
  19691. }
  19692. }
  19693. }
  19694. return null;
  19695. };
  19696. /**
  19697. * get a bone using its id
  19698. * @param {string} the bone's name
  19699. * @return {BABYLON.Bone|null} the bone or null if not found
  19700. */
  19701. Scene.prototype.getBoneByName = function (name) {
  19702. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19703. var skeleton = this.skeletons[skeletonIndex];
  19704. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19705. if (skeleton.bones[boneIndex].name === name) {
  19706. return skeleton.bones[boneIndex];
  19707. }
  19708. }
  19709. }
  19710. return null;
  19711. };
  19712. /**
  19713. * get a light node using its name
  19714. * @param {string} the light's name
  19715. * @return {BABYLON.Light|null} the light or null if none found.
  19716. */
  19717. Scene.prototype.getLightByName = function (name) {
  19718. for (var index = 0; index < this.lights.length; index++) {
  19719. if (this.lights[index].name === name) {
  19720. return this.lights[index];
  19721. }
  19722. }
  19723. return null;
  19724. };
  19725. /**
  19726. * get a light node using its ID
  19727. * @param {string} the light's id
  19728. * @return {BABYLON.Light|null} the light or null if none found.
  19729. */
  19730. Scene.prototype.getLightByID = function (id) {
  19731. for (var index = 0; index < this.lights.length; index++) {
  19732. if (this.lights[index].id === id) {
  19733. return this.lights[index];
  19734. }
  19735. }
  19736. return null;
  19737. };
  19738. /**
  19739. * get a light node using its scene-generated unique ID
  19740. * @param {number} the light's unique id
  19741. * @return {BABYLON.Light|null} the light or null if none found.
  19742. */
  19743. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19744. for (var index = 0; index < this.lights.length; index++) {
  19745. if (this.lights[index].uniqueId === uniqueId) {
  19746. return this.lights[index];
  19747. }
  19748. }
  19749. return null;
  19750. };
  19751. /**
  19752. * get a particle system by id
  19753. * @param id {number} the particle system id
  19754. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19755. */
  19756. Scene.prototype.getParticleSystemByID = function (id) {
  19757. for (var index = 0; index < this.particleSystems.length; index++) {
  19758. if (this.particleSystems[index].id === id) {
  19759. return this.particleSystems[index];
  19760. }
  19761. }
  19762. return null;
  19763. };
  19764. /**
  19765. * get a geometry using its ID
  19766. * @param {string} the geometry's id
  19767. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19768. */
  19769. Scene.prototype.getGeometryByID = function (id) {
  19770. for (var index = 0; index < this._geometries.length; index++) {
  19771. if (this._geometries[index].id === id) {
  19772. return this._geometries[index];
  19773. }
  19774. }
  19775. return null;
  19776. };
  19777. /**
  19778. * add a new geometry to this scene.
  19779. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19780. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19781. * @return {boolean} was the geometry added or not
  19782. */
  19783. Scene.prototype.pushGeometry = function (geometry, force) {
  19784. if (!force && this.getGeometryByID(geometry.id)) {
  19785. return false;
  19786. }
  19787. this._geometries.push(geometry);
  19788. //notify the collision coordinator
  19789. if (this.collisionCoordinator) {
  19790. this.collisionCoordinator.onGeometryAdded(geometry);
  19791. }
  19792. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19793. return true;
  19794. };
  19795. /**
  19796. * Removes an existing geometry
  19797. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19798. * @return {boolean} was the geometry removed or not
  19799. */
  19800. Scene.prototype.removeGeometry = function (geometry) {
  19801. var index = this._geometries.indexOf(geometry);
  19802. if (index > -1) {
  19803. this._geometries.splice(index, 1);
  19804. //notify the collision coordinator
  19805. if (this.collisionCoordinator) {
  19806. this.collisionCoordinator.onGeometryDeleted(geometry);
  19807. }
  19808. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19809. return true;
  19810. }
  19811. return false;
  19812. };
  19813. Scene.prototype.getGeometries = function () {
  19814. return this._geometries;
  19815. };
  19816. /**
  19817. * Get the first added mesh found of a given ID
  19818. * @param {string} id - the id to search for
  19819. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19820. */
  19821. Scene.prototype.getMeshByID = function (id) {
  19822. for (var index = 0; index < this.meshes.length; index++) {
  19823. if (this.meshes[index].id === id) {
  19824. return this.meshes[index];
  19825. }
  19826. }
  19827. return null;
  19828. };
  19829. Scene.prototype.getMeshesByID = function (id) {
  19830. return this.meshes.filter(function (m) {
  19831. return m.id === id;
  19832. });
  19833. };
  19834. /**
  19835. * Get the first added transform node found of a given ID
  19836. * @param {string} id - the id to search for
  19837. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  19838. */
  19839. Scene.prototype.getTransformNodeByID = function (id) {
  19840. for (var index = 0; index < this.transformNodes.length; index++) {
  19841. if (this.transformNodes[index].id === id) {
  19842. return this.transformNodes[index];
  19843. }
  19844. }
  19845. return null;
  19846. };
  19847. Scene.prototype.getTransformNodesByID = function (id) {
  19848. return this.transformNodes.filter(function (m) {
  19849. return m.id === id;
  19850. });
  19851. };
  19852. /**
  19853. * Get a mesh with its auto-generated unique id
  19854. * @param {number} uniqueId - the unique id to search for
  19855. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19856. */
  19857. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19858. for (var index = 0; index < this.meshes.length; index++) {
  19859. if (this.meshes[index].uniqueId === uniqueId) {
  19860. return this.meshes[index];
  19861. }
  19862. }
  19863. return null;
  19864. };
  19865. /**
  19866. * Get a the last added mesh found of a given ID
  19867. * @param {string} id - the id to search for
  19868. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19869. */
  19870. Scene.prototype.getLastMeshByID = function (id) {
  19871. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19872. if (this.meshes[index].id === id) {
  19873. return this.meshes[index];
  19874. }
  19875. }
  19876. return null;
  19877. };
  19878. /**
  19879. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19880. * @param {string} id - the id to search for
  19881. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19882. */
  19883. Scene.prototype.getLastEntryByID = function (id) {
  19884. var index;
  19885. for (index = this.meshes.length - 1; index >= 0; index--) {
  19886. if (this.meshes[index].id === id) {
  19887. return this.meshes[index];
  19888. }
  19889. }
  19890. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  19891. if (this.transformNodes[index].id === id) {
  19892. return this.transformNodes[index];
  19893. }
  19894. }
  19895. for (index = this.cameras.length - 1; index >= 0; index--) {
  19896. if (this.cameras[index].id === id) {
  19897. return this.cameras[index];
  19898. }
  19899. }
  19900. for (index = this.lights.length - 1; index >= 0; index--) {
  19901. if (this.lights[index].id === id) {
  19902. return this.lights[index];
  19903. }
  19904. }
  19905. return null;
  19906. };
  19907. Scene.prototype.getNodeByID = function (id) {
  19908. var mesh = this.getMeshByID(id);
  19909. if (mesh) {
  19910. return mesh;
  19911. }
  19912. var light = this.getLightByID(id);
  19913. if (light) {
  19914. return light;
  19915. }
  19916. var camera = this.getCameraByID(id);
  19917. if (camera) {
  19918. return camera;
  19919. }
  19920. var bone = this.getBoneByID(id);
  19921. return bone;
  19922. };
  19923. Scene.prototype.getNodeByName = function (name) {
  19924. var mesh = this.getMeshByName(name);
  19925. if (mesh) {
  19926. return mesh;
  19927. }
  19928. var light = this.getLightByName(name);
  19929. if (light) {
  19930. return light;
  19931. }
  19932. var camera = this.getCameraByName(name);
  19933. if (camera) {
  19934. return camera;
  19935. }
  19936. var bone = this.getBoneByName(name);
  19937. return bone;
  19938. };
  19939. Scene.prototype.getMeshByName = function (name) {
  19940. for (var index = 0; index < this.meshes.length; index++) {
  19941. if (this.meshes[index].name === name) {
  19942. return this.meshes[index];
  19943. }
  19944. }
  19945. return null;
  19946. };
  19947. Scene.prototype.getTransformNodeByName = function (name) {
  19948. for (var index = 0; index < this.transformNodes.length; index++) {
  19949. if (this.transformNodes[index].name === name) {
  19950. return this.transformNodes[index];
  19951. }
  19952. }
  19953. return null;
  19954. };
  19955. Scene.prototype.getSoundByName = function (name) {
  19956. var index;
  19957. if (BABYLON.AudioEngine) {
  19958. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19959. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19960. return this.mainSoundTrack.soundCollection[index];
  19961. }
  19962. }
  19963. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19964. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19965. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19966. return this.soundTracks[sdIndex].soundCollection[index];
  19967. }
  19968. }
  19969. }
  19970. }
  19971. return null;
  19972. };
  19973. Scene.prototype.getLastSkeletonByID = function (id) {
  19974. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  19975. if (this.skeletons[index].id === id) {
  19976. return this.skeletons[index];
  19977. }
  19978. }
  19979. return null;
  19980. };
  19981. Scene.prototype.getSkeletonById = function (id) {
  19982. for (var index = 0; index < this.skeletons.length; index++) {
  19983. if (this.skeletons[index].id === id) {
  19984. return this.skeletons[index];
  19985. }
  19986. }
  19987. return null;
  19988. };
  19989. Scene.prototype.getSkeletonByName = function (name) {
  19990. for (var index = 0; index < this.skeletons.length; index++) {
  19991. if (this.skeletons[index].name === name) {
  19992. return this.skeletons[index];
  19993. }
  19994. }
  19995. return null;
  19996. };
  19997. Scene.prototype.getMorphTargetManagerById = function (id) {
  19998. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  19999. if (this.morphTargetManagers[index].uniqueId === id) {
  20000. return this.morphTargetManagers[index];
  20001. }
  20002. }
  20003. return null;
  20004. };
  20005. Scene.prototype.isActiveMesh = function (mesh) {
  20006. return (this._activeMeshes.indexOf(mesh) !== -1);
  20007. };
  20008. /**
  20009. * Return a the first highlight layer of the scene with a given name.
  20010. * @param name The name of the highlight layer to look for.
  20011. * @return The highlight layer if found otherwise null.
  20012. */
  20013. Scene.prototype.getHighlightLayerByName = function (name) {
  20014. for (var index = 0; index < this.highlightLayers.length; index++) {
  20015. if (this.highlightLayers[index].name === name) {
  20016. return this.highlightLayers[index];
  20017. }
  20018. }
  20019. return null;
  20020. };
  20021. Object.defineProperty(Scene.prototype, "uid", {
  20022. /**
  20023. * Return a unique id as a string which can serve as an identifier for the scene
  20024. */
  20025. get: function () {
  20026. if (!this._uid) {
  20027. this._uid = BABYLON.Tools.RandomId();
  20028. }
  20029. return this._uid;
  20030. },
  20031. enumerable: true,
  20032. configurable: true
  20033. });
  20034. /**
  20035. * Add an externaly attached data from its key.
  20036. * This method call will fail and return false, if such key already exists.
  20037. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20038. * @param key the unique key that identifies the data
  20039. * @param data the data object to associate to the key for this Engine instance
  20040. * @return true if no such key were already present and the data was added successfully, false otherwise
  20041. */
  20042. Scene.prototype.addExternalData = function (key, data) {
  20043. if (!this._externalData) {
  20044. this._externalData = new BABYLON.StringDictionary();
  20045. }
  20046. return this._externalData.add(key, data);
  20047. };
  20048. /**
  20049. * Get an externaly attached data from its key
  20050. * @param key the unique key that identifies the data
  20051. * @return the associated data, if present (can be null), or undefined if not present
  20052. */
  20053. Scene.prototype.getExternalData = function (key) {
  20054. if (!this._externalData) {
  20055. return null;
  20056. }
  20057. return this._externalData.get(key);
  20058. };
  20059. /**
  20060. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20061. * @param key the unique key that identifies the data
  20062. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20063. * @return the associated data, can be null if the factory returned null.
  20064. */
  20065. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20066. if (!this._externalData) {
  20067. this._externalData = new BABYLON.StringDictionary();
  20068. }
  20069. return this._externalData.getOrAddWithFactory(key, factory);
  20070. };
  20071. /**
  20072. * Remove an externaly attached data from the Engine instance
  20073. * @param key the unique key that identifies the data
  20074. * @return true if the data was successfully removed, false if it doesn't exist
  20075. */
  20076. Scene.prototype.removeExternalData = function (key) {
  20077. return this._externalData.remove(key);
  20078. };
  20079. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20080. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20081. var material = subMesh.getMaterial();
  20082. if (mesh.showSubMeshesBoundingBox) {
  20083. var boundingInfo = subMesh.getBoundingInfo();
  20084. if (boundingInfo) {
  20085. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20086. }
  20087. }
  20088. if (material) {
  20089. // Render targets
  20090. if (material.getRenderTargetTextures) {
  20091. if (this._processedMaterials.indexOf(material) === -1) {
  20092. this._processedMaterials.push(material);
  20093. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20094. }
  20095. }
  20096. // Dispatch
  20097. this._activeIndices.addCount(subMesh.indexCount, false);
  20098. this._renderingManager.dispatch(subMesh);
  20099. }
  20100. }
  20101. };
  20102. Scene.prototype._isInIntermediateRendering = function () {
  20103. return this._intermediateRendering;
  20104. };
  20105. /**
  20106. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  20107. */
  20108. Scene.prototype.freezeActiveMeshes = function () {
  20109. this._evaluateActiveMeshes();
  20110. this._activeMeshesFrozen = true;
  20111. return this;
  20112. };
  20113. /**
  20114. * Use this function to restart evaluating active meshes on every frame
  20115. */
  20116. Scene.prototype.unfreezeActiveMeshes = function () {
  20117. this._activeMeshesFrozen = false;
  20118. return this;
  20119. };
  20120. Scene.prototype._evaluateActiveMeshes = function () {
  20121. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  20122. return;
  20123. }
  20124. if (!this.activeCamera) {
  20125. return;
  20126. }
  20127. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  20128. this.activeCamera._activeMeshes.reset();
  20129. this._activeMeshes.reset();
  20130. this._renderingManager.reset();
  20131. this._processedMaterials.reset();
  20132. this._activeParticleSystems.reset();
  20133. this._activeSkeletons.reset();
  20134. this._softwareSkinnedMeshes.reset();
  20135. if (this._boundingBoxRenderer) {
  20136. this._boundingBoxRenderer.reset();
  20137. }
  20138. // Meshes
  20139. var meshes;
  20140. var len;
  20141. if (this._selectionOctree) {
  20142. var selection = this._selectionOctree.select(this._frustumPlanes);
  20143. meshes = selection.data;
  20144. len = selection.length;
  20145. }
  20146. else {
  20147. len = this.meshes.length;
  20148. meshes = this.meshes;
  20149. }
  20150. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  20151. var mesh = meshes[meshIndex];
  20152. if (mesh.isBlocked) {
  20153. continue;
  20154. }
  20155. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20156. if (!mesh.isReady() || !mesh.isEnabled()) {
  20157. continue;
  20158. }
  20159. mesh.computeWorldMatrix();
  20160. // Intersections
  20161. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20162. this._meshesForIntersections.pushNoDuplicate(mesh);
  20163. }
  20164. // Switch to current LOD
  20165. var meshLOD = mesh.getLOD(this.activeCamera);
  20166. if (!meshLOD) {
  20167. continue;
  20168. }
  20169. mesh._preActivate();
  20170. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20171. this._activeMeshes.push(mesh);
  20172. this.activeCamera._activeMeshes.push(mesh);
  20173. mesh._activate(this._renderId);
  20174. if (meshLOD !== mesh) {
  20175. meshLOD._activate(this._renderId);
  20176. }
  20177. this._activeMesh(mesh, meshLOD);
  20178. }
  20179. }
  20180. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  20181. // Particle systems
  20182. if (this.particlesEnabled) {
  20183. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  20184. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20185. var particleSystem = this.particleSystems[particleIndex];
  20186. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  20187. continue;
  20188. }
  20189. var emitter = particleSystem.emitter;
  20190. if (!emitter.position || emitter.isEnabled()) {
  20191. this._activeParticleSystems.push(particleSystem);
  20192. particleSystem.animate();
  20193. this._renderingManager.dispatchParticles(particleSystem);
  20194. }
  20195. }
  20196. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  20197. }
  20198. };
  20199. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20200. if (mesh.skeleton && this.skeletonsEnabled) {
  20201. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20202. mesh.skeleton.prepare();
  20203. }
  20204. if (!mesh.computeBonesUsingShaders) {
  20205. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20206. }
  20207. }
  20208. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  20209. var boundingInfo = sourceMesh.getBoundingInfo();
  20210. if (boundingInfo) {
  20211. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20212. }
  20213. }
  20214. if (mesh && mesh.subMeshes) {
  20215. // Submeshes Octrees
  20216. var len;
  20217. var subMeshes;
  20218. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  20219. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20220. len = intersections.length;
  20221. subMeshes = intersections.data;
  20222. }
  20223. else {
  20224. subMeshes = mesh.subMeshes;
  20225. len = subMeshes.length;
  20226. }
  20227. for (var subIndex = 0; subIndex < len; subIndex++) {
  20228. var subMesh = subMeshes[subIndex];
  20229. this._evaluateSubMesh(subMesh, mesh);
  20230. }
  20231. }
  20232. };
  20233. Scene.prototype.updateTransformMatrix = function (force) {
  20234. if (!this.activeCamera) {
  20235. return;
  20236. }
  20237. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20238. };
  20239. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  20240. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  20241. };
  20242. Scene.prototype._renderForCamera = function (camera) {
  20243. if (camera && camera._skipRendering) {
  20244. return;
  20245. }
  20246. var engine = this._engine;
  20247. this.activeCamera = camera;
  20248. if (!this.activeCamera)
  20249. throw new Error("Active camera not set");
  20250. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20251. // Viewport
  20252. engine.setViewport(this.activeCamera.viewport);
  20253. // Camera
  20254. this.resetCachedMaterial();
  20255. this._renderId++;
  20256. this.activeCamera.update();
  20257. this.updateTransformMatrix();
  20258. if (camera._alternateCamera) {
  20259. this.updateAlternateTransformMatrix(camera._alternateCamera);
  20260. this._alternateRendering = true;
  20261. }
  20262. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20263. // Meshes
  20264. this._evaluateActiveMeshes();
  20265. // Software skinning
  20266. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20267. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20268. mesh.applySkeleton(mesh.skeleton);
  20269. }
  20270. // Render targets
  20271. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20272. var needsRestoreFrameBuffer = false;
  20273. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  20274. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  20275. }
  20276. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20277. this._intermediateRendering = true;
  20278. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20279. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20280. var renderTarget = this._renderTargets.data[renderIndex];
  20281. if (renderTarget._shouldRender()) {
  20282. this._renderId++;
  20283. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20284. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20285. }
  20286. }
  20287. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20288. this._intermediateRendering = false;
  20289. this._renderId++;
  20290. needsRestoreFrameBuffer = true; // Restore back buffer
  20291. }
  20292. // Render HighlightLayer Texture
  20293. var stencilState = this._engine.getStencilBuffer();
  20294. var renderhighlights = false;
  20295. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20296. this._intermediateRendering = true;
  20297. for (var i = 0; i < this.highlightLayers.length; i++) {
  20298. var highlightLayer = this.highlightLayers[i];
  20299. if (highlightLayer.shouldRender() &&
  20300. (!highlightLayer.camera ||
  20301. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20302. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20303. renderhighlights = true;
  20304. var renderTarget = highlightLayer._mainTexture;
  20305. if (renderTarget._shouldRender()) {
  20306. this._renderId++;
  20307. renderTarget.render(false, false);
  20308. needsRestoreFrameBuffer = true;
  20309. }
  20310. }
  20311. }
  20312. this._intermediateRendering = false;
  20313. this._renderId++;
  20314. }
  20315. if (needsRestoreFrameBuffer) {
  20316. engine.restoreDefaultFramebuffer(); // Restore back buffer
  20317. }
  20318. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20319. // Prepare Frame
  20320. this.postProcessManager._prepareFrame();
  20321. // Backgrounds
  20322. var layerIndex;
  20323. var layer;
  20324. if (this.layers.length) {
  20325. engine.setDepthBuffer(false);
  20326. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20327. layer = this.layers[layerIndex];
  20328. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20329. layer.render();
  20330. }
  20331. }
  20332. engine.setDepthBuffer(true);
  20333. }
  20334. // Activate HighlightLayer stencil
  20335. if (renderhighlights) {
  20336. this._engine.setStencilBuffer(true);
  20337. }
  20338. // Render
  20339. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  20340. this._renderingManager.render(null, null, true, true);
  20341. this.onAfterDrawPhaseObservable.notifyObservers(this);
  20342. // Restore HighlightLayer stencil
  20343. if (renderhighlights) {
  20344. this._engine.setStencilBuffer(stencilState);
  20345. }
  20346. // Bounding boxes
  20347. if (this._boundingBoxRenderer) {
  20348. this._boundingBoxRenderer.render();
  20349. }
  20350. // Lens flares
  20351. if (this.lensFlaresEnabled) {
  20352. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20353. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20354. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20355. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20356. lensFlareSystem.render();
  20357. }
  20358. }
  20359. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20360. }
  20361. // Foregrounds
  20362. if (this.layers.length) {
  20363. engine.setDepthBuffer(false);
  20364. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20365. layer = this.layers[layerIndex];
  20366. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20367. layer.render();
  20368. }
  20369. }
  20370. engine.setDepthBuffer(true);
  20371. }
  20372. // Highlight Layer
  20373. if (renderhighlights) {
  20374. engine.setDepthBuffer(false);
  20375. for (var i = 0; i < this.highlightLayers.length; i++) {
  20376. if (this.highlightLayers[i].shouldRender()) {
  20377. this.highlightLayers[i].render();
  20378. }
  20379. }
  20380. engine.setDepthBuffer(true);
  20381. }
  20382. // Finalize frame
  20383. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  20384. // Reset some special arrays
  20385. this._renderTargets.reset();
  20386. this._alternateRendering = false;
  20387. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  20388. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20389. };
  20390. Scene.prototype._processSubCameras = function (camera) {
  20391. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  20392. this._renderForCamera(camera);
  20393. return;
  20394. }
  20395. // Update camera
  20396. if (this.activeCamera) {
  20397. this.activeCamera.update();
  20398. }
  20399. // rig cameras
  20400. for (var index = 0; index < camera._rigCameras.length; index++) {
  20401. this._renderForCamera(camera._rigCameras[index]);
  20402. }
  20403. this.activeCamera = camera;
  20404. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  20405. };
  20406. Scene.prototype._checkIntersections = function () {
  20407. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  20408. var sourceMesh = this._meshesForIntersections.data[index];
  20409. if (!sourceMesh.actionManager) {
  20410. continue;
  20411. }
  20412. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  20413. var action = sourceMesh.actionManager.actions[actionIndex];
  20414. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20415. var parameters = action.getTriggerParameter();
  20416. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  20417. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  20418. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  20419. if (areIntersecting && currentIntersectionInProgress === -1) {
  20420. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  20421. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20422. sourceMesh._intersectionsInProgress.push(otherMesh);
  20423. }
  20424. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20425. sourceMesh._intersectionsInProgress.push(otherMesh);
  20426. }
  20427. }
  20428. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20429. //They intersected, and now they don't.
  20430. //is this trigger an exit trigger? execute an event.
  20431. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20432. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20433. }
  20434. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20435. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20436. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20437. }
  20438. }
  20439. }
  20440. }
  20441. }
  20442. };
  20443. Scene.prototype.render = function () {
  20444. if (this.isDisposed) {
  20445. return;
  20446. }
  20447. this._activeParticles.fetchNewFrame();
  20448. this._totalVertices.fetchNewFrame();
  20449. this._activeIndices.fetchNewFrame();
  20450. this._activeBones.fetchNewFrame();
  20451. this._meshesForIntersections.reset();
  20452. this.resetCachedMaterial();
  20453. this.onBeforeAnimationsObservable.notifyObservers(this);
  20454. // Actions
  20455. if (this.actionManager) {
  20456. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20457. }
  20458. //Simplification Queue
  20459. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20460. this.simplificationQueue.executeNext();
  20461. }
  20462. if (this._engine.isDeterministicLockStep()) {
  20463. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  20464. var defaultTimeStep = (60.0 / 1000.0);
  20465. if (this._physicsEngine) {
  20466. defaultTimeStep = this._physicsEngine.getTimeStep();
  20467. }
  20468. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20469. this._timeAccumulator += deltaTime;
  20470. // compute the amount of fixed steps we should have taken since the last step
  20471. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  20472. internalSteps = Math.min(internalSteps, maxSubSteps);
  20473. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  20474. this.onBeforeStepObservable.notifyObservers(this);
  20475. // Animations
  20476. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  20477. this._animate();
  20478. this.onAfterAnimationsObservable.notifyObservers(this);
  20479. // Physics
  20480. if (this._physicsEngine) {
  20481. this.onBeforePhysicsObservable.notifyObservers(this);
  20482. this._physicsEngine._step(defaultTimeStep);
  20483. this.onAfterPhysicsObservable.notifyObservers(this);
  20484. }
  20485. this._timeAccumulator -= defaultTimeStep;
  20486. this.onAfterStepObservable.notifyObservers(this);
  20487. this._currentStepId++;
  20488. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  20489. this._evaluateActiveMeshes();
  20490. }
  20491. }
  20492. }
  20493. else {
  20494. // Animations
  20495. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20496. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20497. this._animate();
  20498. this.onAfterAnimationsObservable.notifyObservers(this);
  20499. // Physics
  20500. if (this._physicsEngine) {
  20501. this.onBeforePhysicsObservable.notifyObservers(this);
  20502. this._physicsEngine._step(deltaTime / 1000.0);
  20503. this.onAfterPhysicsObservable.notifyObservers(this);
  20504. }
  20505. }
  20506. // Before render
  20507. this.onBeforeRenderObservable.notifyObservers(this);
  20508. // Customs render targets
  20509. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20510. var engine = this.getEngine();
  20511. var currentActiveCamera = this.activeCamera;
  20512. if (this.renderTargetsEnabled) {
  20513. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20514. this._intermediateRendering = true;
  20515. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20516. var renderTarget = this.customRenderTargets[customIndex];
  20517. if (renderTarget._shouldRender()) {
  20518. this._renderId++;
  20519. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20520. if (!this.activeCamera)
  20521. throw new Error("Active camera not set");
  20522. // Viewport
  20523. engine.setViewport(this.activeCamera.viewport);
  20524. // Camera
  20525. this.updateTransformMatrix();
  20526. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20527. }
  20528. }
  20529. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20530. this._intermediateRendering = false;
  20531. this._renderId++;
  20532. }
  20533. // Restore back buffer
  20534. if (this.customRenderTargets.length > 0) {
  20535. engine.restoreDefaultFramebuffer();
  20536. }
  20537. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20538. this.activeCamera = currentActiveCamera;
  20539. // Procedural textures
  20540. if (this.proceduralTexturesEnabled) {
  20541. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20542. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20543. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20544. if (proceduralTexture._shouldRender()) {
  20545. proceduralTexture.render();
  20546. }
  20547. }
  20548. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20549. }
  20550. // Clear
  20551. if (this.autoClearDepthAndStencil || this.autoClear) {
  20552. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20553. }
  20554. // Shadows
  20555. if (this.shadowsEnabled) {
  20556. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20557. var light = this.lights[lightIndex];
  20558. var shadowGenerator = light.getShadowGenerator();
  20559. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20560. var shadowMap = (shadowGenerator.getShadowMap());
  20561. if (this.textures.indexOf(shadowMap) !== -1) {
  20562. this._renderTargets.push(shadowMap);
  20563. }
  20564. }
  20565. }
  20566. }
  20567. // Depth renderer
  20568. if (this._depthRenderer) {
  20569. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20570. }
  20571. // Geometry renderer
  20572. if (this._geometryBufferRenderer) {
  20573. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20574. }
  20575. // RenderPipeline
  20576. if (this._postProcessRenderPipelineManager) {
  20577. this._postProcessRenderPipelineManager.update();
  20578. }
  20579. // Multi-cameras?
  20580. if (this.activeCameras.length > 0) {
  20581. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20582. if (cameraIndex > 0) {
  20583. this._engine.clear(null, false, true, true);
  20584. }
  20585. this._processSubCameras(this.activeCameras[cameraIndex]);
  20586. }
  20587. }
  20588. else {
  20589. if (!this.activeCamera) {
  20590. throw new Error("No camera defined");
  20591. }
  20592. this._processSubCameras(this.activeCamera);
  20593. }
  20594. // Intersection checks
  20595. this._checkIntersections();
  20596. // Update the audio listener attached to the camera
  20597. if (BABYLON.AudioEngine) {
  20598. this._updateAudioParameters();
  20599. }
  20600. // After render
  20601. if (this.afterRender) {
  20602. this.afterRender();
  20603. }
  20604. this.onAfterRenderObservable.notifyObservers(this);
  20605. // Cleaning
  20606. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20607. var data = this._toBeDisposed.data[index];
  20608. if (data) {
  20609. data.dispose();
  20610. }
  20611. this._toBeDisposed[index] = null;
  20612. }
  20613. this._toBeDisposed.reset();
  20614. if (this.dumpNextRenderTargets) {
  20615. this.dumpNextRenderTargets = false;
  20616. }
  20617. this._activeBones.addCount(0, true);
  20618. this._activeIndices.addCount(0, true);
  20619. this._activeParticles.addCount(0, true);
  20620. };
  20621. Scene.prototype._updateAudioParameters = function () {
  20622. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20623. return;
  20624. }
  20625. var listeningCamera;
  20626. var audioEngine = BABYLON.Engine.audioEngine;
  20627. if (this.activeCameras.length > 0) {
  20628. listeningCamera = this.activeCameras[0];
  20629. }
  20630. else {
  20631. listeningCamera = this.activeCamera;
  20632. }
  20633. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20634. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20635. // for VR cameras
  20636. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20637. listeningCamera = listeningCamera.rigCameras[0];
  20638. }
  20639. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20640. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20641. cameraDirection.normalize();
  20642. // To avoid some errors on GearVR
  20643. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20644. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20645. }
  20646. var i;
  20647. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20648. var sound = this.mainSoundTrack.soundCollection[i];
  20649. if (sound.useCustomAttenuation) {
  20650. sound.updateDistanceFromListener();
  20651. }
  20652. }
  20653. for (i = 0; i < this.soundTracks.length; i++) {
  20654. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20655. sound = this.soundTracks[i].soundCollection[j];
  20656. if (sound.useCustomAttenuation) {
  20657. sound.updateDistanceFromListener();
  20658. }
  20659. }
  20660. }
  20661. }
  20662. };
  20663. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20664. // Audio
  20665. get: function () {
  20666. return this._audioEnabled;
  20667. },
  20668. set: function (value) {
  20669. this._audioEnabled = value;
  20670. if (BABYLON.AudioEngine) {
  20671. if (this._audioEnabled) {
  20672. this._enableAudio();
  20673. }
  20674. else {
  20675. this._disableAudio();
  20676. }
  20677. }
  20678. },
  20679. enumerable: true,
  20680. configurable: true
  20681. });
  20682. Scene.prototype._disableAudio = function () {
  20683. var i;
  20684. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20685. this.mainSoundTrack.soundCollection[i].pause();
  20686. }
  20687. for (i = 0; i < this.soundTracks.length; i++) {
  20688. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20689. this.soundTracks[i].soundCollection[j].pause();
  20690. }
  20691. }
  20692. };
  20693. Scene.prototype._enableAudio = function () {
  20694. var i;
  20695. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20696. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20697. this.mainSoundTrack.soundCollection[i].play();
  20698. }
  20699. }
  20700. for (i = 0; i < this.soundTracks.length; i++) {
  20701. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20702. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20703. this.soundTracks[i].soundCollection[j].play();
  20704. }
  20705. }
  20706. }
  20707. };
  20708. Object.defineProperty(Scene.prototype, "headphone", {
  20709. get: function () {
  20710. return this._headphone;
  20711. },
  20712. set: function (value) {
  20713. this._headphone = value;
  20714. if (BABYLON.AudioEngine) {
  20715. if (this._headphone) {
  20716. this._switchAudioModeForHeadphones();
  20717. }
  20718. else {
  20719. this._switchAudioModeForNormalSpeakers();
  20720. }
  20721. }
  20722. },
  20723. enumerable: true,
  20724. configurable: true
  20725. });
  20726. Scene.prototype._switchAudioModeForHeadphones = function () {
  20727. this.mainSoundTrack.switchPanningModelToHRTF();
  20728. for (var i = 0; i < this.soundTracks.length; i++) {
  20729. this.soundTracks[i].switchPanningModelToHRTF();
  20730. }
  20731. };
  20732. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20733. this.mainSoundTrack.switchPanningModelToEqualPower();
  20734. for (var i = 0; i < this.soundTracks.length; i++) {
  20735. this.soundTracks[i].switchPanningModelToEqualPower();
  20736. }
  20737. };
  20738. Scene.prototype.enableDepthRenderer = function () {
  20739. if (this._depthRenderer) {
  20740. return this._depthRenderer;
  20741. }
  20742. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20743. return this._depthRenderer;
  20744. };
  20745. Scene.prototype.disableDepthRenderer = function () {
  20746. if (!this._depthRenderer) {
  20747. return;
  20748. }
  20749. this._depthRenderer.dispose();
  20750. this._depthRenderer = null;
  20751. };
  20752. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20753. if (ratio === void 0) { ratio = 1; }
  20754. if (this._geometryBufferRenderer) {
  20755. return this._geometryBufferRenderer;
  20756. }
  20757. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20758. if (!this._geometryBufferRenderer.isSupported) {
  20759. this._geometryBufferRenderer = null;
  20760. }
  20761. return this._geometryBufferRenderer;
  20762. };
  20763. Scene.prototype.disableGeometryBufferRenderer = function () {
  20764. if (!this._geometryBufferRenderer) {
  20765. return;
  20766. }
  20767. this._geometryBufferRenderer.dispose();
  20768. this._geometryBufferRenderer = null;
  20769. };
  20770. Scene.prototype.freezeMaterials = function () {
  20771. for (var i = 0; i < this.materials.length; i++) {
  20772. this.materials[i].freeze();
  20773. }
  20774. };
  20775. Scene.prototype.unfreezeMaterials = function () {
  20776. for (var i = 0; i < this.materials.length; i++) {
  20777. this.materials[i].unfreeze();
  20778. }
  20779. };
  20780. Scene.prototype.dispose = function () {
  20781. this.beforeRender = null;
  20782. this.afterRender = null;
  20783. this.skeletons = [];
  20784. this.morphTargetManagers = [];
  20785. this.importedMeshesFiles = new Array();
  20786. this.stopAllAnimations();
  20787. this.resetCachedMaterial();
  20788. if (this._depthRenderer) {
  20789. this._depthRenderer.dispose();
  20790. }
  20791. if (this._gamepadManager) {
  20792. this._gamepadManager.dispose();
  20793. this._gamepadManager = null;
  20794. }
  20795. // Smart arrays
  20796. if (this.activeCamera) {
  20797. this.activeCamera._activeMeshes.dispose();
  20798. this.activeCamera = null;
  20799. }
  20800. this._activeMeshes.dispose();
  20801. this._renderingManager.dispose();
  20802. this._processedMaterials.dispose();
  20803. this._activeParticleSystems.dispose();
  20804. this._activeSkeletons.dispose();
  20805. this._softwareSkinnedMeshes.dispose();
  20806. this._renderTargets.dispose();
  20807. if (this._boundingBoxRenderer) {
  20808. this._boundingBoxRenderer.dispose();
  20809. }
  20810. this._meshesForIntersections.dispose();
  20811. this._toBeDisposed.dispose();
  20812. // Debug layer
  20813. if (this._debugLayer) {
  20814. this._debugLayer.hide();
  20815. }
  20816. // Events
  20817. this.onDisposeObservable.notifyObservers(this);
  20818. this.onDisposeObservable.clear();
  20819. this.onBeforeRenderObservable.clear();
  20820. this.onAfterRenderObservable.clear();
  20821. this.OnBeforeRenderTargetsRenderObservable.clear();
  20822. this.OnAfterRenderTargetsRenderObservable.clear();
  20823. this.onAfterStepObservable.clear();
  20824. this.onBeforeStepObservable.clear();
  20825. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20826. this.onAfterActiveMeshesEvaluationObservable.clear();
  20827. this.onBeforeParticlesRenderingObservable.clear();
  20828. this.onAfterParticlesRenderingObservable.clear();
  20829. this.onBeforeSpritesRenderingObservable.clear();
  20830. this.onAfterSpritesRenderingObservable.clear();
  20831. this.onBeforeDrawPhaseObservable.clear();
  20832. this.onAfterDrawPhaseObservable.clear();
  20833. this.onBeforePhysicsObservable.clear();
  20834. this.onAfterPhysicsObservable.clear();
  20835. this.onBeforeAnimationsObservable.clear();
  20836. this.onAfterAnimationsObservable.clear();
  20837. this.onDataLoadedObservable.clear();
  20838. this.detachControl();
  20839. // Release sounds & sounds tracks
  20840. if (BABYLON.AudioEngine) {
  20841. this.disposeSounds();
  20842. }
  20843. // VR Helper
  20844. if (this.VRHelper) {
  20845. this.VRHelper.dispose();
  20846. }
  20847. // Detach cameras
  20848. var canvas = this._engine.getRenderingCanvas();
  20849. if (canvas) {
  20850. var index;
  20851. for (index = 0; index < this.cameras.length; index++) {
  20852. this.cameras[index].detachControl(canvas);
  20853. }
  20854. }
  20855. // Release lights
  20856. while (this.lights.length) {
  20857. this.lights[0].dispose();
  20858. }
  20859. // Release meshes
  20860. while (this.meshes.length) {
  20861. this.meshes[0].dispose(true);
  20862. }
  20863. while (this.transformNodes.length) {
  20864. this.removeTransformNode(this.transformNodes[0]);
  20865. }
  20866. // Release cameras
  20867. while (this.cameras.length) {
  20868. this.cameras[0].dispose();
  20869. }
  20870. // Release materials
  20871. if (this.defaultMaterial) {
  20872. this.defaultMaterial.dispose();
  20873. }
  20874. while (this.multiMaterials.length) {
  20875. this.multiMaterials[0].dispose();
  20876. }
  20877. while (this.materials.length) {
  20878. this.materials[0].dispose();
  20879. }
  20880. // Release particles
  20881. while (this.particleSystems.length) {
  20882. this.particleSystems[0].dispose();
  20883. }
  20884. // Release sprites
  20885. while (this.spriteManagers.length) {
  20886. this.spriteManagers[0].dispose();
  20887. }
  20888. // Release postProcesses
  20889. while (this.postProcesses.length) {
  20890. this.postProcesses[0].dispose();
  20891. }
  20892. // Release layers
  20893. while (this.layers.length) {
  20894. this.layers[0].dispose();
  20895. }
  20896. while (this.highlightLayers.length) {
  20897. this.highlightLayers[0].dispose();
  20898. }
  20899. // Release textures
  20900. while (this.textures.length) {
  20901. this.textures[0].dispose();
  20902. }
  20903. // Release UBO
  20904. this._sceneUbo.dispose();
  20905. if (this._alternateSceneUbo) {
  20906. this._alternateSceneUbo.dispose();
  20907. }
  20908. // Post-processes
  20909. this.postProcessManager.dispose();
  20910. if (this._postProcessRenderPipelineManager) {
  20911. this._postProcessRenderPipelineManager.dispose();
  20912. }
  20913. // Physics
  20914. if (this._physicsEngine) {
  20915. this.disablePhysicsEngine();
  20916. }
  20917. // Remove from engine
  20918. index = this._engine.scenes.indexOf(this);
  20919. if (index > -1) {
  20920. this._engine.scenes.splice(index, 1);
  20921. }
  20922. this._engine.wipeCaches();
  20923. this._isDisposed = true;
  20924. };
  20925. Object.defineProperty(Scene.prototype, "isDisposed", {
  20926. get: function () {
  20927. return this._isDisposed;
  20928. },
  20929. enumerable: true,
  20930. configurable: true
  20931. });
  20932. // Release sounds & sounds tracks
  20933. Scene.prototype.disposeSounds = function () {
  20934. if (!this._mainSoundTrack) {
  20935. return;
  20936. }
  20937. this.mainSoundTrack.dispose();
  20938. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20939. this.soundTracks[scIndex].dispose();
  20940. }
  20941. };
  20942. // Octrees
  20943. Scene.prototype.getWorldExtends = function () {
  20944. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20945. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20946. for (var index = 0; index < this.meshes.length; index++) {
  20947. var mesh = this.meshes[index];
  20948. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  20949. continue;
  20950. }
  20951. mesh.computeWorldMatrix(true);
  20952. var boundingInfo = mesh.getBoundingInfo();
  20953. if (boundingInfo) {
  20954. var minBox = boundingInfo.boundingBox.minimumWorld;
  20955. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20956. BABYLON.Tools.CheckExtends(minBox, min, max);
  20957. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20958. }
  20959. }
  20960. return {
  20961. min: min,
  20962. max: max
  20963. };
  20964. };
  20965. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20966. if (maxCapacity === void 0) { maxCapacity = 64; }
  20967. if (maxDepth === void 0) { maxDepth = 2; }
  20968. if (!this._selectionOctree) {
  20969. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20970. }
  20971. var worldExtends = this.getWorldExtends();
  20972. // Update octree
  20973. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20974. return this._selectionOctree;
  20975. };
  20976. // Picking
  20977. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  20978. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  20979. var engine = this._engine;
  20980. if (!camera) {
  20981. if (!this.activeCamera)
  20982. throw new Error("Active camera not set");
  20983. camera = this.activeCamera;
  20984. }
  20985. var cameraViewport = camera.viewport;
  20986. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20987. // Moving coordinates to local viewport world
  20988. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20989. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20990. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  20991. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  20992. };
  20993. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  20994. if (!BABYLON.PickingInfo) {
  20995. return null;
  20996. }
  20997. var engine = this._engine;
  20998. if (!camera) {
  20999. if (!this.activeCamera)
  21000. throw new Error("Active camera not set");
  21001. camera = this.activeCamera;
  21002. }
  21003. var cameraViewport = camera.viewport;
  21004. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21005. var identity = BABYLON.Matrix.Identity();
  21006. // Moving coordinates to local viewport world
  21007. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21008. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21009. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21010. };
  21011. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21012. if (!BABYLON.PickingInfo) {
  21013. return null;
  21014. }
  21015. var pickingInfo = null;
  21016. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21017. var mesh = this.meshes[meshIndex];
  21018. if (predicate) {
  21019. if (!predicate(mesh)) {
  21020. continue;
  21021. }
  21022. }
  21023. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21024. continue;
  21025. }
  21026. var world = mesh.getWorldMatrix();
  21027. var ray = rayFunction(world);
  21028. var result = mesh.intersects(ray, fastCheck);
  21029. if (!result || !result.hit)
  21030. continue;
  21031. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21032. continue;
  21033. pickingInfo = result;
  21034. if (fastCheck) {
  21035. break;
  21036. }
  21037. }
  21038. return pickingInfo || new BABYLON.PickingInfo();
  21039. };
  21040. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21041. if (!BABYLON.PickingInfo) {
  21042. return null;
  21043. }
  21044. var pickingInfos = new Array();
  21045. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21046. var mesh = this.meshes[meshIndex];
  21047. if (predicate) {
  21048. if (!predicate(mesh)) {
  21049. continue;
  21050. }
  21051. }
  21052. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21053. continue;
  21054. }
  21055. var world = mesh.getWorldMatrix();
  21056. var ray = rayFunction(world);
  21057. var result = mesh.intersects(ray, false);
  21058. if (!result || !result.hit)
  21059. continue;
  21060. pickingInfos.push(result);
  21061. }
  21062. return pickingInfos;
  21063. };
  21064. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21065. if (!BABYLON.PickingInfo) {
  21066. return null;
  21067. }
  21068. var pickingInfo = null;
  21069. if (!camera) {
  21070. if (!this.activeCamera) {
  21071. return null;
  21072. }
  21073. camera = this.activeCamera;
  21074. }
  21075. if (this.spriteManagers.length > 0) {
  21076. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21077. var spriteManager = this.spriteManagers[spriteIndex];
  21078. if (!spriteManager.isPickable) {
  21079. continue;
  21080. }
  21081. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21082. if (!result || !result.hit)
  21083. continue;
  21084. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21085. continue;
  21086. pickingInfo = result;
  21087. if (fastCheck) {
  21088. break;
  21089. }
  21090. }
  21091. }
  21092. return pickingInfo || new BABYLON.PickingInfo();
  21093. };
  21094. /** Launch a ray to try to pick a mesh in the scene
  21095. * @param x position on screen
  21096. * @param y position on screen
  21097. * @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
  21098. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21099. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21100. */
  21101. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21102. var _this = this;
  21103. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, fastCheck);
  21104. };
  21105. /** Launch a ray to try to pick a sprite in the scene
  21106. * @param x position on screen
  21107. * @param y position on screen
  21108. * @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
  21109. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21110. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21111. */
  21112. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21113. var ray = this.createPickingRayInCameraSpace(x, y, camera);
  21114. if (!ray) {
  21115. return null;
  21116. }
  21117. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  21118. };
  21119. /** Use the given ray to pick a mesh in the scene
  21120. * @param ray The ray to use to pick meshes
  21121. * @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
  21122. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21123. */
  21124. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21125. var _this = this;
  21126. return this._internalPick(function (world) {
  21127. if (!_this._pickWithRayInverseMatrix) {
  21128. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21129. }
  21130. world.invertToRef(_this._pickWithRayInverseMatrix);
  21131. if (!_this._cachedRayForTransform) {
  21132. _this._cachedRayForTransform = new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  21133. }
  21134. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21135. return _this._cachedRayForTransform;
  21136. }, predicate, fastCheck);
  21137. };
  21138. /**
  21139. * Launch a ray to try to pick a mesh in the scene
  21140. * @param x X position on screen
  21141. * @param y Y position on screen
  21142. * @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
  21143. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21144. */
  21145. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21146. var _this = this;
  21147. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  21148. };
  21149. /**
  21150. * Launch a ray to try to pick a mesh in the scene
  21151. * @param ray Ray to use
  21152. * @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
  21153. */
  21154. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21155. var _this = this;
  21156. return this._internalMultiPick(function (world) {
  21157. if (!_this._pickWithRayInverseMatrix) {
  21158. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21159. }
  21160. world.invertToRef(_this._pickWithRayInverseMatrix);
  21161. if (!_this._cachedRayForTransform) {
  21162. _this._cachedRayForTransform = new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  21163. }
  21164. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21165. return _this._cachedRayForTransform;
  21166. }, predicate);
  21167. };
  21168. Scene.prototype.setPointerOverMesh = function (mesh) {
  21169. if (this._pointerOverMesh === mesh) {
  21170. return;
  21171. }
  21172. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21173. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21174. }
  21175. this._pointerOverMesh = mesh;
  21176. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21177. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21178. }
  21179. };
  21180. Scene.prototype.getPointerOverMesh = function () {
  21181. return this._pointerOverMesh;
  21182. };
  21183. Scene.prototype.setPointerOverSprite = function (sprite) {
  21184. if (this._pointerOverSprite === sprite) {
  21185. return;
  21186. }
  21187. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21188. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21189. }
  21190. this._pointerOverSprite = sprite;
  21191. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21192. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21193. }
  21194. };
  21195. Scene.prototype.getPointerOverSprite = function () {
  21196. return this._pointerOverSprite;
  21197. };
  21198. // Physics
  21199. Scene.prototype.getPhysicsEngine = function () {
  21200. return this._physicsEngine;
  21201. };
  21202. /**
  21203. * Enables physics to the current scene
  21204. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21205. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21206. * @return {boolean} was the physics engine initialized
  21207. */
  21208. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21209. if (gravity === void 0) { gravity = null; }
  21210. if (this._physicsEngine) {
  21211. return true;
  21212. }
  21213. try {
  21214. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21215. return true;
  21216. }
  21217. catch (e) {
  21218. BABYLON.Tools.Error(e.message);
  21219. return false;
  21220. }
  21221. };
  21222. Scene.prototype.disablePhysicsEngine = function () {
  21223. if (!this._physicsEngine) {
  21224. return;
  21225. }
  21226. this._physicsEngine.dispose();
  21227. this._physicsEngine = null;
  21228. };
  21229. Scene.prototype.isPhysicsEnabled = function () {
  21230. return this._physicsEngine !== undefined;
  21231. };
  21232. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21233. var mesh = compound.parts[0].mesh;
  21234. if (mesh.physicsImpostor) {
  21235. mesh.physicsImpostor.dispose();
  21236. mesh.physicsImpostor = null;
  21237. }
  21238. };
  21239. // Misc.
  21240. Scene.prototype._rebuildGeometries = function () {
  21241. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  21242. var geometry = _a[_i];
  21243. geometry._rebuild();
  21244. }
  21245. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  21246. var mesh = _c[_b];
  21247. mesh._rebuild();
  21248. }
  21249. if (this.postProcessManager) {
  21250. this.postProcessManager._rebuild();
  21251. }
  21252. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  21253. var layer = _e[_d];
  21254. layer._rebuild();
  21255. }
  21256. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  21257. var highlightLayer = _g[_f];
  21258. highlightLayer._rebuild();
  21259. }
  21260. if (this._boundingBoxRenderer) {
  21261. this._boundingBoxRenderer._rebuild();
  21262. }
  21263. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  21264. var system = _j[_h];
  21265. system.rebuild();
  21266. }
  21267. if (this._postProcessRenderPipelineManager) {
  21268. this._postProcessRenderPipelineManager._rebuild();
  21269. }
  21270. };
  21271. Scene.prototype._rebuildTextures = function () {
  21272. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  21273. var texture = _a[_i];
  21274. texture._rebuild();
  21275. }
  21276. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21277. };
  21278. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  21279. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21280. if (replace === void 0) { replace = false; }
  21281. if (attachCameraControls === void 0) { attachCameraControls = false; }
  21282. // Dispose existing camera or light in replace mode.
  21283. if (replace) {
  21284. if (this.activeCamera) {
  21285. this.activeCamera.dispose();
  21286. this.activeCamera = null;
  21287. }
  21288. if (this.lights) {
  21289. for (var i = 0; i < this.lights.length; i++) {
  21290. this.lights[i].dispose();
  21291. }
  21292. }
  21293. }
  21294. // Light
  21295. if (this.lights.length === 0) {
  21296. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21297. }
  21298. // Camera
  21299. if (!this.activeCamera) {
  21300. var worldExtends = this.getWorldExtends();
  21301. var worldSize = worldExtends.max.subtract(worldExtends.min);
  21302. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  21303. var camera;
  21304. var radius = worldSize.length() * 1.5;
  21305. if (createArcRotateCamera) {
  21306. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  21307. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  21308. arcRotateCamera.wheelPrecision = 100 / radius;
  21309. camera = arcRotateCamera;
  21310. }
  21311. else {
  21312. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  21313. freeCamera.setTarget(worldCenter);
  21314. camera = freeCamera;
  21315. }
  21316. camera.minZ = radius * 0.01;
  21317. camera.maxZ = radius * 100;
  21318. camera.speed = radius * 0.2;
  21319. this.activeCamera = camera;
  21320. var canvas = this.getEngine().getRenderingCanvas();
  21321. if (attachCameraControls && canvas) {
  21322. camera.attachControl(canvas);
  21323. }
  21324. }
  21325. };
  21326. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  21327. if (pbr === void 0) { pbr = false; }
  21328. if (scale === void 0) { scale = 1000; }
  21329. if (blur === void 0) { blur = 0; }
  21330. if (environmentTexture) {
  21331. this.environmentTexture = environmentTexture;
  21332. }
  21333. if (!this.environmentTexture) {
  21334. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  21335. return null;
  21336. }
  21337. // Skybox
  21338. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  21339. if (pbr) {
  21340. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  21341. hdrSkyboxMaterial.backFaceCulling = false;
  21342. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21343. if (hdrSkyboxMaterial.reflectionTexture) {
  21344. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21345. }
  21346. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  21347. hdrSkyboxMaterial.disableLighting = true;
  21348. hdrSkyboxMaterial.twoSidedLighting = true;
  21349. hdrSkybox.infiniteDistance = true;
  21350. hdrSkybox.material = hdrSkyboxMaterial;
  21351. }
  21352. else {
  21353. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  21354. skyboxMaterial.backFaceCulling = false;
  21355. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  21356. if (skyboxMaterial.reflectionTexture) {
  21357. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  21358. }
  21359. skyboxMaterial.disableLighting = true;
  21360. hdrSkybox.infiniteDistance = true;
  21361. hdrSkybox.material = skyboxMaterial;
  21362. }
  21363. return hdrSkybox;
  21364. };
  21365. Scene.prototype.createDefaultEnvironment = function (options) {
  21366. if (BABYLON.EnvironmentHelper) {
  21367. return new BABYLON.EnvironmentHelper(options, this);
  21368. }
  21369. return null;
  21370. };
  21371. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  21372. if (webVROptions === void 0) { webVROptions = {}; }
  21373. return new BABYLON.VRExperienceHelper(this, webVROptions);
  21374. };
  21375. // Tags
  21376. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  21377. if (tagsQuery === undefined) {
  21378. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  21379. return list;
  21380. }
  21381. var listByTags = [];
  21382. forEach = forEach || (function (item) { return; });
  21383. for (var i in list) {
  21384. var item = list[i];
  21385. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  21386. listByTags.push(item);
  21387. forEach(item);
  21388. }
  21389. }
  21390. return listByTags;
  21391. };
  21392. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  21393. return this._getByTags(this.meshes, tagsQuery, forEach);
  21394. };
  21395. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  21396. return this._getByTags(this.cameras, tagsQuery, forEach);
  21397. };
  21398. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  21399. return this._getByTags(this.lights, tagsQuery, forEach);
  21400. };
  21401. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  21402. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  21403. };
  21404. /**
  21405. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21406. * This allowed control for front to back rendering or reversly depending of the special needs.
  21407. *
  21408. * @param renderingGroupId The rendering group id corresponding to its index
  21409. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21410. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21411. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21412. */
  21413. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21414. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21415. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21416. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21417. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  21418. };
  21419. /**
  21420. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21421. *
  21422. * @param renderingGroupId The rendering group id corresponding to its index
  21423. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21424. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21425. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21426. */
  21427. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21428. if (depth === void 0) { depth = true; }
  21429. if (stencil === void 0) { stencil = true; }
  21430. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  21431. };
  21432. /**
  21433. * Will flag all materials as dirty to trigger new shader compilation
  21434. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  21435. */
  21436. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  21437. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  21438. var material = _a[_i];
  21439. if (predicate && !predicate(material)) {
  21440. continue;
  21441. }
  21442. material.markAsDirty(flag);
  21443. }
  21444. };
  21445. // Statics
  21446. Scene._FOGMODE_NONE = 0;
  21447. Scene._FOGMODE_EXP = 1;
  21448. Scene._FOGMODE_EXP2 = 2;
  21449. Scene._FOGMODE_LINEAR = 3;
  21450. Scene._uniqueIdCounter = 0;
  21451. Scene.MinDeltaTime = 1.0;
  21452. Scene.MaxDeltaTime = 1000.0;
  21453. /** The distance in pixel that you have to move to prevent some events */
  21454. Scene.DragMovementThreshold = 10; // in pixels
  21455. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  21456. Scene.LongPressDelay = 500; // in milliseconds
  21457. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  21458. Scene.DoubleClickDelay = 300; // in milliseconds
  21459. /** If you need to check double click without raising a single click at first click, enable this flag */
  21460. Scene.ExclusiveDoubleClickMode = false;
  21461. return Scene;
  21462. }());
  21463. BABYLON.Scene = Scene;
  21464. })(BABYLON || (BABYLON = {}));
  21465. //# sourceMappingURL=babylon.scene.js.map
  21466. var BABYLON;
  21467. (function (BABYLON) {
  21468. var Buffer = /** @class */ (function () {
  21469. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21470. if (instanced === void 0) { instanced = false; }
  21471. if (engine instanceof BABYLON.Mesh) {
  21472. this._engine = engine.getScene().getEngine();
  21473. }
  21474. else {
  21475. this._engine = engine;
  21476. }
  21477. this._updatable = updatable;
  21478. this._data = data;
  21479. this._strideSize = stride;
  21480. if (!postponeInternalCreation) {
  21481. this.create();
  21482. }
  21483. this._instanced = instanced;
  21484. this._instanceDivisor = instanced ? 1 : 0;
  21485. }
  21486. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21487. // a lot of these parameters are ignored as they are overriden by the buffer
  21488. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21489. };
  21490. // Properties
  21491. Buffer.prototype.isUpdatable = function () {
  21492. return this._updatable;
  21493. };
  21494. Buffer.prototype.getData = function () {
  21495. return this._data;
  21496. };
  21497. Buffer.prototype.getBuffer = function () {
  21498. return this._buffer;
  21499. };
  21500. Buffer.prototype.getStrideSize = function () {
  21501. return this._strideSize;
  21502. };
  21503. Buffer.prototype.getIsInstanced = function () {
  21504. return this._instanced;
  21505. };
  21506. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21507. get: function () {
  21508. return this._instanceDivisor;
  21509. },
  21510. set: function (value) {
  21511. this._instanceDivisor = value;
  21512. if (value == 0) {
  21513. this._instanced = false;
  21514. }
  21515. else {
  21516. this._instanced = true;
  21517. }
  21518. },
  21519. enumerable: true,
  21520. configurable: true
  21521. });
  21522. // Methods
  21523. Buffer.prototype.create = function (data) {
  21524. if (data === void 0) { data = null; }
  21525. if (!data && this._buffer) {
  21526. return; // nothing to do
  21527. }
  21528. data = data || this._data;
  21529. if (!data) {
  21530. return;
  21531. }
  21532. if (!this._buffer) {
  21533. if (this._updatable) {
  21534. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21535. this._data = data;
  21536. }
  21537. else {
  21538. this._buffer = this._engine.createVertexBuffer(data);
  21539. }
  21540. }
  21541. else if (this._updatable) {
  21542. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21543. this._data = data;
  21544. }
  21545. };
  21546. Buffer.prototype._rebuild = function () {
  21547. this._buffer = null;
  21548. this.create(this._data);
  21549. };
  21550. Buffer.prototype.update = function (data) {
  21551. this.create(data);
  21552. };
  21553. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21554. if (!this._buffer) {
  21555. return;
  21556. }
  21557. if (this._updatable) {
  21558. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21559. this._data = null;
  21560. }
  21561. };
  21562. Buffer.prototype.dispose = function () {
  21563. if (!this._buffer) {
  21564. return;
  21565. }
  21566. if (this._engine._releaseBuffer(this._buffer)) {
  21567. this._buffer = null;
  21568. }
  21569. };
  21570. return Buffer;
  21571. }());
  21572. BABYLON.Buffer = Buffer;
  21573. })(BABYLON || (BABYLON = {}));
  21574. //# sourceMappingURL=babylon.buffer.js.map
  21575. var BABYLON;
  21576. (function (BABYLON) {
  21577. var VertexBuffer = /** @class */ (function () {
  21578. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21579. if (!stride) {
  21580. // Deduce stride from kind
  21581. switch (kind) {
  21582. case VertexBuffer.PositionKind:
  21583. stride = 3;
  21584. break;
  21585. case VertexBuffer.NormalKind:
  21586. stride = 3;
  21587. break;
  21588. case VertexBuffer.UVKind:
  21589. case VertexBuffer.UV2Kind:
  21590. case VertexBuffer.UV3Kind:
  21591. case VertexBuffer.UV4Kind:
  21592. case VertexBuffer.UV5Kind:
  21593. case VertexBuffer.UV6Kind:
  21594. stride = 2;
  21595. break;
  21596. case VertexBuffer.TangentKind:
  21597. case VertexBuffer.ColorKind:
  21598. stride = 4;
  21599. break;
  21600. case VertexBuffer.MatricesIndicesKind:
  21601. case VertexBuffer.MatricesIndicesExtraKind:
  21602. stride = 4;
  21603. break;
  21604. case VertexBuffer.MatricesWeightsKind:
  21605. case VertexBuffer.MatricesWeightsExtraKind:
  21606. default:
  21607. stride = 4;
  21608. break;
  21609. }
  21610. }
  21611. if (data instanceof BABYLON.Buffer) {
  21612. if (!stride) {
  21613. stride = data.getStrideSize();
  21614. }
  21615. this._buffer = data;
  21616. this._ownsBuffer = false;
  21617. }
  21618. else {
  21619. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21620. this._ownsBuffer = true;
  21621. }
  21622. this._stride = stride;
  21623. this._offset = offset ? offset : 0;
  21624. this._size = size ? size : stride;
  21625. this._kind = kind;
  21626. }
  21627. VertexBuffer.prototype._rebuild = function () {
  21628. if (!this._buffer) {
  21629. return;
  21630. }
  21631. this._buffer._rebuild();
  21632. };
  21633. /**
  21634. * Returns the kind of the VertexBuffer (string).
  21635. */
  21636. VertexBuffer.prototype.getKind = function () {
  21637. return this._kind;
  21638. };
  21639. // Properties
  21640. /**
  21641. * Boolean : is the VertexBuffer updatable ?
  21642. */
  21643. VertexBuffer.prototype.isUpdatable = function () {
  21644. return this._buffer.isUpdatable();
  21645. };
  21646. /**
  21647. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21648. */
  21649. VertexBuffer.prototype.getData = function () {
  21650. return this._buffer.getData();
  21651. };
  21652. /**
  21653. * Returns the WebGLBuffer associated to the VertexBuffer.
  21654. */
  21655. VertexBuffer.prototype.getBuffer = function () {
  21656. return this._buffer.getBuffer();
  21657. };
  21658. /**
  21659. * Returns the stride of the VertexBuffer (integer).
  21660. */
  21661. VertexBuffer.prototype.getStrideSize = function () {
  21662. return this._stride;
  21663. };
  21664. /**
  21665. * Returns the offset (integer).
  21666. */
  21667. VertexBuffer.prototype.getOffset = function () {
  21668. return this._offset;
  21669. };
  21670. /**
  21671. * Returns the VertexBuffer total size (integer).
  21672. */
  21673. VertexBuffer.prototype.getSize = function () {
  21674. return this._size;
  21675. };
  21676. /**
  21677. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21678. */
  21679. VertexBuffer.prototype.getIsInstanced = function () {
  21680. return this._buffer.getIsInstanced();
  21681. };
  21682. /**
  21683. * Returns the instancing divisor, zero for non-instanced (integer).
  21684. */
  21685. VertexBuffer.prototype.getInstanceDivisor = function () {
  21686. return this._buffer.instanceDivisor;
  21687. };
  21688. // Methods
  21689. /**
  21690. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21691. * Returns the created WebGLBuffer.
  21692. */
  21693. VertexBuffer.prototype.create = function (data) {
  21694. return this._buffer.create(data);
  21695. };
  21696. /**
  21697. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21698. * Returns the updated WebGLBuffer.
  21699. */
  21700. VertexBuffer.prototype.update = function (data) {
  21701. return this._buffer.update(data);
  21702. };
  21703. /**
  21704. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21705. * Returns the directly updated WebGLBuffer.
  21706. */
  21707. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21708. return this._buffer.updateDirectly(data, offset);
  21709. };
  21710. /**
  21711. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21712. */
  21713. VertexBuffer.prototype.dispose = function () {
  21714. if (this._ownsBuffer) {
  21715. this._buffer.dispose();
  21716. }
  21717. };
  21718. Object.defineProperty(VertexBuffer, "PositionKind", {
  21719. get: function () {
  21720. return VertexBuffer._PositionKind;
  21721. },
  21722. enumerable: true,
  21723. configurable: true
  21724. });
  21725. Object.defineProperty(VertexBuffer, "NormalKind", {
  21726. get: function () {
  21727. return VertexBuffer._NormalKind;
  21728. },
  21729. enumerable: true,
  21730. configurable: true
  21731. });
  21732. Object.defineProperty(VertexBuffer, "TangentKind", {
  21733. get: function () {
  21734. return VertexBuffer._TangentKind;
  21735. },
  21736. enumerable: true,
  21737. configurable: true
  21738. });
  21739. Object.defineProperty(VertexBuffer, "UVKind", {
  21740. get: function () {
  21741. return VertexBuffer._UVKind;
  21742. },
  21743. enumerable: true,
  21744. configurable: true
  21745. });
  21746. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21747. get: function () {
  21748. return VertexBuffer._UV2Kind;
  21749. },
  21750. enumerable: true,
  21751. configurable: true
  21752. });
  21753. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21754. get: function () {
  21755. return VertexBuffer._UV3Kind;
  21756. },
  21757. enumerable: true,
  21758. configurable: true
  21759. });
  21760. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21761. get: function () {
  21762. return VertexBuffer._UV4Kind;
  21763. },
  21764. enumerable: true,
  21765. configurable: true
  21766. });
  21767. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21768. get: function () {
  21769. return VertexBuffer._UV5Kind;
  21770. },
  21771. enumerable: true,
  21772. configurable: true
  21773. });
  21774. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21775. get: function () {
  21776. return VertexBuffer._UV6Kind;
  21777. },
  21778. enumerable: true,
  21779. configurable: true
  21780. });
  21781. Object.defineProperty(VertexBuffer, "ColorKind", {
  21782. get: function () {
  21783. return VertexBuffer._ColorKind;
  21784. },
  21785. enumerable: true,
  21786. configurable: true
  21787. });
  21788. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21789. get: function () {
  21790. return VertexBuffer._MatricesIndicesKind;
  21791. },
  21792. enumerable: true,
  21793. configurable: true
  21794. });
  21795. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21796. get: function () {
  21797. return VertexBuffer._MatricesWeightsKind;
  21798. },
  21799. enumerable: true,
  21800. configurable: true
  21801. });
  21802. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21803. get: function () {
  21804. return VertexBuffer._MatricesIndicesExtraKind;
  21805. },
  21806. enumerable: true,
  21807. configurable: true
  21808. });
  21809. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21810. get: function () {
  21811. return VertexBuffer._MatricesWeightsExtraKind;
  21812. },
  21813. enumerable: true,
  21814. configurable: true
  21815. });
  21816. // Enums
  21817. VertexBuffer._PositionKind = "position";
  21818. VertexBuffer._NormalKind = "normal";
  21819. VertexBuffer._TangentKind = "tangent";
  21820. VertexBuffer._UVKind = "uv";
  21821. VertexBuffer._UV2Kind = "uv2";
  21822. VertexBuffer._UV3Kind = "uv3";
  21823. VertexBuffer._UV4Kind = "uv4";
  21824. VertexBuffer._UV5Kind = "uv5";
  21825. VertexBuffer._UV6Kind = "uv6";
  21826. VertexBuffer._ColorKind = "color";
  21827. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21828. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21829. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21830. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21831. return VertexBuffer;
  21832. }());
  21833. BABYLON.VertexBuffer = VertexBuffer;
  21834. })(BABYLON || (BABYLON = {}));
  21835. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21836. var BABYLON;
  21837. (function (BABYLON) {
  21838. var InternalTexture = /** @class */ (function () {
  21839. function InternalTexture(engine, dataSource) {
  21840. this.onLoadedObservable = new BABYLON.Observable();
  21841. // Private
  21842. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21843. this._references = 1;
  21844. this._engine = engine;
  21845. this._dataSource = dataSource;
  21846. this._webGLTexture = engine._createTexture();
  21847. }
  21848. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21849. get: function () {
  21850. return this._dataSource;
  21851. },
  21852. enumerable: true,
  21853. configurable: true
  21854. });
  21855. InternalTexture.prototype.incrementReferences = function () {
  21856. this._references++;
  21857. };
  21858. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21859. if (depth === void 0) { depth = 1; }
  21860. this.width = width;
  21861. this.height = height;
  21862. this.depth = depth;
  21863. this.baseWidth = width;
  21864. this.baseHeight = height;
  21865. this.baseDepth = depth;
  21866. this._size = width * height * depth;
  21867. };
  21868. InternalTexture.prototype._rebuild = function () {
  21869. var _this = this;
  21870. var proxy;
  21871. this.isReady = false;
  21872. this._cachedCoordinatesMode = null;
  21873. this._cachedWrapU = null;
  21874. this._cachedWrapV = null;
  21875. this._cachedAnisotropicFilteringLevel = null;
  21876. switch (this._dataSource) {
  21877. case InternalTexture.DATASOURCE_TEMP:
  21878. return;
  21879. case InternalTexture.DATASOURCE_URL:
  21880. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21881. _this.isReady = true;
  21882. }, null, this._buffer, undefined, this.format);
  21883. proxy._swapAndDie(this);
  21884. return;
  21885. case InternalTexture.DATASOURCE_RAW:
  21886. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21887. proxy._swapAndDie(this);
  21888. this.isReady = true;
  21889. return;
  21890. case InternalTexture.DATASOURCE_RAW3D:
  21891. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21892. proxy._swapAndDie(this);
  21893. this.isReady = true;
  21894. return;
  21895. case InternalTexture.DATASOURCE_DYNAMIC:
  21896. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21897. proxy._swapAndDie(this);
  21898. // The engine will make sure to update content so no need to flag it as isReady = true
  21899. return;
  21900. case InternalTexture.DATASOURCE_RENDERTARGET:
  21901. var options = new BABYLON.RenderTargetCreationOptions();
  21902. options.generateDepthBuffer = this._generateDepthBuffer;
  21903. options.generateMipMaps = this.generateMipMaps;
  21904. options.generateStencilBuffer = this._generateStencilBuffer;
  21905. options.samplingMode = this.samplingMode;
  21906. options.type = this.type;
  21907. if (this.isCube) {
  21908. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  21909. }
  21910. else {
  21911. var size = {
  21912. width: this.width,
  21913. height: this.height
  21914. };
  21915. proxy = this._engine.createRenderTargetTexture(size, options);
  21916. }
  21917. proxy._swapAndDie(this);
  21918. this.isReady = true;
  21919. return;
  21920. case InternalTexture.DATASOURCE_CUBE:
  21921. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  21922. _this.isReady = true;
  21923. }, null, this.format, this._extension);
  21924. proxy._swapAndDie(this);
  21925. return;
  21926. case InternalTexture.DATASOURCE_CUBERAW:
  21927. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21928. proxy._swapAndDie(this);
  21929. this.isReady = true;
  21930. return;
  21931. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  21932. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  21933. if (proxy) {
  21934. proxy._swapAndDie(_this);
  21935. }
  21936. _this.isReady = true;
  21937. }, null, this.format, this._extension);
  21938. return;
  21939. }
  21940. };
  21941. InternalTexture.prototype._swapAndDie = function (target) {
  21942. target._webGLTexture = this._webGLTexture;
  21943. if (this._framebuffer) {
  21944. target._framebuffer = this._framebuffer;
  21945. }
  21946. if (this._depthStencilBuffer) {
  21947. target._depthStencilBuffer = this._depthStencilBuffer;
  21948. }
  21949. if (this._lodTextureHigh) {
  21950. if (target._lodTextureHigh) {
  21951. target._lodTextureHigh.dispose();
  21952. }
  21953. target._lodTextureHigh = this._lodTextureHigh;
  21954. }
  21955. if (this._lodTextureMid) {
  21956. if (target._lodTextureMid) {
  21957. target._lodTextureMid.dispose();
  21958. }
  21959. target._lodTextureMid = this._lodTextureMid;
  21960. }
  21961. if (this._lodTextureLow) {
  21962. if (target._lodTextureLow) {
  21963. target._lodTextureLow.dispose();
  21964. }
  21965. target._lodTextureLow = this._lodTextureLow;
  21966. }
  21967. var cache = this._engine.getLoadedTexturesCache();
  21968. var index = cache.indexOf(this);
  21969. if (index !== -1) {
  21970. cache.splice(index, 1);
  21971. }
  21972. };
  21973. InternalTexture.prototype.dispose = function () {
  21974. if (!this._webGLTexture) {
  21975. return;
  21976. }
  21977. this._references--;
  21978. if (this._references === 0) {
  21979. this._engine._releaseTexture(this);
  21980. this._webGLTexture = null;
  21981. }
  21982. };
  21983. InternalTexture.DATASOURCE_UNKNOWN = 0;
  21984. InternalTexture.DATASOURCE_URL = 1;
  21985. InternalTexture.DATASOURCE_TEMP = 2;
  21986. InternalTexture.DATASOURCE_RAW = 3;
  21987. InternalTexture.DATASOURCE_DYNAMIC = 4;
  21988. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  21989. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  21990. InternalTexture.DATASOURCE_CUBE = 7;
  21991. InternalTexture.DATASOURCE_CUBERAW = 8;
  21992. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  21993. InternalTexture.DATASOURCE_RAW3D = 10;
  21994. return InternalTexture;
  21995. }());
  21996. BABYLON.InternalTexture = InternalTexture;
  21997. })(BABYLON || (BABYLON = {}));
  21998. //# sourceMappingURL=babylon.internalTexture.js.map
  21999. var BABYLON;
  22000. (function (BABYLON) {
  22001. var BaseTexture = /** @class */ (function () {
  22002. function BaseTexture(scene) {
  22003. this._hasAlpha = false;
  22004. this.getAlphaFromRGB = false;
  22005. this.level = 1;
  22006. this.coordinatesIndex = 0;
  22007. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22008. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22009. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22010. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  22011. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  22012. this.isCube = false;
  22013. this.is3D = false;
  22014. this.gammaSpace = true;
  22015. this.invertZ = false;
  22016. this.lodLevelInAlpha = false;
  22017. this.lodGenerationOffset = 0.0;
  22018. this.lodGenerationScale = 0.8;
  22019. this.isRenderTarget = false;
  22020. this.animations = new Array();
  22021. /**
  22022. * An event triggered when the texture is disposed.
  22023. * @type {BABYLON.Observable}
  22024. */
  22025. this.onDisposeObservable = new BABYLON.Observable();
  22026. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22027. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22028. if (this._scene) {
  22029. this._scene.textures.push(this);
  22030. }
  22031. this._uid = null;
  22032. }
  22033. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  22034. get: function () {
  22035. return this._hasAlpha;
  22036. },
  22037. set: function (value) {
  22038. if (this._hasAlpha === value) {
  22039. return;
  22040. }
  22041. this._hasAlpha = value;
  22042. if (this._scene) {
  22043. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22044. }
  22045. },
  22046. enumerable: true,
  22047. configurable: true
  22048. });
  22049. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  22050. get: function () {
  22051. return this._coordinatesMode;
  22052. },
  22053. set: function (value) {
  22054. if (this._coordinatesMode === value) {
  22055. return;
  22056. }
  22057. this._coordinatesMode = value;
  22058. if (this._scene) {
  22059. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22060. }
  22061. },
  22062. enumerable: true,
  22063. configurable: true
  22064. });
  22065. Object.defineProperty(BaseTexture.prototype, "uid", {
  22066. get: function () {
  22067. if (!this._uid) {
  22068. this._uid = BABYLON.Tools.RandomId();
  22069. }
  22070. return this._uid;
  22071. },
  22072. enumerable: true,
  22073. configurable: true
  22074. });
  22075. BaseTexture.prototype.toString = function () {
  22076. return this.name;
  22077. };
  22078. BaseTexture.prototype.getClassName = function () {
  22079. return "BaseTexture";
  22080. };
  22081. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22082. set: function (callback) {
  22083. if (this._onDisposeObserver) {
  22084. this.onDisposeObservable.remove(this._onDisposeObserver);
  22085. }
  22086. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22087. },
  22088. enumerable: true,
  22089. configurable: true
  22090. });
  22091. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  22092. get: function () {
  22093. return true;
  22094. },
  22095. enumerable: true,
  22096. configurable: true
  22097. });
  22098. BaseTexture.prototype.getScene = function () {
  22099. return this._scene;
  22100. };
  22101. BaseTexture.prototype.getTextureMatrix = function () {
  22102. return BABYLON.Matrix.IdentityReadOnly;
  22103. };
  22104. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22105. return BABYLON.Matrix.IdentityReadOnly;
  22106. };
  22107. BaseTexture.prototype.getInternalTexture = function () {
  22108. return this._texture;
  22109. };
  22110. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  22111. return !this.isBlocking || this.isReady();
  22112. };
  22113. BaseTexture.prototype.isReady = function () {
  22114. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22115. this.delayLoad();
  22116. return false;
  22117. }
  22118. if (this._texture) {
  22119. return this._texture.isReady;
  22120. }
  22121. return false;
  22122. };
  22123. BaseTexture.prototype.getSize = function () {
  22124. if (this._texture && this._texture.width) {
  22125. return new BABYLON.Size(this._texture.width, this._texture.height);
  22126. }
  22127. if (this._texture && this._texture._size) {
  22128. return new BABYLON.Size(this._texture._size, this._texture._size);
  22129. }
  22130. return BABYLON.Size.Zero();
  22131. };
  22132. BaseTexture.prototype.getBaseSize = function () {
  22133. if (!this.isReady() || !this._texture)
  22134. return BABYLON.Size.Zero();
  22135. if (this._texture._size) {
  22136. return new BABYLON.Size(this._texture._size, this._texture._size);
  22137. }
  22138. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  22139. };
  22140. BaseTexture.prototype.scale = function (ratio) {
  22141. };
  22142. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22143. get: function () {
  22144. return false;
  22145. },
  22146. enumerable: true,
  22147. configurable: true
  22148. });
  22149. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22150. if (!this._scene) {
  22151. return null;
  22152. }
  22153. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22154. for (var index = 0; index < texturesCache.length; index++) {
  22155. var texturesCacheEntry = texturesCache[index];
  22156. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  22157. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22158. texturesCacheEntry.incrementReferences();
  22159. return texturesCacheEntry;
  22160. }
  22161. }
  22162. }
  22163. return null;
  22164. };
  22165. BaseTexture.prototype._rebuild = function () {
  22166. };
  22167. BaseTexture.prototype.delayLoad = function () {
  22168. };
  22169. BaseTexture.prototype.clone = function () {
  22170. return null;
  22171. };
  22172. Object.defineProperty(BaseTexture.prototype, "textureType", {
  22173. get: function () {
  22174. if (!this._texture) {
  22175. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22176. }
  22177. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22178. },
  22179. enumerable: true,
  22180. configurable: true
  22181. });
  22182. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  22183. get: function () {
  22184. if (!this._texture) {
  22185. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22186. }
  22187. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22188. },
  22189. enumerable: true,
  22190. configurable: true
  22191. });
  22192. BaseTexture.prototype.readPixels = function (faceIndex) {
  22193. if (faceIndex === void 0) { faceIndex = 0; }
  22194. if (!this._texture) {
  22195. return null;
  22196. }
  22197. var size = this.getSize();
  22198. var scene = this.getScene();
  22199. if (!scene) {
  22200. return null;
  22201. }
  22202. var engine = scene.getEngine();
  22203. if (this._texture.isCube) {
  22204. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  22205. }
  22206. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  22207. };
  22208. BaseTexture.prototype.releaseInternalTexture = function () {
  22209. if (this._texture) {
  22210. this._texture.dispose();
  22211. this._texture = null;
  22212. }
  22213. };
  22214. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  22215. get: function () {
  22216. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  22217. return null;
  22218. }
  22219. if (!this._texture._sphericalPolynomial) {
  22220. this._texture._sphericalPolynomial =
  22221. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  22222. }
  22223. return this._texture._sphericalPolynomial;
  22224. },
  22225. set: function (value) {
  22226. if (this._texture) {
  22227. this._texture._sphericalPolynomial = value;
  22228. }
  22229. },
  22230. enumerable: true,
  22231. configurable: true
  22232. });
  22233. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  22234. get: function () {
  22235. if (this._texture) {
  22236. return this._texture._lodTextureHigh;
  22237. }
  22238. return null;
  22239. },
  22240. enumerable: true,
  22241. configurable: true
  22242. });
  22243. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  22244. get: function () {
  22245. if (this._texture) {
  22246. return this._texture._lodTextureMid;
  22247. }
  22248. return null;
  22249. },
  22250. enumerable: true,
  22251. configurable: true
  22252. });
  22253. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  22254. get: function () {
  22255. if (this._texture) {
  22256. return this._texture._lodTextureLow;
  22257. }
  22258. return null;
  22259. },
  22260. enumerable: true,
  22261. configurable: true
  22262. });
  22263. BaseTexture.prototype.dispose = function () {
  22264. if (!this._scene) {
  22265. return;
  22266. }
  22267. // Animations
  22268. this._scene.stopAnimation(this);
  22269. // Remove from scene
  22270. this._scene._removePendingData(this);
  22271. var index = this._scene.textures.indexOf(this);
  22272. if (index >= 0) {
  22273. this._scene.textures.splice(index, 1);
  22274. }
  22275. if (this._texture === undefined) {
  22276. return;
  22277. }
  22278. // Release
  22279. this.releaseInternalTexture();
  22280. // Callback
  22281. this.onDisposeObservable.notifyObservers(this);
  22282. this.onDisposeObservable.clear();
  22283. };
  22284. BaseTexture.prototype.serialize = function () {
  22285. if (!this.name) {
  22286. return null;
  22287. }
  22288. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22289. // Animations
  22290. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22291. return serializationObject;
  22292. };
  22293. BaseTexture.WhenAllReady = function (textures, callback) {
  22294. var numRemaining = textures.length;
  22295. if (numRemaining === 0) {
  22296. callback();
  22297. return;
  22298. }
  22299. var _loop_1 = function () {
  22300. texture = textures[i];
  22301. if (texture.isReady()) {
  22302. if (--numRemaining === 0) {
  22303. callback();
  22304. }
  22305. }
  22306. else {
  22307. onLoadObservable = texture.onLoadObservable;
  22308. var onLoadCallback_1 = function () {
  22309. onLoadObservable.removeCallback(onLoadCallback_1);
  22310. if (--numRemaining === 0) {
  22311. callback();
  22312. }
  22313. };
  22314. onLoadObservable.add(onLoadCallback_1);
  22315. }
  22316. };
  22317. var texture, onLoadObservable;
  22318. for (var i = 0; i < textures.length; i++) {
  22319. _loop_1();
  22320. }
  22321. };
  22322. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  22323. __decorate([
  22324. BABYLON.serialize()
  22325. ], BaseTexture.prototype, "name", void 0);
  22326. __decorate([
  22327. BABYLON.serialize("hasAlpha")
  22328. ], BaseTexture.prototype, "_hasAlpha", void 0);
  22329. __decorate([
  22330. BABYLON.serialize()
  22331. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22332. __decorate([
  22333. BABYLON.serialize()
  22334. ], BaseTexture.prototype, "level", void 0);
  22335. __decorate([
  22336. BABYLON.serialize()
  22337. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22338. __decorate([
  22339. BABYLON.serialize("coordinatesMode")
  22340. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  22341. __decorate([
  22342. BABYLON.serialize()
  22343. ], BaseTexture.prototype, "wrapU", void 0);
  22344. __decorate([
  22345. BABYLON.serialize()
  22346. ], BaseTexture.prototype, "wrapV", void 0);
  22347. __decorate([
  22348. BABYLON.serialize()
  22349. ], BaseTexture.prototype, "wrapR", void 0);
  22350. __decorate([
  22351. BABYLON.serialize()
  22352. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22353. __decorate([
  22354. BABYLON.serialize()
  22355. ], BaseTexture.prototype, "isCube", void 0);
  22356. __decorate([
  22357. BABYLON.serialize()
  22358. ], BaseTexture.prototype, "is3D", void 0);
  22359. __decorate([
  22360. BABYLON.serialize()
  22361. ], BaseTexture.prototype, "gammaSpace", void 0);
  22362. __decorate([
  22363. BABYLON.serialize()
  22364. ], BaseTexture.prototype, "invertZ", void 0);
  22365. __decorate([
  22366. BABYLON.serialize()
  22367. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  22368. __decorate([
  22369. BABYLON.serialize()
  22370. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  22371. __decorate([
  22372. BABYLON.serialize()
  22373. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  22374. __decorate([
  22375. BABYLON.serialize()
  22376. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22377. return BaseTexture;
  22378. }());
  22379. BABYLON.BaseTexture = BaseTexture;
  22380. })(BABYLON || (BABYLON = {}));
  22381. //# sourceMappingURL=babylon.baseTexture.js.map
  22382. var BABYLON;
  22383. (function (BABYLON) {
  22384. var Texture = /** @class */ (function (_super) {
  22385. __extends(Texture, _super);
  22386. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  22387. if (noMipmap === void 0) { noMipmap = false; }
  22388. if (invertY === void 0) { invertY = true; }
  22389. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22390. if (onLoad === void 0) { onLoad = null; }
  22391. if (onError === void 0) { onError = null; }
  22392. if (buffer === void 0) { buffer = null; }
  22393. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22394. var _this = _super.call(this, scene) || this;
  22395. _this.uOffset = 0;
  22396. _this.vOffset = 0;
  22397. _this.uScale = 1.0;
  22398. _this.vScale = 1.0;
  22399. _this.uAng = 0;
  22400. _this.vAng = 0;
  22401. _this.wAng = 0;
  22402. _this._isBlocking = true;
  22403. _this.name = url || "";
  22404. _this.url = url;
  22405. _this._noMipmap = noMipmap;
  22406. _this._invertY = invertY;
  22407. _this._samplingMode = samplingMode;
  22408. _this._buffer = buffer;
  22409. _this._deleteBuffer = deleteBuffer;
  22410. if (format) {
  22411. _this._format = format;
  22412. }
  22413. scene = _this.getScene();
  22414. if (!scene) {
  22415. return _this;
  22416. }
  22417. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  22418. var load = function () {
  22419. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  22420. _this.onLoadObservable.notifyObservers(_this);
  22421. }
  22422. if (onLoad) {
  22423. onLoad();
  22424. }
  22425. if (!_this.isBlocking && scene) {
  22426. scene.resetCachedMaterial();
  22427. }
  22428. };
  22429. if (!_this.url) {
  22430. _this._delayedOnLoad = load;
  22431. _this._delayedOnError = onError;
  22432. return _this;
  22433. }
  22434. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  22435. if (!_this._texture) {
  22436. if (!scene.useDelayedTextureLoading) {
  22437. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  22438. if (deleteBuffer) {
  22439. delete _this._buffer;
  22440. }
  22441. }
  22442. else {
  22443. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22444. _this._delayedOnLoad = load;
  22445. _this._delayedOnError = onError;
  22446. }
  22447. }
  22448. else {
  22449. if (_this._texture.isReady) {
  22450. BABYLON.Tools.SetImmediate(function () { return load(); });
  22451. }
  22452. else {
  22453. _this._texture.onLoadedObservable.add(load);
  22454. }
  22455. }
  22456. return _this;
  22457. }
  22458. Object.defineProperty(Texture.prototype, "noMipmap", {
  22459. get: function () {
  22460. return this._noMipmap;
  22461. },
  22462. enumerable: true,
  22463. configurable: true
  22464. });
  22465. Object.defineProperty(Texture.prototype, "isBlocking", {
  22466. get: function () {
  22467. return this._isBlocking;
  22468. },
  22469. set: function (value) {
  22470. this._isBlocking = value;
  22471. },
  22472. enumerable: true,
  22473. configurable: true
  22474. });
  22475. Object.defineProperty(Texture.prototype, "samplingMode", {
  22476. get: function () {
  22477. return this._samplingMode;
  22478. },
  22479. enumerable: true,
  22480. configurable: true
  22481. });
  22482. Texture.prototype.updateURL = function (url) {
  22483. this.url = url;
  22484. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22485. this.delayLoad();
  22486. };
  22487. Texture.prototype.delayLoad = function () {
  22488. var _this = this;
  22489. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22490. return;
  22491. }
  22492. var scene = this.getScene();
  22493. if (!scene) {
  22494. return;
  22495. }
  22496. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22497. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22498. if (!this._texture) {
  22499. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22500. if (this._deleteBuffer) {
  22501. delete this._buffer;
  22502. }
  22503. }
  22504. else {
  22505. if (this._texture.isReady) {
  22506. BABYLON.Tools.SetImmediate(function () {
  22507. if (!_this._delayedOnLoad) {
  22508. return;
  22509. }
  22510. _this._delayedOnLoad();
  22511. });
  22512. }
  22513. else {
  22514. if (this._delayedOnLoad) {
  22515. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22516. }
  22517. }
  22518. }
  22519. };
  22520. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22521. if (!this._texture) {
  22522. return;
  22523. }
  22524. var scene = this.getScene();
  22525. if (!scene) {
  22526. return;
  22527. }
  22528. this._samplingMode = samplingMode;
  22529. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22530. };
  22531. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22532. x *= this.uScale;
  22533. y *= this.vScale;
  22534. x -= 0.5 * this.uScale;
  22535. y -= 0.5 * this.vScale;
  22536. z -= 0.5;
  22537. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22538. t.x += 0.5 * this.uScale + this.uOffset;
  22539. t.y += 0.5 * this.vScale + this.vOffset;
  22540. t.z += 0.5;
  22541. };
  22542. Texture.prototype.getTextureMatrix = function () {
  22543. var _this = this;
  22544. if (this.uOffset === this._cachedUOffset &&
  22545. this.vOffset === this._cachedVOffset &&
  22546. this.uScale === this._cachedUScale &&
  22547. this.vScale === this._cachedVScale &&
  22548. this.uAng === this._cachedUAng &&
  22549. this.vAng === this._cachedVAng &&
  22550. this.wAng === this._cachedWAng) {
  22551. return this._cachedTextureMatrix;
  22552. }
  22553. this._cachedUOffset = this.uOffset;
  22554. this._cachedVOffset = this.vOffset;
  22555. this._cachedUScale = this.uScale;
  22556. this._cachedVScale = this.vScale;
  22557. this._cachedUAng = this.uAng;
  22558. this._cachedVAng = this.vAng;
  22559. this._cachedWAng = this.wAng;
  22560. if (!this._cachedTextureMatrix) {
  22561. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22562. this._rowGenerationMatrix = new BABYLON.Matrix();
  22563. this._t0 = BABYLON.Vector3.Zero();
  22564. this._t1 = BABYLON.Vector3.Zero();
  22565. this._t2 = BABYLON.Vector3.Zero();
  22566. }
  22567. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22568. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22569. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22570. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22571. this._t1.subtractInPlace(this._t0);
  22572. this._t2.subtractInPlace(this._t0);
  22573. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22574. this._cachedTextureMatrix.m[0] = this._t1.x;
  22575. this._cachedTextureMatrix.m[1] = this._t1.y;
  22576. this._cachedTextureMatrix.m[2] = this._t1.z;
  22577. this._cachedTextureMatrix.m[4] = this._t2.x;
  22578. this._cachedTextureMatrix.m[5] = this._t2.y;
  22579. this._cachedTextureMatrix.m[6] = this._t2.z;
  22580. this._cachedTextureMatrix.m[8] = this._t0.x;
  22581. this._cachedTextureMatrix.m[9] = this._t0.y;
  22582. this._cachedTextureMatrix.m[10] = this._t0.z;
  22583. var scene = this.getScene();
  22584. if (!scene) {
  22585. return this._cachedTextureMatrix;
  22586. }
  22587. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22588. return mat.hasTexture(_this);
  22589. });
  22590. return this._cachedTextureMatrix;
  22591. };
  22592. Texture.prototype.getReflectionTextureMatrix = function () {
  22593. var _this = this;
  22594. var scene = this.getScene();
  22595. if (!scene) {
  22596. return this._cachedTextureMatrix;
  22597. }
  22598. if (this.uOffset === this._cachedUOffset &&
  22599. this.vOffset === this._cachedVOffset &&
  22600. this.uScale === this._cachedUScale &&
  22601. this.vScale === this._cachedVScale &&
  22602. this.coordinatesMode === this._cachedCoordinatesMode) {
  22603. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22604. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22605. return this._cachedTextureMatrix;
  22606. }
  22607. }
  22608. else {
  22609. return this._cachedTextureMatrix;
  22610. }
  22611. }
  22612. if (!this._cachedTextureMatrix) {
  22613. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22614. }
  22615. if (!this._projectionModeMatrix) {
  22616. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22617. }
  22618. this._cachedUOffset = this.uOffset;
  22619. this._cachedVOffset = this.vOffset;
  22620. this._cachedUScale = this.uScale;
  22621. this._cachedVScale = this.vScale;
  22622. this._cachedCoordinatesMode = this.coordinatesMode;
  22623. switch (this.coordinatesMode) {
  22624. case Texture.PLANAR_MODE:
  22625. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22626. this._cachedTextureMatrix[0] = this.uScale;
  22627. this._cachedTextureMatrix[5] = this.vScale;
  22628. this._cachedTextureMatrix[12] = this.uOffset;
  22629. this._cachedTextureMatrix[13] = this.vOffset;
  22630. break;
  22631. case Texture.PROJECTION_MODE:
  22632. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22633. this._projectionModeMatrix.m[0] = 0.5;
  22634. this._projectionModeMatrix.m[5] = -0.5;
  22635. this._projectionModeMatrix.m[10] = 0.0;
  22636. this._projectionModeMatrix.m[12] = 0.5;
  22637. this._projectionModeMatrix.m[13] = 0.5;
  22638. this._projectionModeMatrix.m[14] = 1.0;
  22639. this._projectionModeMatrix.m[15] = 1.0;
  22640. var projectionMatrix = scene.getProjectionMatrix();
  22641. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22642. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22643. break;
  22644. default:
  22645. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22646. break;
  22647. }
  22648. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22649. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22650. });
  22651. return this._cachedTextureMatrix;
  22652. };
  22653. Texture.prototype.clone = function () {
  22654. var _this = this;
  22655. return BABYLON.SerializationHelper.Clone(function () {
  22656. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22657. }, this);
  22658. };
  22659. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22660. get: function () {
  22661. if (!this._onLoadObservable) {
  22662. this._onLoadObservable = new BABYLON.Observable();
  22663. }
  22664. return this._onLoadObservable;
  22665. },
  22666. enumerable: true,
  22667. configurable: true
  22668. });
  22669. Texture.prototype.serialize = function () {
  22670. var serializationObject = _super.prototype.serialize.call(this);
  22671. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22672. serializationObject.base64String = this._buffer;
  22673. serializationObject.name = serializationObject.name.replace("data:", "");
  22674. }
  22675. return serializationObject;
  22676. };
  22677. Texture.prototype.getClassName = function () {
  22678. return "Texture";
  22679. };
  22680. Texture.prototype.dispose = function () {
  22681. _super.prototype.dispose.call(this);
  22682. if (this.onLoadObservable) {
  22683. this.onLoadObservable.clear();
  22684. this._onLoadObservable = null;
  22685. }
  22686. this._delayedOnLoad = null;
  22687. this._delayedOnError = null;
  22688. };
  22689. // Statics
  22690. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22691. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22692. if (onLoad === void 0) { onLoad = null; }
  22693. if (onError === void 0) { onError = null; }
  22694. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22695. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22696. };
  22697. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22698. if (parsedTexture.customType) {
  22699. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22700. // Update Sampling Mode
  22701. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22702. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22703. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22704. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22705. }
  22706. }
  22707. return parsedCustomTexture;
  22708. }
  22709. if (parsedTexture.isCube) {
  22710. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22711. }
  22712. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22713. return null;
  22714. }
  22715. var texture = BABYLON.SerializationHelper.Parse(function () {
  22716. if (parsedTexture.mirrorPlane) {
  22717. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22718. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22719. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22720. return mirrorTexture;
  22721. }
  22722. else if (parsedTexture.isRenderTarget) {
  22723. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22724. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22725. return renderTargetTexture;
  22726. }
  22727. else {
  22728. var texture;
  22729. if (parsedTexture.base64String) {
  22730. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22731. }
  22732. else {
  22733. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22734. }
  22735. return texture;
  22736. }
  22737. }, parsedTexture, scene);
  22738. // Update Sampling Mode
  22739. if (parsedTexture.samplingMode) {
  22740. var sampling = parsedTexture.samplingMode;
  22741. if (texture._samplingMode !== sampling) {
  22742. texture.updateSamplingMode(sampling);
  22743. }
  22744. }
  22745. // Animations
  22746. if (parsedTexture.animations) {
  22747. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22748. var parsedAnimation = parsedTexture.animations[animationIndex];
  22749. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22750. }
  22751. }
  22752. return texture;
  22753. };
  22754. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22755. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22756. if (noMipmap === void 0) { noMipmap = false; }
  22757. if (invertY === void 0) { invertY = true; }
  22758. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22759. if (onLoad === void 0) { onLoad = null; }
  22760. if (onError === void 0) { onError = null; }
  22761. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22762. if (name.substr(0, 5) !== "data:") {
  22763. name = "data:" + name;
  22764. }
  22765. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22766. };
  22767. // Constants
  22768. Texture.NEAREST_SAMPLINGMODE = 1;
  22769. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22770. Texture.BILINEAR_SAMPLINGMODE = 2;
  22771. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22772. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22773. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22774. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22775. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22776. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22777. Texture.NEAREST_LINEAR = 7;
  22778. Texture.NEAREST_NEAREST = 8;
  22779. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22780. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22781. Texture.LINEAR_LINEAR = 11;
  22782. Texture.LINEAR_NEAREST = 12;
  22783. Texture.EXPLICIT_MODE = 0;
  22784. Texture.SPHERICAL_MODE = 1;
  22785. Texture.PLANAR_MODE = 2;
  22786. Texture.CUBIC_MODE = 3;
  22787. Texture.PROJECTION_MODE = 4;
  22788. Texture.SKYBOX_MODE = 5;
  22789. Texture.INVCUBIC_MODE = 6;
  22790. Texture.EQUIRECTANGULAR_MODE = 7;
  22791. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22792. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22793. Texture.CLAMP_ADDRESSMODE = 0;
  22794. Texture.WRAP_ADDRESSMODE = 1;
  22795. Texture.MIRROR_ADDRESSMODE = 2;
  22796. __decorate([
  22797. BABYLON.serialize()
  22798. ], Texture.prototype, "url", void 0);
  22799. __decorate([
  22800. BABYLON.serialize()
  22801. ], Texture.prototype, "uOffset", void 0);
  22802. __decorate([
  22803. BABYLON.serialize()
  22804. ], Texture.prototype, "vOffset", void 0);
  22805. __decorate([
  22806. BABYLON.serialize()
  22807. ], Texture.prototype, "uScale", void 0);
  22808. __decorate([
  22809. BABYLON.serialize()
  22810. ], Texture.prototype, "vScale", void 0);
  22811. __decorate([
  22812. BABYLON.serialize()
  22813. ], Texture.prototype, "uAng", void 0);
  22814. __decorate([
  22815. BABYLON.serialize()
  22816. ], Texture.prototype, "vAng", void 0);
  22817. __decorate([
  22818. BABYLON.serialize()
  22819. ], Texture.prototype, "wAng", void 0);
  22820. __decorate([
  22821. BABYLON.serialize()
  22822. ], Texture.prototype, "isBlocking", null);
  22823. return Texture;
  22824. }(BABYLON.BaseTexture));
  22825. BABYLON.Texture = Texture;
  22826. })(BABYLON || (BABYLON = {}));
  22827. //# sourceMappingURL=babylon.texture.js.map
  22828. var BABYLON;
  22829. (function (BABYLON) {
  22830. var _InstancesBatch = /** @class */ (function () {
  22831. function _InstancesBatch() {
  22832. this.mustReturn = false;
  22833. this.visibleInstances = new Array();
  22834. this.renderSelf = new Array();
  22835. }
  22836. return _InstancesBatch;
  22837. }());
  22838. BABYLON._InstancesBatch = _InstancesBatch;
  22839. var Mesh = /** @class */ (function (_super) {
  22840. __extends(Mesh, _super);
  22841. /**
  22842. * @constructor
  22843. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22844. * @param {Scene} scene The scene to add this mesh to.
  22845. * @param {Node} parent The parent of this mesh, if it has one
  22846. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22847. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22848. * When false, achieved by calling a clone(), also passing False.
  22849. * This will make creation of children, recursive.
  22850. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22851. */
  22852. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22853. if (scene === void 0) { scene = null; }
  22854. if (parent === void 0) { parent = null; }
  22855. if (source === void 0) { source = null; }
  22856. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22857. var _this = _super.call(this, name, scene) || this;
  22858. // Events
  22859. /**
  22860. * An event triggered before rendering the mesh
  22861. * @type {BABYLON.Observable}
  22862. */
  22863. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22864. /**
  22865. * An event triggered after rendering the mesh
  22866. * @type {BABYLON.Observable}
  22867. */
  22868. _this.onAfterRenderObservable = new BABYLON.Observable();
  22869. /**
  22870. * An event triggered before drawing the mesh
  22871. * @type {BABYLON.Observable}
  22872. */
  22873. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22874. // Members
  22875. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22876. _this.instances = new Array();
  22877. _this._LODLevels = new Array();
  22878. _this._visibleInstances = {};
  22879. _this._renderIdForInstances = new Array();
  22880. _this._batchCache = new _InstancesBatch();
  22881. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22882. // Use by builder only to know what orientation were the mesh build in.
  22883. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22884. _this.overrideMaterialSideOrientation = null;
  22885. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22886. // Will be used to save a source mesh reference, If any
  22887. _this._source = null;
  22888. scene = _this.getScene();
  22889. if (source) {
  22890. // Source mesh
  22891. _this._source = source;
  22892. // Geometry
  22893. if (source._geometry) {
  22894. source._geometry.applyToMesh(_this);
  22895. }
  22896. // Deep copy
  22897. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  22898. // Tags
  22899. if (BABYLON.Tags.HasTags(source)) {
  22900. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22901. }
  22902. _this.metadata = source.metadata;
  22903. // Parent
  22904. _this.parent = source.parent;
  22905. // Pivot
  22906. _this.setPivotMatrix(source.getPivotMatrix());
  22907. _this.id = name + "." + source.id;
  22908. // Material
  22909. _this.material = source.material;
  22910. var index;
  22911. if (!doNotCloneChildren) {
  22912. // Children
  22913. for (index = 0; index < scene.meshes.length; index++) {
  22914. var mesh = scene.meshes[index];
  22915. if (mesh.parent === source) {
  22916. // doNotCloneChildren is always going to be False
  22917. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22918. }
  22919. }
  22920. }
  22921. // Physics clone
  22922. var physicsEngine = _this.getScene().getPhysicsEngine();
  22923. if (clonePhysicsImpostor && physicsEngine) {
  22924. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22925. if (impostor) {
  22926. _this.physicsImpostor = impostor.clone(_this);
  22927. }
  22928. }
  22929. // Particles
  22930. for (index = 0; index < scene.particleSystems.length; index++) {
  22931. var system = scene.particleSystems[index];
  22932. if (system.emitter === source) {
  22933. system.clone(system.name, _this);
  22934. }
  22935. }
  22936. _this.computeWorldMatrix(true);
  22937. }
  22938. // Parent
  22939. if (parent !== null) {
  22940. _this.parent = parent;
  22941. }
  22942. return _this;
  22943. }
  22944. Object.defineProperty(Mesh, "FRONTSIDE", {
  22945. /**
  22946. * Mesh side orientation : usually the external or front surface
  22947. */
  22948. get: function () {
  22949. return Mesh._FRONTSIDE;
  22950. },
  22951. enumerable: true,
  22952. configurable: true
  22953. });
  22954. Object.defineProperty(Mesh, "BACKSIDE", {
  22955. /**
  22956. * Mesh side orientation : usually the internal or back surface
  22957. */
  22958. get: function () {
  22959. return Mesh._BACKSIDE;
  22960. },
  22961. enumerable: true,
  22962. configurable: true
  22963. });
  22964. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22965. /**
  22966. * Mesh side orientation : both internal and external or front and back surfaces
  22967. */
  22968. get: function () {
  22969. return Mesh._DOUBLESIDE;
  22970. },
  22971. enumerable: true,
  22972. configurable: true
  22973. });
  22974. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22975. /**
  22976. * Mesh side orientation : by default, `FRONTSIDE`
  22977. */
  22978. get: function () {
  22979. return Mesh._DEFAULTSIDE;
  22980. },
  22981. enumerable: true,
  22982. configurable: true
  22983. });
  22984. Object.defineProperty(Mesh, "NO_CAP", {
  22985. /**
  22986. * Mesh cap setting : no cap
  22987. */
  22988. get: function () {
  22989. return Mesh._NO_CAP;
  22990. },
  22991. enumerable: true,
  22992. configurable: true
  22993. });
  22994. Object.defineProperty(Mesh, "CAP_START", {
  22995. /**
  22996. * Mesh cap setting : one cap at the beginning of the mesh
  22997. */
  22998. get: function () {
  22999. return Mesh._CAP_START;
  23000. },
  23001. enumerable: true,
  23002. configurable: true
  23003. });
  23004. Object.defineProperty(Mesh, "CAP_END", {
  23005. /**
  23006. * Mesh cap setting : one cap at the end of the mesh
  23007. */
  23008. get: function () {
  23009. return Mesh._CAP_END;
  23010. },
  23011. enumerable: true,
  23012. configurable: true
  23013. });
  23014. Object.defineProperty(Mesh, "CAP_ALL", {
  23015. /**
  23016. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23017. */
  23018. get: function () {
  23019. return Mesh._CAP_ALL;
  23020. },
  23021. enumerable: true,
  23022. configurable: true
  23023. });
  23024. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23025. set: function (callback) {
  23026. if (this._onBeforeDrawObserver) {
  23027. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23028. }
  23029. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23030. },
  23031. enumerable: true,
  23032. configurable: true
  23033. });
  23034. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  23035. get: function () {
  23036. return this._morphTargetManager;
  23037. },
  23038. set: function (value) {
  23039. if (this._morphTargetManager === value) {
  23040. return;
  23041. }
  23042. this._morphTargetManager = value;
  23043. this._syncGeometryWithMorphTargetManager();
  23044. },
  23045. enumerable: true,
  23046. configurable: true
  23047. });
  23048. Object.defineProperty(Mesh.prototype, "source", {
  23049. get: function () {
  23050. return this._source;
  23051. },
  23052. enumerable: true,
  23053. configurable: true
  23054. });
  23055. // Methods
  23056. /**
  23057. * Returns the string "Mesh".
  23058. */
  23059. Mesh.prototype.getClassName = function () {
  23060. return "Mesh";
  23061. };
  23062. /**
  23063. * Returns a string.
  23064. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23065. */
  23066. Mesh.prototype.toString = function (fullDetails) {
  23067. var ret = _super.prototype.toString.call(this, fullDetails);
  23068. ret += ", n vertices: " + this.getTotalVertices();
  23069. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23070. if (this.animations) {
  23071. for (var i = 0; i < this.animations.length; i++) {
  23072. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23073. }
  23074. }
  23075. if (fullDetails) {
  23076. if (this._geometry) {
  23077. var ib = this.getIndices();
  23078. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23079. if (vb && ib) {
  23080. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  23081. }
  23082. }
  23083. else {
  23084. ret += ", flat shading: UNKNOWN";
  23085. }
  23086. }
  23087. return ret;
  23088. };
  23089. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23090. /**
  23091. * True if the mesh has some Levels Of Details (LOD).
  23092. * Returns a boolean.
  23093. */
  23094. get: function () {
  23095. return this._LODLevels.length > 0;
  23096. },
  23097. enumerable: true,
  23098. configurable: true
  23099. });
  23100. Mesh.prototype._sortLODLevels = function () {
  23101. this._LODLevels.sort(function (a, b) {
  23102. if (a.distance < b.distance) {
  23103. return 1;
  23104. }
  23105. if (a.distance > b.distance) {
  23106. return -1;
  23107. }
  23108. return 0;
  23109. });
  23110. };
  23111. /**
  23112. * Add a mesh as LOD level triggered at the given distance.
  23113. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23114. * @param {number} distance The distance from the center of the object to show this level
  23115. * @param {Mesh} mesh The mesh to be added as LOD level
  23116. * @return {Mesh} This mesh (for chaining)
  23117. */
  23118. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23119. if (mesh && mesh._masterMesh) {
  23120. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23121. return this;
  23122. }
  23123. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23124. this._LODLevels.push(level);
  23125. if (mesh) {
  23126. mesh._masterMesh = this;
  23127. }
  23128. this._sortLODLevels();
  23129. return this;
  23130. };
  23131. /**
  23132. * Returns the LOD level mesh at the passed distance or null if not found.
  23133. * It is related to the method `addLODLevel(distance, mesh)`.
  23134. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23135. * Returns an object Mesh or `null`.
  23136. */
  23137. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23138. for (var index = 0; index < this._LODLevels.length; index++) {
  23139. var level = this._LODLevels[index];
  23140. if (level.distance === distance) {
  23141. return level.mesh;
  23142. }
  23143. }
  23144. return null;
  23145. };
  23146. /**
  23147. * Remove a mesh from the LOD array
  23148. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23149. * @param {Mesh} mesh The mesh to be removed.
  23150. * @return {Mesh} This mesh (for chaining)
  23151. */
  23152. Mesh.prototype.removeLODLevel = function (mesh) {
  23153. for (var index = 0; index < this._LODLevels.length; index++) {
  23154. if (this._LODLevels[index].mesh === mesh) {
  23155. this._LODLevels.splice(index, 1);
  23156. if (mesh) {
  23157. mesh._masterMesh = null;
  23158. }
  23159. }
  23160. }
  23161. this._sortLODLevels();
  23162. return this;
  23163. };
  23164. /**
  23165. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23166. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23167. */
  23168. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23169. if (!this._LODLevels || this._LODLevels.length === 0) {
  23170. return this;
  23171. }
  23172. var bSphere;
  23173. if (boundingSphere) {
  23174. bSphere = boundingSphere;
  23175. }
  23176. else {
  23177. var boundingInfo = this.getBoundingInfo();
  23178. if (!boundingInfo) {
  23179. return this;
  23180. }
  23181. bSphere = boundingInfo.boundingSphere;
  23182. }
  23183. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  23184. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23185. if (this.onLODLevelSelection) {
  23186. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23187. }
  23188. return this;
  23189. }
  23190. for (var index = 0; index < this._LODLevels.length; index++) {
  23191. var level = this._LODLevels[index];
  23192. if (level.distance < distanceToCamera) {
  23193. if (level.mesh) {
  23194. level.mesh._preActivate();
  23195. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23196. }
  23197. if (this.onLODLevelSelection) {
  23198. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23199. }
  23200. return level.mesh;
  23201. }
  23202. }
  23203. if (this.onLODLevelSelection) {
  23204. this.onLODLevelSelection(distanceToCamera, this, this);
  23205. }
  23206. return this;
  23207. };
  23208. Object.defineProperty(Mesh.prototype, "geometry", {
  23209. /**
  23210. * Returns the mesh internal Geometry object.
  23211. */
  23212. get: function () {
  23213. return this._geometry;
  23214. },
  23215. enumerable: true,
  23216. configurable: true
  23217. });
  23218. /**
  23219. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23220. */
  23221. Mesh.prototype.getTotalVertices = function () {
  23222. if (!this._geometry) {
  23223. return 0;
  23224. }
  23225. return this._geometry.getTotalVertices();
  23226. };
  23227. /**
  23228. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23229. * 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.
  23230. * You can force the copy with forceCopy === true
  23231. * Returns null if the mesh has no geometry or no vertex buffer.
  23232. * Possible `kind` values :
  23233. * - BABYLON.VertexBuffer.PositionKind
  23234. * - BABYLON.VertexBuffer.UVKind
  23235. * - BABYLON.VertexBuffer.UV2Kind
  23236. * - BABYLON.VertexBuffer.UV3Kind
  23237. * - BABYLON.VertexBuffer.UV4Kind
  23238. * - BABYLON.VertexBuffer.UV5Kind
  23239. * - BABYLON.VertexBuffer.UV6Kind
  23240. * - BABYLON.VertexBuffer.ColorKind
  23241. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23242. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23243. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23244. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23245. */
  23246. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  23247. if (!this._geometry) {
  23248. return null;
  23249. }
  23250. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  23251. };
  23252. /**
  23253. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23254. * Returns `null` if the mesh has no geometry.
  23255. * Possible `kind` values :
  23256. * - BABYLON.VertexBuffer.PositionKind
  23257. * - BABYLON.VertexBuffer.UVKind
  23258. * - BABYLON.VertexBuffer.UV2Kind
  23259. * - BABYLON.VertexBuffer.UV3Kind
  23260. * - BABYLON.VertexBuffer.UV4Kind
  23261. * - BABYLON.VertexBuffer.UV5Kind
  23262. * - BABYLON.VertexBuffer.UV6Kind
  23263. * - BABYLON.VertexBuffer.ColorKind
  23264. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23265. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23266. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23267. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23268. */
  23269. Mesh.prototype.getVertexBuffer = function (kind) {
  23270. if (!this._geometry) {
  23271. return null;
  23272. }
  23273. return this._geometry.getVertexBuffer(kind);
  23274. };
  23275. /**
  23276. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23277. * Possible `kind` values :
  23278. * - BABYLON.VertexBuffer.PositionKind
  23279. * - BABYLON.VertexBuffer.UVKind
  23280. * - BABYLON.VertexBuffer.UV2Kind
  23281. * - BABYLON.VertexBuffer.UV3Kind
  23282. * - BABYLON.VertexBuffer.UV4Kind
  23283. * - BABYLON.VertexBuffer.UV5Kind
  23284. * - BABYLON.VertexBuffer.UV6Kind
  23285. * - BABYLON.VertexBuffer.ColorKind
  23286. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23287. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23288. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23289. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23290. */
  23291. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23292. if (!this._geometry) {
  23293. if (this._delayInfo) {
  23294. return this._delayInfo.indexOf(kind) !== -1;
  23295. }
  23296. return false;
  23297. }
  23298. return this._geometry.isVerticesDataPresent(kind);
  23299. };
  23300. /**
  23301. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  23302. * Possible `kind` values :
  23303. * - BABYLON.VertexBuffer.PositionKind
  23304. * - BABYLON.VertexBuffer.UVKind
  23305. * - BABYLON.VertexBuffer.UV2Kind
  23306. * - BABYLON.VertexBuffer.UV3Kind
  23307. * - BABYLON.VertexBuffer.UV4Kind
  23308. * - BABYLON.VertexBuffer.UV5Kind
  23309. * - BABYLON.VertexBuffer.UV6Kind
  23310. * - BABYLON.VertexBuffer.ColorKind
  23311. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23312. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23313. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23314. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23315. */
  23316. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  23317. if (!this._geometry) {
  23318. if (this._delayInfo) {
  23319. return this._delayInfo.indexOf(kind) !== -1;
  23320. }
  23321. return false;
  23322. }
  23323. return this._geometry.isVertexBufferUpdatable(kind);
  23324. };
  23325. /**
  23326. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  23327. * Possible `kind` values :
  23328. * - BABYLON.VertexBuffer.PositionKind
  23329. * - BABYLON.VertexBuffer.UVKind
  23330. * - BABYLON.VertexBuffer.UV2Kind
  23331. * - BABYLON.VertexBuffer.UV3Kind
  23332. * - BABYLON.VertexBuffer.UV4Kind
  23333. * - BABYLON.VertexBuffer.UV5Kind
  23334. * - BABYLON.VertexBuffer.UV6Kind
  23335. * - BABYLON.VertexBuffer.ColorKind
  23336. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23337. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23338. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23339. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23340. */
  23341. Mesh.prototype.getVerticesDataKinds = function () {
  23342. if (!this._geometry) {
  23343. var result = new Array();
  23344. if (this._delayInfo) {
  23345. this._delayInfo.forEach(function (kind, index, array) {
  23346. result.push(kind);
  23347. });
  23348. }
  23349. return result;
  23350. }
  23351. return this._geometry.getVerticesDataKinds();
  23352. };
  23353. /**
  23354. * Returns a positive integer : the total number of indices in this mesh geometry.
  23355. * Returns zero if the mesh has no geometry.
  23356. */
  23357. Mesh.prototype.getTotalIndices = function () {
  23358. if (!this._geometry) {
  23359. return 0;
  23360. }
  23361. return this._geometry.getTotalIndices();
  23362. };
  23363. /**
  23364. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  23365. * 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.
  23366. * Returns an empty array if the mesh has no geometry.
  23367. */
  23368. Mesh.prototype.getIndices = function (copyWhenShared) {
  23369. if (!this._geometry) {
  23370. return [];
  23371. }
  23372. return this._geometry.getIndices(copyWhenShared);
  23373. };
  23374. Object.defineProperty(Mesh.prototype, "isBlocked", {
  23375. get: function () {
  23376. return this._masterMesh !== null && this._masterMesh !== undefined;
  23377. },
  23378. enumerable: true,
  23379. configurable: true
  23380. });
  23381. /**
  23382. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  23383. */
  23384. Mesh.prototype.isReady = function () {
  23385. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23386. return false;
  23387. }
  23388. return _super.prototype.isReady.call(this);
  23389. };
  23390. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  23391. /**
  23392. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  23393. * This property is pertinent only for updatable parametric shapes.
  23394. */
  23395. get: function () {
  23396. return this._areNormalsFrozen;
  23397. },
  23398. enumerable: true,
  23399. configurable: true
  23400. });
  23401. /**
  23402. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23403. * It has no effect at all on other shapes.
  23404. * It prevents the mesh normals from being recomputed on next `positions` array update.
  23405. * Returns the Mesh.
  23406. */
  23407. Mesh.prototype.freezeNormals = function () {
  23408. this._areNormalsFrozen = true;
  23409. return this;
  23410. };
  23411. /**
  23412. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  23413. * It has no effect at all on other shapes.
  23414. * It reactivates the mesh normals computation if it was previously frozen.
  23415. * Returns the Mesh.
  23416. */
  23417. Mesh.prototype.unfreezeNormals = function () {
  23418. this._areNormalsFrozen = false;
  23419. return this;
  23420. };
  23421. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  23422. /**
  23423. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  23424. */
  23425. set: function (count) {
  23426. this._overridenInstanceCount = count;
  23427. },
  23428. enumerable: true,
  23429. configurable: true
  23430. });
  23431. // Methods
  23432. Mesh.prototype._preActivate = function () {
  23433. var sceneRenderId = this.getScene().getRenderId();
  23434. if (this._preActivateId === sceneRenderId) {
  23435. return this;
  23436. }
  23437. this._preActivateId = sceneRenderId;
  23438. this._visibleInstances = null;
  23439. return this;
  23440. };
  23441. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  23442. if (this._visibleInstances) {
  23443. this._visibleInstances.intermediateDefaultRenderId = renderId;
  23444. }
  23445. return this;
  23446. };
  23447. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23448. if (!this._visibleInstances) {
  23449. this._visibleInstances = {};
  23450. this._visibleInstances.defaultRenderId = renderId;
  23451. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23452. }
  23453. if (!this._visibleInstances[renderId]) {
  23454. this._visibleInstances[renderId] = new Array();
  23455. }
  23456. this._visibleInstances[renderId].push(instance);
  23457. return this;
  23458. };
  23459. /**
  23460. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23461. * This means the mesh underlying bounding box and sphere are recomputed.
  23462. * Returns the Mesh.
  23463. */
  23464. Mesh.prototype.refreshBoundingInfo = function () {
  23465. if (this._boundingInfo && this._boundingInfo.isLocked) {
  23466. return this;
  23467. }
  23468. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23469. if (data) {
  23470. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23471. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23472. }
  23473. if (this.subMeshes) {
  23474. for (var index = 0; index < this.subMeshes.length; index++) {
  23475. this.subMeshes[index].refreshBoundingInfo();
  23476. }
  23477. }
  23478. this._updateBoundingInfo();
  23479. return this;
  23480. };
  23481. Mesh.prototype._createGlobalSubMesh = function (force) {
  23482. var totalVertices = this.getTotalVertices();
  23483. if (!totalVertices || !this.getIndices()) {
  23484. return null;
  23485. }
  23486. // Check if we need to recreate the submeshes
  23487. if (this.subMeshes && this.subMeshes.length > 0) {
  23488. var ib = this.getIndices();
  23489. if (!ib) {
  23490. return null;
  23491. }
  23492. var totalIndices = ib.length;
  23493. var needToRecreate = false;
  23494. if (force) {
  23495. needToRecreate = true;
  23496. }
  23497. else {
  23498. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23499. var submesh = _a[_i];
  23500. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23501. needToRecreate = true;
  23502. break;
  23503. }
  23504. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23505. needToRecreate = true;
  23506. break;
  23507. }
  23508. }
  23509. }
  23510. if (!needToRecreate) {
  23511. return this.subMeshes[0];
  23512. }
  23513. }
  23514. this.releaseSubMeshes();
  23515. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23516. };
  23517. Mesh.prototype.subdivide = function (count) {
  23518. if (count < 1) {
  23519. return;
  23520. }
  23521. var totalIndices = this.getTotalIndices();
  23522. var subdivisionSize = (totalIndices / count) | 0;
  23523. var offset = 0;
  23524. // Ensure that subdivisionSize is a multiple of 3
  23525. while (subdivisionSize % 3 !== 0) {
  23526. subdivisionSize++;
  23527. }
  23528. this.releaseSubMeshes();
  23529. for (var index = 0; index < count; index++) {
  23530. if (offset >= totalIndices) {
  23531. break;
  23532. }
  23533. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23534. offset += subdivisionSize;
  23535. }
  23536. this.synchronizeInstances();
  23537. };
  23538. /**
  23539. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23540. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23541. * The `data` are either a numeric array either a Float32Array.
  23542. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23543. * 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).
  23544. * Note that a new underlying VertexBuffer object is created each call.
  23545. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23546. *
  23547. * Possible `kind` values :
  23548. * - BABYLON.VertexBuffer.PositionKind
  23549. * - BABYLON.VertexBuffer.UVKind
  23550. * - BABYLON.VertexBuffer.UV2Kind
  23551. * - BABYLON.VertexBuffer.UV3Kind
  23552. * - BABYLON.VertexBuffer.UV4Kind
  23553. * - BABYLON.VertexBuffer.UV5Kind
  23554. * - BABYLON.VertexBuffer.UV6Kind
  23555. * - BABYLON.VertexBuffer.ColorKind
  23556. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23557. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23558. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23559. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23560. *
  23561. * Returns the Mesh.
  23562. */
  23563. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23564. if (updatable === void 0) { updatable = false; }
  23565. if (!this._geometry) {
  23566. var vertexData = new BABYLON.VertexData();
  23567. vertexData.set(data, kind);
  23568. var scene = this.getScene();
  23569. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23570. }
  23571. else {
  23572. this._geometry.setVerticesData(kind, data, updatable, stride);
  23573. }
  23574. return this;
  23575. };
  23576. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23577. if (updatable === void 0) { updatable = true; }
  23578. var vb = this.getVertexBuffer(kind);
  23579. if (!vb || vb.isUpdatable() === updatable) {
  23580. return;
  23581. }
  23582. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23583. };
  23584. /**
  23585. * Sets the mesh VertexBuffer.
  23586. * Returns the Mesh.
  23587. */
  23588. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23589. if (!this._geometry) {
  23590. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23591. }
  23592. this._geometry.setVerticesBuffer(buffer);
  23593. return this;
  23594. };
  23595. /**
  23596. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23597. * If the mesh has no geometry, it is simply returned as it is.
  23598. * The `data` are either a numeric array either a Float32Array.
  23599. * No new underlying VertexBuffer object is created.
  23600. * 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.
  23601. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23602. *
  23603. * Possible `kind` values :
  23604. * - BABYLON.VertexBuffer.PositionKind
  23605. * - BABYLON.VertexBuffer.UVKind
  23606. * - BABYLON.VertexBuffer.UV2Kind
  23607. * - BABYLON.VertexBuffer.UV3Kind
  23608. * - BABYLON.VertexBuffer.UV4Kind
  23609. * - BABYLON.VertexBuffer.UV5Kind
  23610. * - BABYLON.VertexBuffer.UV6Kind
  23611. * - BABYLON.VertexBuffer.ColorKind
  23612. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23613. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23614. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23615. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23616. *
  23617. * Returns the Mesh.
  23618. */
  23619. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23620. if (!this._geometry) {
  23621. return this;
  23622. }
  23623. if (!makeItUnique) {
  23624. this._geometry.updateVerticesData(kind, data, updateExtends);
  23625. }
  23626. else {
  23627. this.makeGeometryUnique();
  23628. this.updateVerticesData(kind, data, updateExtends, false);
  23629. }
  23630. return this;
  23631. };
  23632. /**
  23633. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23634. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23635. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23636. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23637. * Returns the Mesh.
  23638. */
  23639. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23640. if (computeNormals === void 0) { computeNormals = true; }
  23641. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23642. if (!positions) {
  23643. return this;
  23644. }
  23645. positionFunction(positions);
  23646. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23647. if (computeNormals) {
  23648. var indices = this.getIndices();
  23649. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23650. if (!normals) {
  23651. return this;
  23652. }
  23653. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23654. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23655. }
  23656. return this;
  23657. };
  23658. /**
  23659. * Creates a un-shared specific occurence of the geometry for the mesh.
  23660. * Returns the Mesh.
  23661. */
  23662. Mesh.prototype.makeGeometryUnique = function () {
  23663. if (!this._geometry) {
  23664. return this;
  23665. }
  23666. var oldGeometry = this._geometry;
  23667. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23668. oldGeometry.releaseForMesh(this, true);
  23669. geometry.applyToMesh(this);
  23670. return this;
  23671. };
  23672. /**
  23673. * Sets the mesh indices.
  23674. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23675. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  23676. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23677. * This method creates a new index buffer each call.
  23678. * Returns the Mesh.
  23679. */
  23680. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23681. if (totalVertices === void 0) { totalVertices = null; }
  23682. if (updatable === void 0) { updatable = false; }
  23683. if (!this._geometry) {
  23684. var vertexData = new BABYLON.VertexData();
  23685. vertexData.indices = indices;
  23686. var scene = this.getScene();
  23687. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23688. }
  23689. else {
  23690. this._geometry.setIndices(indices, totalVertices, updatable);
  23691. }
  23692. return this;
  23693. };
  23694. /**
  23695. * Update the current index buffer
  23696. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23697. * Returns the Mesh.
  23698. */
  23699. Mesh.prototype.updateIndices = function (indices, offset) {
  23700. if (!this._geometry) {
  23701. return this;
  23702. }
  23703. this._geometry.updateIndices(indices, offset);
  23704. return this;
  23705. };
  23706. /**
  23707. * Invert the geometry to move from a right handed system to a left handed one.
  23708. * Returns the Mesh.
  23709. */
  23710. Mesh.prototype.toLeftHanded = function () {
  23711. if (!this._geometry) {
  23712. return this;
  23713. }
  23714. this._geometry.toLeftHanded();
  23715. return this;
  23716. };
  23717. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23718. if (!this._geometry) {
  23719. return this;
  23720. }
  23721. var engine = this.getScene().getEngine();
  23722. // Wireframe
  23723. var indexToBind;
  23724. if (this._unIndexed) {
  23725. indexToBind = null;
  23726. }
  23727. else {
  23728. switch (fillMode) {
  23729. case BABYLON.Material.PointFillMode:
  23730. indexToBind = null;
  23731. break;
  23732. case BABYLON.Material.WireFrameFillMode:
  23733. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23734. break;
  23735. default:
  23736. case BABYLON.Material.TriangleFillMode:
  23737. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23738. break;
  23739. }
  23740. }
  23741. // VBOs
  23742. this._geometry._bind(effect, indexToBind);
  23743. return this;
  23744. };
  23745. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23746. if (alternate === void 0) { alternate = false; }
  23747. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23748. return this;
  23749. }
  23750. this.onBeforeDrawObservable.notifyObservers(this);
  23751. var scene = this.getScene();
  23752. var engine = scene.getEngine();
  23753. // Draw order
  23754. switch (fillMode) {
  23755. case BABYLON.Material.PointFillMode:
  23756. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23757. break;
  23758. case BABYLON.Material.WireFrameFillMode:
  23759. if (this._unIndexed) {
  23760. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23761. }
  23762. else {
  23763. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23764. }
  23765. break;
  23766. default:
  23767. if (this._unIndexed) {
  23768. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23769. }
  23770. else {
  23771. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23772. }
  23773. }
  23774. if (scene._isAlternateRenderingEnabled && !alternate) {
  23775. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23776. if (!effect || !scene.activeCamera) {
  23777. return this;
  23778. }
  23779. scene._switchToAlternateCameraConfiguration(true);
  23780. this._effectiveMaterial.bindView(effect);
  23781. this._effectiveMaterial.bindViewProjection(effect);
  23782. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23783. this._draw(subMesh, fillMode, instancesCount, true);
  23784. engine.setViewport(scene.activeCamera.viewport);
  23785. scene._switchToAlternateCameraConfiguration(false);
  23786. this._effectiveMaterial.bindView(effect);
  23787. this._effectiveMaterial.bindViewProjection(effect);
  23788. }
  23789. return this;
  23790. };
  23791. /**
  23792. * Registers for this mesh a javascript function called just before the rendering process.
  23793. * This function is passed the current mesh.
  23794. * Return the Mesh.
  23795. */
  23796. Mesh.prototype.registerBeforeRender = function (func) {
  23797. this.onBeforeRenderObservable.add(func);
  23798. return this;
  23799. };
  23800. /**
  23801. * Disposes a previously registered javascript function called before the rendering.
  23802. * This function is passed the current mesh.
  23803. * Returns the Mesh.
  23804. */
  23805. Mesh.prototype.unregisterBeforeRender = function (func) {
  23806. this.onBeforeRenderObservable.removeCallback(func);
  23807. return this;
  23808. };
  23809. /**
  23810. * Registers for this mesh a javascript function called just after the rendering is complete.
  23811. * This function is passed the current mesh.
  23812. * Returns the Mesh.
  23813. */
  23814. Mesh.prototype.registerAfterRender = function (func) {
  23815. this.onAfterRenderObservable.add(func);
  23816. return this;
  23817. };
  23818. /**
  23819. * Disposes a previously registered javascript function called after the rendering.
  23820. * This function is passed the current mesh.
  23821. * Return the Mesh.
  23822. */
  23823. Mesh.prototype.unregisterAfterRender = function (func) {
  23824. this.onAfterRenderObservable.removeCallback(func);
  23825. return this;
  23826. };
  23827. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23828. var scene = this.getScene();
  23829. this._batchCache.mustReturn = false;
  23830. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23831. this._batchCache.visibleInstances[subMeshId] = null;
  23832. if (this._visibleInstances) {
  23833. var currentRenderId = scene.getRenderId();
  23834. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23835. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23836. var selfRenderId = this._renderId;
  23837. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23838. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23839. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23840. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23841. }
  23842. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23843. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23844. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23845. this._batchCache.mustReturn = true;
  23846. return this._batchCache;
  23847. }
  23848. if (currentRenderId !== selfRenderId) {
  23849. this._batchCache.renderSelf[subMeshId] = false;
  23850. }
  23851. }
  23852. this._renderIdForInstances[subMeshId] = currentRenderId;
  23853. }
  23854. return this._batchCache;
  23855. };
  23856. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23857. var visibleInstances = batch.visibleInstances[subMesh._id];
  23858. if (!visibleInstances) {
  23859. return this;
  23860. }
  23861. var matricesCount = visibleInstances.length + 1;
  23862. var bufferSize = matricesCount * 16 * 4;
  23863. var currentInstancesBufferSize = this._instancesBufferSize;
  23864. var instancesBuffer = this._instancesBuffer;
  23865. while (this._instancesBufferSize < bufferSize) {
  23866. this._instancesBufferSize *= 2;
  23867. }
  23868. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23869. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23870. }
  23871. var offset = 0;
  23872. var instancesCount = 0;
  23873. var world = this.getWorldMatrix();
  23874. if (batch.renderSelf[subMesh._id]) {
  23875. world.copyToArray(this._instancesData, offset);
  23876. offset += 16;
  23877. instancesCount++;
  23878. }
  23879. if (visibleInstances) {
  23880. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23881. var instance = visibleInstances[instanceIndex];
  23882. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23883. offset += 16;
  23884. instancesCount++;
  23885. }
  23886. }
  23887. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23888. if (instancesBuffer) {
  23889. instancesBuffer.dispose();
  23890. }
  23891. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23892. this._instancesBuffer = instancesBuffer;
  23893. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23894. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23895. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23896. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23897. }
  23898. else {
  23899. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23900. }
  23901. this._bind(subMesh, effect, fillMode);
  23902. this._draw(subMesh, fillMode, instancesCount);
  23903. engine.unbindInstanceAttributes();
  23904. return this;
  23905. };
  23906. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23907. var scene = this.getScene();
  23908. var engine = scene.getEngine();
  23909. if (hardwareInstancedRendering) {
  23910. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23911. }
  23912. else {
  23913. if (batch.renderSelf[subMesh._id]) {
  23914. // Draw
  23915. if (onBeforeDraw) {
  23916. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23917. }
  23918. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23919. }
  23920. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  23921. if (visibleInstancesForSubMesh) {
  23922. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  23923. var instance = visibleInstancesForSubMesh[instanceIndex];
  23924. // World
  23925. var world = instance.getWorldMatrix();
  23926. if (onBeforeDraw) {
  23927. onBeforeDraw(true, world, effectiveMaterial);
  23928. }
  23929. // Draw
  23930. this._draw(subMesh, fillMode);
  23931. }
  23932. }
  23933. }
  23934. return this;
  23935. };
  23936. /**
  23937. * Triggers the draw call for the mesh.
  23938. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23939. * Returns the Mesh.
  23940. */
  23941. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23942. this.checkOcclusionQuery();
  23943. if (this._isOccluded) {
  23944. return this;
  23945. }
  23946. var scene = this.getScene();
  23947. // Managing instances
  23948. var batch = this._getInstancesRenderList(subMesh._id);
  23949. if (batch.mustReturn) {
  23950. return this;
  23951. }
  23952. // Checking geometry state
  23953. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23954. return this;
  23955. }
  23956. this.onBeforeRenderObservable.notifyObservers(this);
  23957. var engine = scene.getEngine();
  23958. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23959. // Material
  23960. var material = subMesh.getMaterial();
  23961. if (!material) {
  23962. return this;
  23963. }
  23964. this._effectiveMaterial = material;
  23965. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23966. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  23967. return this;
  23968. }
  23969. }
  23970. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23971. return this;
  23972. }
  23973. // Alpha mode
  23974. if (enableAlphaMode) {
  23975. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  23976. }
  23977. // Outline - step 1
  23978. var savedDepthWrite = engine.getDepthWrite();
  23979. if (this.renderOutline) {
  23980. engine.setDepthWrite(false);
  23981. scene.getOutlineRenderer().render(subMesh, batch);
  23982. engine.setDepthWrite(savedDepthWrite);
  23983. }
  23984. var effect;
  23985. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23986. effect = subMesh.effect;
  23987. }
  23988. else {
  23989. effect = this._effectiveMaterial.getEffect();
  23990. }
  23991. if (!effect) {
  23992. return this;
  23993. }
  23994. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  23995. if (this._effectiveMaterial.forceDepthWrite) {
  23996. engine.setDepthWrite(true);
  23997. }
  23998. // Bind
  23999. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  24000. if (!hardwareInstancedRendering) {
  24001. this._bind(subMesh, effect, fillMode);
  24002. }
  24003. var world = this.getWorldMatrix();
  24004. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24005. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24006. }
  24007. else {
  24008. this._effectiveMaterial.bind(world, this);
  24009. }
  24010. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  24011. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  24012. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24013. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  24014. }
  24015. // Draw
  24016. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24017. // Unbind
  24018. this._effectiveMaterial.unbind();
  24019. // Outline - step 2
  24020. if (this.renderOutline && savedDepthWrite) {
  24021. engine.setDepthWrite(true);
  24022. engine.setColorWrite(false);
  24023. scene.getOutlineRenderer().render(subMesh, batch);
  24024. engine.setColorWrite(true);
  24025. }
  24026. // Overlay
  24027. if (this.renderOverlay) {
  24028. var currentMode = engine.getAlphaMode();
  24029. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24030. scene.getOutlineRenderer().render(subMesh, batch, true);
  24031. engine.setAlphaMode(currentMode);
  24032. }
  24033. this.onAfterRenderObservable.notifyObservers(this);
  24034. return this;
  24035. };
  24036. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  24037. if (isInstance) {
  24038. effectiveMaterial.bindOnlyWorldMatrix(world);
  24039. }
  24040. return this;
  24041. };
  24042. /**
  24043. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  24044. */
  24045. Mesh.prototype.getEmittedParticleSystems = function () {
  24046. var results = new Array();
  24047. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24048. var particleSystem = this.getScene().particleSystems[index];
  24049. if (particleSystem.emitter === this) {
  24050. results.push(particleSystem);
  24051. }
  24052. }
  24053. return results;
  24054. };
  24055. /**
  24056. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  24057. */
  24058. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  24059. var results = new Array();
  24060. var descendants = this.getDescendants();
  24061. descendants.push(this);
  24062. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24063. var particleSystem = this.getScene().particleSystems[index];
  24064. var emitter = particleSystem.emitter;
  24065. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  24066. results.push(particleSystem);
  24067. }
  24068. }
  24069. return results;
  24070. };
  24071. Mesh.prototype._checkDelayState = function () {
  24072. var scene = this.getScene();
  24073. if (this._geometry) {
  24074. this._geometry.load(scene);
  24075. }
  24076. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24077. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24078. this._queueLoad(this, scene);
  24079. }
  24080. return this;
  24081. };
  24082. Mesh.prototype._queueLoad = function (mesh, scene) {
  24083. var _this = this;
  24084. scene._addPendingData(mesh);
  24085. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  24086. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24087. if (data instanceof ArrayBuffer) {
  24088. _this._delayLoadingFunction(data, _this);
  24089. }
  24090. else {
  24091. _this._delayLoadingFunction(JSON.parse(data), _this);
  24092. }
  24093. _this.instances.forEach(function (instance) {
  24094. instance._syncSubMeshes();
  24095. });
  24096. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24097. scene._removePendingData(_this);
  24098. }, function () { }, scene.database, getBinaryData);
  24099. return this;
  24100. };
  24101. /**
  24102. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  24103. */
  24104. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  24105. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24106. return false;
  24107. }
  24108. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  24109. return false;
  24110. }
  24111. this._checkDelayState();
  24112. return true;
  24113. };
  24114. /**
  24115. * Sets the mesh material by the material or multiMaterial `id` property.
  24116. * The material `id` is a string identifying the material or the multiMaterial.
  24117. * This method returns the Mesh.
  24118. */
  24119. Mesh.prototype.setMaterialByID = function (id) {
  24120. var materials = this.getScene().materials;
  24121. var index;
  24122. for (index = materials.length - 1; index > -1; index--) {
  24123. if (materials[index].id === id) {
  24124. this.material = materials[index];
  24125. return this;
  24126. }
  24127. }
  24128. // Multi
  24129. var multiMaterials = this.getScene().multiMaterials;
  24130. for (index = multiMaterials.length - 1; index > -1; index--) {
  24131. if (multiMaterials[index].id === id) {
  24132. this.material = multiMaterials[index];
  24133. return this;
  24134. }
  24135. }
  24136. return this;
  24137. };
  24138. /**
  24139. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  24140. */
  24141. Mesh.prototype.getAnimatables = function () {
  24142. var results = new Array();
  24143. if (this.material) {
  24144. results.push(this.material);
  24145. }
  24146. if (this.skeleton) {
  24147. results.push(this.skeleton);
  24148. }
  24149. return results;
  24150. };
  24151. /**
  24152. * Modifies the mesh geometry according to the passed transformation matrix.
  24153. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  24154. * The mesh normals are modified accordingly the same transformation.
  24155. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24156. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24157. * Returns the Mesh.
  24158. */
  24159. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  24160. // Position
  24161. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24162. return this;
  24163. }
  24164. var submeshes = this.subMeshes.splice(0);
  24165. this._resetPointsArrayCache();
  24166. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24167. var temp = new Array();
  24168. var index;
  24169. for (index = 0; index < data.length; index += 3) {
  24170. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24171. }
  24172. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24173. // Normals
  24174. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24175. return this;
  24176. }
  24177. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24178. temp = [];
  24179. for (index = 0; index < data.length; index += 3) {
  24180. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24181. }
  24182. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24183. // flip faces?
  24184. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24185. this.flipFaces();
  24186. }
  24187. // Restore submeshes
  24188. this.releaseSubMeshes();
  24189. this.subMeshes = submeshes;
  24190. return this;
  24191. };
  24192. /**
  24193. * Modifies the mesh geometry according to its own current World Matrix.
  24194. * The mesh World Matrix is then reset.
  24195. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24196. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24197. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24198. * Returns the Mesh.
  24199. */
  24200. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24201. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24202. this.scaling.copyFromFloats(1, 1, 1);
  24203. this.position.copyFromFloats(0, 0, 0);
  24204. this.rotation.copyFromFloats(0, 0, 0);
  24205. //only if quaternion is already set
  24206. if (this.rotationQuaternion) {
  24207. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24208. }
  24209. this._worldMatrix = BABYLON.Matrix.Identity();
  24210. return this;
  24211. };
  24212. Object.defineProperty(Mesh.prototype, "_positions", {
  24213. // Cache
  24214. get: function () {
  24215. if (this._geometry) {
  24216. return this._geometry._positions;
  24217. }
  24218. return null;
  24219. },
  24220. enumerable: true,
  24221. configurable: true
  24222. });
  24223. Mesh.prototype._resetPointsArrayCache = function () {
  24224. if (this._geometry) {
  24225. this._geometry._resetPointsArrayCache();
  24226. }
  24227. return this;
  24228. };
  24229. Mesh.prototype._generatePointsArray = function () {
  24230. if (this._geometry) {
  24231. return this._geometry._generatePointsArray();
  24232. }
  24233. return false;
  24234. };
  24235. /**
  24236. * Returns a new Mesh object generated from the current mesh properties.
  24237. * This method must not get confused with createInstance().
  24238. * The parameter `name` is a string, the name given to the new mesh.
  24239. * The optional parameter `newParent` can be any Node object (default `null`).
  24240. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24241. * 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.
  24242. */
  24243. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24244. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24245. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24246. };
  24247. /**
  24248. * Disposes the mesh.
  24249. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  24250. */
  24251. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  24252. var _this = this;
  24253. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  24254. this.morphTargetManager = null;
  24255. if (this._geometry) {
  24256. this._geometry.releaseForMesh(this, true);
  24257. }
  24258. // Sources
  24259. var meshes = this.getScene().meshes;
  24260. meshes.forEach(function (mesh) {
  24261. if (mesh._source && mesh._source === _this) {
  24262. mesh._source = null;
  24263. }
  24264. });
  24265. this._source = null;
  24266. // Instances
  24267. if (this._instancesBuffer) {
  24268. this._instancesBuffer.dispose();
  24269. this._instancesBuffer = null;
  24270. }
  24271. while (this.instances.length) {
  24272. this.instances[0].dispose();
  24273. }
  24274. // Highlight layers.
  24275. var highlightLayers = this.getScene().highlightLayers;
  24276. for (var i = 0; i < highlightLayers.length; i++) {
  24277. var highlightLayer = highlightLayers[i];
  24278. if (highlightLayer) {
  24279. highlightLayer.removeMesh(this);
  24280. highlightLayer.removeExcludedMesh(this);
  24281. }
  24282. }
  24283. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  24284. };
  24285. /**
  24286. * Modifies the mesh geometry according to a displacement map.
  24287. * 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.
  24288. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24289. * This method returns nothing.
  24290. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  24291. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24292. * 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.
  24293. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24294. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24295. *
  24296. * Returns the Mesh.
  24297. */
  24298. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  24299. var _this = this;
  24300. var scene = this.getScene();
  24301. var onload = function (img) {
  24302. // Getting height map data
  24303. var canvas = document.createElement("canvas");
  24304. var context = canvas.getContext("2d");
  24305. var heightMapWidth = img.width;
  24306. var heightMapHeight = img.height;
  24307. canvas.width = heightMapWidth;
  24308. canvas.height = heightMapHeight;
  24309. context.drawImage(img, 0, 0);
  24310. // Create VertexData from map data
  24311. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  24312. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  24313. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  24314. //execute success callback, if set
  24315. if (onSuccess) {
  24316. onSuccess(_this);
  24317. }
  24318. };
  24319. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  24320. return this;
  24321. };
  24322. /**
  24323. * Modifies the mesh geometry according to a displacementMap buffer.
  24324. * 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.
  24325. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  24326. * This method returns nothing.
  24327. * 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.
  24328. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  24329. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  24330. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  24331. * The parameter `uvScale` is an optional vector2 used to scale UV.
  24332. *
  24333. * Returns the Mesh.
  24334. */
  24335. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  24336. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  24337. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  24338. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24339. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  24340. return this;
  24341. }
  24342. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24343. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24344. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24345. var position = BABYLON.Vector3.Zero();
  24346. var normal = BABYLON.Vector3.Zero();
  24347. var uv = BABYLON.Vector2.Zero();
  24348. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  24349. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  24350. for (var index = 0; index < positions.length; index += 3) {
  24351. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  24352. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  24353. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  24354. // Compute height
  24355. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  24356. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  24357. var pos = (u + v * heightMapWidth) * 4;
  24358. var r = buffer[pos] / 255.0;
  24359. var g = buffer[pos + 1] / 255.0;
  24360. var b = buffer[pos + 2] / 255.0;
  24361. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24362. normal.normalize();
  24363. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  24364. position = position.add(normal);
  24365. position.toArray(positions, index);
  24366. }
  24367. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  24368. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  24369. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24370. return this;
  24371. };
  24372. /**
  24373. * Modify the mesh to get a flat shading rendering.
  24374. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  24375. * This method returns the Mesh.
  24376. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  24377. */
  24378. Mesh.prototype.convertToFlatShadedMesh = function () {
  24379. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  24380. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24381. var kinds = this.getVerticesDataKinds();
  24382. var vbs = {};
  24383. var data = {};
  24384. var newdata = {};
  24385. var updatableNormals = false;
  24386. var kindIndex;
  24387. var kind;
  24388. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24389. kind = kinds[kindIndex];
  24390. var vertexBuffer = this.getVertexBuffer(kind);
  24391. if (kind === BABYLON.VertexBuffer.NormalKind) {
  24392. updatableNormals = vertexBuffer.isUpdatable();
  24393. kinds.splice(kindIndex, 1);
  24394. kindIndex--;
  24395. continue;
  24396. }
  24397. vbs[kind] = vertexBuffer;
  24398. data[kind] = vbs[kind].getData();
  24399. newdata[kind] = [];
  24400. }
  24401. // Save previous submeshes
  24402. var previousSubmeshes = this.subMeshes.slice(0);
  24403. var indices = this.getIndices();
  24404. var totalIndices = this.getTotalIndices();
  24405. // Generating unique vertices per face
  24406. var index;
  24407. for (index = 0; index < totalIndices; index++) {
  24408. var vertexIndex = indices[index];
  24409. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24410. kind = kinds[kindIndex];
  24411. var stride = vbs[kind].getStrideSize();
  24412. for (var offset = 0; offset < stride; offset++) {
  24413. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24414. }
  24415. }
  24416. }
  24417. // Updating faces & normal
  24418. var normals = [];
  24419. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  24420. for (index = 0; index < totalIndices; index += 3) {
  24421. indices[index] = index;
  24422. indices[index + 1] = index + 1;
  24423. indices[index + 2] = index + 2;
  24424. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  24425. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  24426. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  24427. var p1p2 = p1.subtract(p2);
  24428. var p3p2 = p3.subtract(p2);
  24429. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  24430. // Store same normals for every vertex
  24431. for (var localIndex = 0; localIndex < 3; localIndex++) {
  24432. normals.push(normal.x);
  24433. normals.push(normal.y);
  24434. normals.push(normal.z);
  24435. }
  24436. }
  24437. this.setIndices(indices);
  24438. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  24439. // Updating vertex buffers
  24440. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24441. kind = kinds[kindIndex];
  24442. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24443. }
  24444. // Updating submeshes
  24445. this.releaseSubMeshes();
  24446. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24447. var previousOne = previousSubmeshes[submeshIndex];
  24448. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24449. }
  24450. this.synchronizeInstances();
  24451. return this;
  24452. };
  24453. /**
  24454. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24455. * In other words, more vertices, no more indices and a single bigger VBO.
  24456. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24457. * Returns the Mesh.
  24458. */
  24459. Mesh.prototype.convertToUnIndexedMesh = function () {
  24460. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24461. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24462. var kinds = this.getVerticesDataKinds();
  24463. var vbs = {};
  24464. var data = {};
  24465. var newdata = {};
  24466. var kindIndex;
  24467. var kind;
  24468. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24469. kind = kinds[kindIndex];
  24470. var vertexBuffer = this.getVertexBuffer(kind);
  24471. vbs[kind] = vertexBuffer;
  24472. data[kind] = vbs[kind].getData();
  24473. newdata[kind] = [];
  24474. }
  24475. // Save previous submeshes
  24476. var previousSubmeshes = this.subMeshes.slice(0);
  24477. var indices = this.getIndices();
  24478. var totalIndices = this.getTotalIndices();
  24479. // Generating unique vertices per face
  24480. var index;
  24481. for (index = 0; index < totalIndices; index++) {
  24482. var vertexIndex = indices[index];
  24483. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24484. kind = kinds[kindIndex];
  24485. var stride = vbs[kind].getStrideSize();
  24486. for (var offset = 0; offset < stride; offset++) {
  24487. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24488. }
  24489. }
  24490. }
  24491. // Updating indices
  24492. for (index = 0; index < totalIndices; index += 3) {
  24493. indices[index] = index;
  24494. indices[index + 1] = index + 1;
  24495. indices[index + 2] = index + 2;
  24496. }
  24497. this.setIndices(indices);
  24498. // Updating vertex buffers
  24499. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24500. kind = kinds[kindIndex];
  24501. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24502. }
  24503. // Updating submeshes
  24504. this.releaseSubMeshes();
  24505. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24506. var previousOne = previousSubmeshes[submeshIndex];
  24507. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24508. }
  24509. this._unIndexed = true;
  24510. this.synchronizeInstances();
  24511. return this;
  24512. };
  24513. /**
  24514. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24515. * This method returns the Mesh.
  24516. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24517. */
  24518. Mesh.prototype.flipFaces = function (flipNormals) {
  24519. if (flipNormals === void 0) { flipNormals = false; }
  24520. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24521. var i;
  24522. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24523. for (i = 0; i < vertex_data.normals.length; i++) {
  24524. vertex_data.normals[i] *= -1;
  24525. }
  24526. }
  24527. if (vertex_data.indices) {
  24528. var temp;
  24529. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24530. // reassign indices
  24531. temp = vertex_data.indices[i + 1];
  24532. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24533. vertex_data.indices[i + 2] = temp;
  24534. }
  24535. }
  24536. vertex_data.applyToMesh(this);
  24537. return this;
  24538. };
  24539. // Instances
  24540. /**
  24541. * Creates a new InstancedMesh object from the mesh model.
  24542. * An instance shares the same properties and the same material than its model.
  24543. * Only these properties of each instance can then be set individually :
  24544. * - position
  24545. * - rotation
  24546. * - rotationQuaternion
  24547. * - setPivotMatrix
  24548. * - scaling
  24549. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24550. * Warning : this method is not supported for Line mesh and LineSystem
  24551. */
  24552. Mesh.prototype.createInstance = function (name) {
  24553. return new BABYLON.InstancedMesh(name, this);
  24554. };
  24555. /**
  24556. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24557. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24558. * This method returns the Mesh.
  24559. */
  24560. Mesh.prototype.synchronizeInstances = function () {
  24561. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24562. var instance = this.instances[instanceIndex];
  24563. instance._syncSubMeshes();
  24564. }
  24565. return this;
  24566. };
  24567. /**
  24568. * Simplify the mesh according to the given array of settings.
  24569. * Function will return immediately and will simplify async. It returns the Mesh.
  24570. * @param settings a collection of simplification settings.
  24571. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24572. * @param type the type of simplification to run.
  24573. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24574. */
  24575. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24576. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24577. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24578. this.getScene().simplificationQueue.addTask({
  24579. settings: settings,
  24580. parallelProcessing: parallelProcessing,
  24581. mesh: this,
  24582. simplificationType: simplificationType,
  24583. successCallback: successCallback
  24584. });
  24585. return this;
  24586. };
  24587. /**
  24588. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24589. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24590. * This should be used together with the simplification to avoid disappearing triangles.
  24591. * Returns the Mesh.
  24592. * @param successCallback an optional success callback to be called after the optimization finished.
  24593. */
  24594. Mesh.prototype.optimizeIndices = function (successCallback) {
  24595. var _this = this;
  24596. var indices = this.getIndices();
  24597. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24598. if (!positions || !indices) {
  24599. return this;
  24600. }
  24601. var vectorPositions = new Array();
  24602. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24603. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24604. }
  24605. var dupes = new Array();
  24606. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24607. var realPos = vectorPositions.length - 1 - iteration;
  24608. var testedPosition = vectorPositions[realPos];
  24609. for (var j = 0; j < realPos; ++j) {
  24610. var againstPosition = vectorPositions[j];
  24611. if (testedPosition.equals(againstPosition)) {
  24612. dupes[realPos] = j;
  24613. break;
  24614. }
  24615. }
  24616. }, function () {
  24617. for (var i = 0; i < indices.length; ++i) {
  24618. indices[i] = dupes[indices[i]] || indices[i];
  24619. }
  24620. //indices are now reordered
  24621. var originalSubMeshes = _this.subMeshes.slice(0);
  24622. _this.setIndices(indices);
  24623. _this.subMeshes = originalSubMeshes;
  24624. if (successCallback) {
  24625. successCallback(_this);
  24626. }
  24627. });
  24628. return this;
  24629. };
  24630. Mesh.prototype.serialize = function (serializationObject) {
  24631. serializationObject.name = this.name;
  24632. serializationObject.id = this.id;
  24633. serializationObject.type = this.getClassName();
  24634. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24635. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24636. }
  24637. serializationObject.position = this.position.asArray();
  24638. if (this.rotationQuaternion) {
  24639. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24640. }
  24641. else if (this.rotation) {
  24642. serializationObject.rotation = this.rotation.asArray();
  24643. }
  24644. serializationObject.scaling = this.scaling.asArray();
  24645. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24646. serializationObject.isEnabled = this.isEnabled();
  24647. serializationObject.isVisible = this.isVisible;
  24648. serializationObject.infiniteDistance = this.infiniteDistance;
  24649. serializationObject.pickable = this.isPickable;
  24650. serializationObject.receiveShadows = this.receiveShadows;
  24651. serializationObject.billboardMode = this.billboardMode;
  24652. serializationObject.visibility = this.visibility;
  24653. serializationObject.checkCollisions = this.checkCollisions;
  24654. serializationObject.isBlocker = this.isBlocker;
  24655. // Parent
  24656. if (this.parent) {
  24657. serializationObject.parentId = this.parent.id;
  24658. }
  24659. // Geometry
  24660. var geometry = this._geometry;
  24661. if (geometry) {
  24662. var geometryId = geometry.id;
  24663. serializationObject.geometryId = geometryId;
  24664. // SubMeshes
  24665. serializationObject.subMeshes = [];
  24666. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24667. var subMesh = this.subMeshes[subIndex];
  24668. serializationObject.subMeshes.push({
  24669. materialIndex: subMesh.materialIndex,
  24670. verticesStart: subMesh.verticesStart,
  24671. verticesCount: subMesh.verticesCount,
  24672. indexStart: subMesh.indexStart,
  24673. indexCount: subMesh.indexCount
  24674. });
  24675. }
  24676. }
  24677. // Material
  24678. if (this.material) {
  24679. serializationObject.materialId = this.material.id;
  24680. }
  24681. else {
  24682. this.material = null;
  24683. }
  24684. // Morph targets
  24685. if (this.morphTargetManager) {
  24686. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24687. }
  24688. // Skeleton
  24689. if (this.skeleton) {
  24690. serializationObject.skeletonId = this.skeleton.id;
  24691. }
  24692. // Physics
  24693. //TODO implement correct serialization for physics impostors.
  24694. var impostor = this.getPhysicsImpostor();
  24695. if (impostor) {
  24696. serializationObject.physicsMass = impostor.getParam("mass");
  24697. serializationObject.physicsFriction = impostor.getParam("friction");
  24698. serializationObject.physicsRestitution = impostor.getParam("mass");
  24699. serializationObject.physicsImpostor = impostor.type;
  24700. }
  24701. // Metadata
  24702. if (this.metadata) {
  24703. serializationObject.metadata = this.metadata;
  24704. }
  24705. // Instances
  24706. serializationObject.instances = [];
  24707. for (var index = 0; index < this.instances.length; index++) {
  24708. var instance = this.instances[index];
  24709. var serializationInstance = {
  24710. name: instance.name,
  24711. position: instance.position.asArray(),
  24712. scaling: instance.scaling.asArray()
  24713. };
  24714. if (instance.rotationQuaternion) {
  24715. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24716. }
  24717. else if (instance.rotation) {
  24718. serializationInstance.rotation = instance.rotation.asArray();
  24719. }
  24720. serializationObject.instances.push(serializationInstance);
  24721. // Animations
  24722. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24723. serializationInstance.ranges = instance.serializeAnimationRanges();
  24724. }
  24725. //
  24726. // Animations
  24727. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24728. serializationObject.ranges = this.serializeAnimationRanges();
  24729. // Layer mask
  24730. serializationObject.layerMask = this.layerMask;
  24731. // Alpha
  24732. serializationObject.alphaIndex = this.alphaIndex;
  24733. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24734. // Overlay
  24735. serializationObject.overlayAlpha = this.overlayAlpha;
  24736. serializationObject.overlayColor = this.overlayColor.asArray();
  24737. serializationObject.renderOverlay = this.renderOverlay;
  24738. // Fog
  24739. serializationObject.applyFog = this.applyFog;
  24740. // Action Manager
  24741. if (this.actionManager) {
  24742. serializationObject.actions = this.actionManager.serialize(this.name);
  24743. }
  24744. };
  24745. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24746. if (!this.geometry) {
  24747. return;
  24748. }
  24749. this._markSubMeshesAsAttributesDirty();
  24750. var morphTargetManager = this._morphTargetManager;
  24751. if (morphTargetManager && morphTargetManager.vertexCount) {
  24752. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24753. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24754. this.morphTargetManager = null;
  24755. return;
  24756. }
  24757. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24758. var morphTarget = morphTargetManager.getActiveTarget(index);
  24759. var positions = morphTarget.getPositions();
  24760. if (!positions) {
  24761. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  24762. return;
  24763. }
  24764. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  24765. var normals = morphTarget.getNormals();
  24766. if (normals) {
  24767. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  24768. }
  24769. var tangents = morphTarget.getTangents();
  24770. if (tangents) {
  24771. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  24772. }
  24773. }
  24774. }
  24775. else {
  24776. var index = 0;
  24777. // Positions
  24778. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24779. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24780. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24781. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24782. }
  24783. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24784. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24785. }
  24786. index++;
  24787. }
  24788. }
  24789. };
  24790. // Statics
  24791. /**
  24792. * Returns a new Mesh object parsed from the source provided.
  24793. * The parameter `parsedMesh` is the source.
  24794. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24795. */
  24796. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24797. var mesh;
  24798. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24799. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24800. }
  24801. else {
  24802. mesh = new Mesh(parsedMesh.name, scene);
  24803. }
  24804. mesh.id = parsedMesh.id;
  24805. if (BABYLON.Tags) {
  24806. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24807. }
  24808. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24809. if (parsedMesh.metadata !== undefined) {
  24810. mesh.metadata = parsedMesh.metadata;
  24811. }
  24812. if (parsedMesh.rotationQuaternion) {
  24813. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24814. }
  24815. else if (parsedMesh.rotation) {
  24816. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24817. }
  24818. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24819. if (parsedMesh.localMatrix) {
  24820. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24821. }
  24822. else if (parsedMesh.pivotMatrix) {
  24823. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24824. }
  24825. mesh.setEnabled(parsedMesh.isEnabled);
  24826. mesh.isVisible = parsedMesh.isVisible;
  24827. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24828. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24829. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24830. if (parsedMesh.applyFog !== undefined) {
  24831. mesh.applyFog = parsedMesh.applyFog;
  24832. }
  24833. if (parsedMesh.pickable !== undefined) {
  24834. mesh.isPickable = parsedMesh.pickable;
  24835. }
  24836. if (parsedMesh.alphaIndex !== undefined) {
  24837. mesh.alphaIndex = parsedMesh.alphaIndex;
  24838. }
  24839. mesh.receiveShadows = parsedMesh.receiveShadows;
  24840. mesh.billboardMode = parsedMesh.billboardMode;
  24841. if (parsedMesh.visibility !== undefined) {
  24842. mesh.visibility = parsedMesh.visibility;
  24843. }
  24844. mesh.checkCollisions = parsedMesh.checkCollisions;
  24845. if (parsedMesh.isBlocker !== undefined) {
  24846. mesh.isBlocker = parsedMesh.isBlocker;
  24847. }
  24848. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24849. // freezeWorldMatrix
  24850. if (parsedMesh.freezeWorldMatrix) {
  24851. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24852. }
  24853. // Parent
  24854. if (parsedMesh.parentId) {
  24855. mesh._waitingParentId = parsedMesh.parentId;
  24856. }
  24857. // Actions
  24858. if (parsedMesh.actions !== undefined) {
  24859. mesh._waitingActions = parsedMesh.actions;
  24860. }
  24861. // Overlay
  24862. if (parsedMesh.overlayAlpha !== undefined) {
  24863. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24864. }
  24865. if (parsedMesh.overlayColor !== undefined) {
  24866. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24867. }
  24868. if (parsedMesh.renderOverlay !== undefined) {
  24869. mesh.renderOverlay = parsedMesh.renderOverlay;
  24870. }
  24871. // Geometry
  24872. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24873. if (parsedMesh.delayLoadingFile) {
  24874. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24875. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24876. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24877. if (parsedMesh._binaryInfo) {
  24878. mesh._binaryInfo = parsedMesh._binaryInfo;
  24879. }
  24880. mesh._delayInfo = [];
  24881. if (parsedMesh.hasUVs) {
  24882. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24883. }
  24884. if (parsedMesh.hasUVs2) {
  24885. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24886. }
  24887. if (parsedMesh.hasUVs3) {
  24888. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24889. }
  24890. if (parsedMesh.hasUVs4) {
  24891. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24892. }
  24893. if (parsedMesh.hasUVs5) {
  24894. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24895. }
  24896. if (parsedMesh.hasUVs6) {
  24897. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24898. }
  24899. if (parsedMesh.hasColors) {
  24900. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24901. }
  24902. if (parsedMesh.hasMatricesIndices) {
  24903. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24904. }
  24905. if (parsedMesh.hasMatricesWeights) {
  24906. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24907. }
  24908. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24909. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24910. mesh._checkDelayState();
  24911. }
  24912. }
  24913. else {
  24914. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24915. }
  24916. // Material
  24917. if (parsedMesh.materialId) {
  24918. mesh.setMaterialByID(parsedMesh.materialId);
  24919. }
  24920. else {
  24921. mesh.material = null;
  24922. }
  24923. // Morph targets
  24924. if (parsedMesh.morphTargetManagerId > -1) {
  24925. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  24926. }
  24927. // Skeleton
  24928. if (parsedMesh.skeletonId > -1) {
  24929. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24930. if (parsedMesh.numBoneInfluencers) {
  24931. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24932. }
  24933. }
  24934. // Animations
  24935. if (parsedMesh.animations) {
  24936. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24937. var parsedAnimation = parsedMesh.animations[animationIndex];
  24938. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24939. }
  24940. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24941. }
  24942. if (parsedMesh.autoAnimate) {
  24943. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24944. }
  24945. // Layer Mask
  24946. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24947. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24948. }
  24949. else {
  24950. mesh.layerMask = 0x0FFFFFFF;
  24951. }
  24952. // Physics
  24953. if (parsedMesh.physicsImpostor) {
  24954. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24955. mass: parsedMesh.physicsMass,
  24956. friction: parsedMesh.physicsFriction,
  24957. restitution: parsedMesh.physicsRestitution
  24958. }, scene);
  24959. }
  24960. // Instances
  24961. if (parsedMesh.instances) {
  24962. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24963. var parsedInstance = parsedMesh.instances[index];
  24964. var instance = mesh.createInstance(parsedInstance.name);
  24965. if (BABYLON.Tags) {
  24966. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24967. }
  24968. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24969. if (parsedInstance.parentId) {
  24970. instance._waitingParentId = parsedInstance.parentId;
  24971. }
  24972. if (parsedInstance.rotationQuaternion) {
  24973. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24974. }
  24975. else if (parsedInstance.rotation) {
  24976. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24977. }
  24978. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24979. instance.checkCollisions = mesh.checkCollisions;
  24980. if (parsedMesh.animations) {
  24981. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24982. parsedAnimation = parsedMesh.animations[animationIndex];
  24983. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24984. }
  24985. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24986. }
  24987. }
  24988. }
  24989. return mesh;
  24990. };
  24991. /**
  24992. * Creates a ribbon mesh.
  24993. * Please consider using the same method from the MeshBuilder class instead.
  24994. * 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.
  24995. *
  24996. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24997. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24998. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24999. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25000. * 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.
  25001. * 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.
  25002. * 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
  25003. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25004. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25005. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25006. */
  25007. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25008. if (closeArray === void 0) { closeArray = false; }
  25009. if (updatable === void 0) { updatable = false; }
  25010. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25011. pathArray: pathArray,
  25012. closeArray: closeArray,
  25013. closePath: closePath,
  25014. offset: offset,
  25015. updatable: updatable,
  25016. sideOrientation: sideOrientation,
  25017. instance: instance
  25018. }, scene);
  25019. };
  25020. /**
  25021. * Creates a plane polygonal mesh. By default, this is a disc.
  25022. * Please consider using the same method from the MeshBuilder class instead.
  25023. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25024. * 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.
  25025. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25026. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25028. */
  25029. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25030. if (scene === void 0) { scene = null; }
  25031. var options = {
  25032. radius: radius,
  25033. tessellation: tessellation,
  25034. sideOrientation: sideOrientation,
  25035. updatable: updatable
  25036. };
  25037. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25038. };
  25039. /**
  25040. * Creates a box mesh.
  25041. * Please consider using the same method from the MeshBuilder class instead.
  25042. * The parameter `size` sets the size (float) of each box side (default 1).
  25043. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25044. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25046. */
  25047. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  25048. if (scene === void 0) { scene = null; }
  25049. var options = {
  25050. size: size,
  25051. sideOrientation: sideOrientation,
  25052. updatable: updatable
  25053. };
  25054. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  25055. };
  25056. /**
  25057. * Creates a sphere mesh.
  25058. * Please consider using the same method from the MeshBuilder class instead.
  25059. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25060. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25061. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25062. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25064. */
  25065. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  25066. var options = {
  25067. segments: segments,
  25068. diameterX: diameter,
  25069. diameterY: diameter,
  25070. diameterZ: diameter,
  25071. sideOrientation: sideOrientation,
  25072. updatable: updatable
  25073. };
  25074. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  25075. };
  25076. /**
  25077. * Creates a cylinder or a cone mesh.
  25078. * Please consider using the same method from the MeshBuilder class instead.
  25079. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25080. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25081. * 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.
  25082. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25083. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25084. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25085. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25086. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25087. */
  25088. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  25089. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  25090. if (scene !== undefined) {
  25091. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  25092. updatable = scene;
  25093. }
  25094. scene = subdivisions;
  25095. subdivisions = 1;
  25096. }
  25097. var options = {
  25098. height: height,
  25099. diameterTop: diameterTop,
  25100. diameterBottom: diameterBottom,
  25101. tessellation: tessellation,
  25102. subdivisions: subdivisions,
  25103. sideOrientation: sideOrientation,
  25104. updatable: updatable
  25105. };
  25106. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  25107. };
  25108. // Torus (Code from SharpDX.org)
  25109. /**
  25110. * Creates a torus mesh.
  25111. * Please consider using the same method from the MeshBuilder class instead.
  25112. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25113. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25114. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25115. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25116. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25117. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25118. */
  25119. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  25120. var options = {
  25121. diameter: diameter,
  25122. thickness: thickness,
  25123. tessellation: tessellation,
  25124. sideOrientation: sideOrientation,
  25125. updatable: updatable
  25126. };
  25127. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  25128. };
  25129. /**
  25130. * Creates a torus knot mesh.
  25131. * Please consider using the same method from the MeshBuilder class instead.
  25132. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25133. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25134. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25135. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25136. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25137. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25138. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25139. */
  25140. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  25141. var options = {
  25142. radius: radius,
  25143. tube: tube,
  25144. radialSegments: radialSegments,
  25145. tubularSegments: tubularSegments,
  25146. p: p,
  25147. q: q,
  25148. sideOrientation: sideOrientation,
  25149. updatable: updatable
  25150. };
  25151. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  25152. };
  25153. /**
  25154. * Creates a line mesh.
  25155. * Please consider using the same method from the MeshBuilder class instead.
  25156. * 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.
  25157. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25158. * The parameter `points` is an array successive Vector3.
  25159. * 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
  25160. * When updating an instance, remember that only point positions can change, not the number of points.
  25161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25162. */
  25163. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  25164. if (scene === void 0) { scene = null; }
  25165. if (updatable === void 0) { updatable = false; }
  25166. if (instance === void 0) { instance = null; }
  25167. var options = {
  25168. points: points,
  25169. updatable: updatable,
  25170. instance: instance
  25171. };
  25172. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  25173. };
  25174. /**
  25175. * Creates a dashed line mesh.
  25176. * Please consider using the same method from the MeshBuilder class instead.
  25177. * 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.
  25178. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25179. * The parameter `points` is an array successive Vector3.
  25180. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25181. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25182. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25183. * 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
  25184. * When updating an instance, remember that only point positions can change, not the number of points.
  25185. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25186. */
  25187. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  25188. if (scene === void 0) { scene = null; }
  25189. var options = {
  25190. points: points,
  25191. dashSize: dashSize,
  25192. gapSize: gapSize,
  25193. dashNb: dashNb,
  25194. updatable: updatable,
  25195. instance: instance
  25196. };
  25197. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  25198. };
  25199. /**
  25200. * Creates a polygon mesh.
  25201. * Please consider using the same method from the MeshBuilder class instead.
  25202. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  25203. * 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.
  25204. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25205. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25206. * Remember you can only change the shape positions, not their number when updating a polygon.
  25207. */
  25208. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  25209. var options = {
  25210. shape: shape,
  25211. holes: holes,
  25212. updatable: updatable,
  25213. sideOrientation: sideOrientation
  25214. };
  25215. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  25216. };
  25217. /**
  25218. * Creates an extruded polygon mesh, with depth in the Y direction.
  25219. * Please consider using the same method from the MeshBuilder class instead.
  25220. */
  25221. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  25222. var options = {
  25223. shape: shape,
  25224. holes: holes,
  25225. depth: depth,
  25226. updatable: updatable,
  25227. sideOrientation: sideOrientation
  25228. };
  25229. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  25230. };
  25231. /**
  25232. * Creates an extruded shape mesh.
  25233. * 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.
  25234. * Please consider using the same method from the MeshBuilder class instead.
  25235. *
  25236. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25237. * 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
  25238. * extruded along the Z axis.
  25239. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25240. * 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.
  25241. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25242. * 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
  25243. * 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
  25244. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25245. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25246. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25247. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25248. */
  25249. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  25250. if (scene === void 0) { scene = null; }
  25251. var options = {
  25252. shape: shape,
  25253. path: path,
  25254. scale: scale,
  25255. rotation: rotation,
  25256. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25257. sideOrientation: sideOrientation,
  25258. instance: instance,
  25259. updatable: updatable
  25260. };
  25261. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  25262. };
  25263. /**
  25264. * Creates an custom extruded shape mesh.
  25265. * 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.
  25266. * Please consider using the same method from the MeshBuilder class instead.
  25267. *
  25268. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25269. * 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
  25270. * extruded along the Z axis.
  25271. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25272. * 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
  25273. * and the distance of this point from the begining of the path :
  25274. * ```javascript
  25275. * var rotationFunction = function(i, distance) {
  25276. * // do things
  25277. * return rotationValue; }
  25278. * ```
  25279. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  25280. * 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
  25281. * and the distance of this point from the begining of the path :
  25282. * ```javascript
  25283. * var scaleFunction = function(i, distance) {
  25284. * // do things
  25285. * return scaleValue;}
  25286. * ```
  25287. * It must returns a float value that will be the scale value applied to the shape on each path point.
  25288. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  25289. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  25290. * 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
  25291. * 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
  25292. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25293. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25294. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25295. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25296. */
  25297. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  25298. var options = {
  25299. shape: shape,
  25300. path: path,
  25301. scaleFunction: scaleFunction,
  25302. rotationFunction: rotationFunction,
  25303. ribbonCloseArray: ribbonCloseArray,
  25304. ribbonClosePath: ribbonClosePath,
  25305. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25306. sideOrientation: sideOrientation,
  25307. instance: instance,
  25308. updatable: updatable
  25309. };
  25310. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  25311. };
  25312. /**
  25313. * Creates lathe mesh.
  25314. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  25315. * Please consider using the same method from the MeshBuilder class instead.
  25316. * 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
  25317. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  25318. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  25319. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  25320. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25321. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25322. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25323. */
  25324. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  25325. var options = {
  25326. shape: shape,
  25327. radius: radius,
  25328. tessellation: tessellation,
  25329. sideOrientation: sideOrientation,
  25330. updatable: updatable
  25331. };
  25332. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  25333. };
  25334. /**
  25335. * Creates a plane mesh.
  25336. * Please consider using the same method from the MeshBuilder class instead.
  25337. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  25338. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25339. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25341. */
  25342. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  25343. var options = {
  25344. size: size,
  25345. width: size,
  25346. height: size,
  25347. sideOrientation: sideOrientation,
  25348. updatable: updatable
  25349. };
  25350. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  25351. };
  25352. /**
  25353. * Creates a ground mesh.
  25354. * Please consider using the same method from the MeshBuilder class instead.
  25355. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  25356. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  25357. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25358. */
  25359. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  25360. var options = {
  25361. width: width,
  25362. height: height,
  25363. subdivisions: subdivisions,
  25364. updatable: updatable
  25365. };
  25366. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  25367. };
  25368. /**
  25369. * Creates a tiled ground mesh.
  25370. * Please consider using the same method from the MeshBuilder class instead.
  25371. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  25372. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  25373. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  25374. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  25375. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  25376. * numbers of subdivisions on the ground width and height of each tile.
  25377. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25378. */
  25379. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  25380. var options = {
  25381. xmin: xmin,
  25382. zmin: zmin,
  25383. xmax: xmax,
  25384. zmax: zmax,
  25385. subdivisions: subdivisions,
  25386. precision: precision,
  25387. updatable: updatable
  25388. };
  25389. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  25390. };
  25391. /**
  25392. * Creates a ground mesh from a height map.
  25393. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  25394. * Please consider using the same method from the MeshBuilder class instead.
  25395. * The parameter `url` sets the URL of the height map image resource.
  25396. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  25397. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  25398. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  25399. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  25400. * 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).
  25401. * This function is passed the newly built mesh :
  25402. * ```javascript
  25403. * function(mesh) { // do things
  25404. * return; }
  25405. * ```
  25406. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25407. */
  25408. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  25409. var options = {
  25410. width: width,
  25411. height: height,
  25412. subdivisions: subdivisions,
  25413. minHeight: minHeight,
  25414. maxHeight: maxHeight,
  25415. updatable: updatable,
  25416. onReady: onReady
  25417. };
  25418. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  25419. };
  25420. /**
  25421. * Creates a tube mesh.
  25422. * 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.
  25423. * Please consider using the same method from the MeshBuilder class instead.
  25424. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  25425. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  25426. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  25427. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  25428. * 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.
  25429. * It must return a radius value (positive float) :
  25430. * ```javascript
  25431. * var radiusFunction = function(i, distance) {
  25432. * // do things
  25433. * return radius; }
  25434. * ```
  25435. * 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
  25436. * 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
  25437. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25438. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25439. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25440. */
  25441. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  25442. var options = {
  25443. path: path,
  25444. radius: radius,
  25445. tessellation: tessellation,
  25446. radiusFunction: radiusFunction,
  25447. arc: 1,
  25448. cap: cap,
  25449. updatable: updatable,
  25450. sideOrientation: sideOrientation,
  25451. instance: instance
  25452. };
  25453. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25454. };
  25455. /**
  25456. * Creates a polyhedron mesh.
  25457. * Please consider using the same method from the MeshBuilder class instead.
  25458. * 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
  25459. * to choose the wanted type.
  25460. * The parameter `size` (positive float, default 1) sets the polygon size.
  25461. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25462. * 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`.
  25463. * 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
  25464. * 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)`).
  25465. * 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
  25466. * 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.
  25467. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25468. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25469. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25470. */
  25471. Mesh.CreatePolyhedron = function (name, options, scene) {
  25472. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25473. };
  25474. /**
  25475. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25476. * Please consider using the same method from the MeshBuilder class instead.
  25477. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25478. * 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`).
  25479. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25480. * 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.
  25481. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25482. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25483. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25484. */
  25485. Mesh.CreateIcoSphere = function (name, options, scene) {
  25486. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25487. };
  25488. /**
  25489. * Creates a decal mesh.
  25490. * Please consider using the same method from the MeshBuilder class instead.
  25491. * 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.
  25492. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25493. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25494. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25495. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25496. */
  25497. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25498. var options = {
  25499. position: position,
  25500. normal: normal,
  25501. size: size,
  25502. angle: angle
  25503. };
  25504. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25505. };
  25506. // Skeletons
  25507. /**
  25508. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25509. */
  25510. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25511. if (!this._sourcePositions) {
  25512. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25513. if (!source) {
  25514. return this._sourcePositions;
  25515. }
  25516. this._sourcePositions = new Float32Array(source);
  25517. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25518. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25519. }
  25520. }
  25521. return this._sourcePositions;
  25522. };
  25523. /**
  25524. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25525. */
  25526. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25527. if (!this._sourceNormals) {
  25528. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25529. if (!source) {
  25530. return this._sourceNormals;
  25531. }
  25532. this._sourceNormals = new Float32Array(source);
  25533. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25534. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25535. }
  25536. }
  25537. return this._sourceNormals;
  25538. };
  25539. /**
  25540. * Updates the vertex buffer by applying transformation from the bones.
  25541. * Returns the Mesh.
  25542. *
  25543. * @param {skeleton} skeleton to apply
  25544. */
  25545. Mesh.prototype.applySkeleton = function (skeleton) {
  25546. if (!this.geometry) {
  25547. return this;
  25548. }
  25549. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25550. return this;
  25551. }
  25552. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25553. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25554. return this;
  25555. }
  25556. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25557. return this;
  25558. }
  25559. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25560. return this;
  25561. }
  25562. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25563. return this;
  25564. }
  25565. if (!this._sourcePositions) {
  25566. var submeshes = this.subMeshes.slice();
  25567. this.setPositionsForCPUSkinning();
  25568. this.subMeshes = submeshes;
  25569. }
  25570. if (!this._sourceNormals) {
  25571. this.setNormalsForCPUSkinning();
  25572. }
  25573. // positionsData checks for not being Float32Array will only pass at most once
  25574. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25575. if (!positionsData) {
  25576. return this;
  25577. }
  25578. if (!(positionsData instanceof Float32Array)) {
  25579. positionsData = new Float32Array(positionsData);
  25580. }
  25581. // normalsData checks for not being Float32Array will only pass at most once
  25582. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25583. if (!normalsData) {
  25584. return this;
  25585. }
  25586. if (!(normalsData instanceof Float32Array)) {
  25587. normalsData = new Float32Array(normalsData);
  25588. }
  25589. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25590. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25591. if (!matricesWeightsData || !matricesIndicesData) {
  25592. return this;
  25593. }
  25594. var needExtras = this.numBoneInfluencers > 4;
  25595. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25596. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25597. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  25598. return this;
  25599. }
  25600. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25601. var tempVector3 = BABYLON.Vector3.Zero();
  25602. var finalMatrix = new BABYLON.Matrix();
  25603. var tempMatrix = new BABYLON.Matrix();
  25604. var matWeightIdx = 0;
  25605. var inf;
  25606. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25607. var weight;
  25608. for (inf = 0; inf < 4; inf++) {
  25609. weight = matricesWeightsData[matWeightIdx + inf];
  25610. if (weight > 0) {
  25611. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25612. finalMatrix.addToSelf(tempMatrix);
  25613. }
  25614. else
  25615. break;
  25616. }
  25617. if (needExtras) {
  25618. for (inf = 0; inf < 4; inf++) {
  25619. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25620. if (weight > 0) {
  25621. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25622. finalMatrix.addToSelf(tempMatrix);
  25623. }
  25624. else
  25625. break;
  25626. }
  25627. }
  25628. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25629. tempVector3.toArray(positionsData, index);
  25630. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25631. tempVector3.toArray(normalsData, index);
  25632. finalMatrix.reset();
  25633. }
  25634. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25635. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25636. return this;
  25637. };
  25638. // Tools
  25639. /**
  25640. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25641. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25642. */
  25643. Mesh.MinMax = function (meshes) {
  25644. var minVector = null;
  25645. var maxVector = null;
  25646. meshes.forEach(function (mesh, index, array) {
  25647. var boundingInfo = mesh.getBoundingInfo();
  25648. if (!boundingInfo) {
  25649. return;
  25650. }
  25651. var boundingBox = boundingInfo.boundingBox;
  25652. if (!minVector || !maxVector) {
  25653. minVector = boundingBox.minimumWorld;
  25654. maxVector = boundingBox.maximumWorld;
  25655. }
  25656. else {
  25657. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25658. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25659. }
  25660. });
  25661. if (!minVector || !maxVector) {
  25662. return {
  25663. min: BABYLON.Vector3.Zero(),
  25664. max: BABYLON.Vector3.Zero()
  25665. };
  25666. }
  25667. return {
  25668. min: minVector,
  25669. max: maxVector
  25670. };
  25671. };
  25672. /**
  25673. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25674. */
  25675. Mesh.Center = function (meshesOrMinMaxVector) {
  25676. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25677. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25678. };
  25679. /**
  25680. * Merge the array of meshes into a single mesh for performance reasons.
  25681. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25682. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25683. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25684. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25685. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25686. */
  25687. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25688. if (disposeSource === void 0) { disposeSource = true; }
  25689. var index;
  25690. if (!allow32BitsIndices) {
  25691. var totalVertices = 0;
  25692. // Counting vertices
  25693. for (index = 0; index < meshes.length; index++) {
  25694. if (meshes[index]) {
  25695. totalVertices += meshes[index].getTotalVertices();
  25696. if (totalVertices > 65536) {
  25697. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25698. return null;
  25699. }
  25700. }
  25701. }
  25702. }
  25703. // Merge
  25704. var vertexData = null;
  25705. var otherVertexData;
  25706. var indiceArray = new Array();
  25707. var source = null;
  25708. for (index = 0; index < meshes.length; index++) {
  25709. if (meshes[index]) {
  25710. meshes[index].computeWorldMatrix(true);
  25711. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25712. otherVertexData.transform(meshes[index].getWorldMatrix());
  25713. if (vertexData) {
  25714. vertexData.merge(otherVertexData);
  25715. }
  25716. else {
  25717. vertexData = otherVertexData;
  25718. source = meshes[index];
  25719. }
  25720. if (subdivideWithSubMeshes) {
  25721. indiceArray.push(meshes[index].getTotalIndices());
  25722. }
  25723. }
  25724. }
  25725. source = source;
  25726. if (!meshSubclass) {
  25727. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25728. }
  25729. vertexData.applyToMesh(meshSubclass);
  25730. // Setting properties
  25731. meshSubclass.material = source.material;
  25732. meshSubclass.checkCollisions = source.checkCollisions;
  25733. // Cleaning
  25734. if (disposeSource) {
  25735. for (index = 0; index < meshes.length; index++) {
  25736. if (meshes[index]) {
  25737. meshes[index].dispose();
  25738. }
  25739. }
  25740. }
  25741. // Subdivide
  25742. if (subdivideWithSubMeshes) {
  25743. //-- Suppresions du submesh global
  25744. meshSubclass.releaseSubMeshes();
  25745. index = 0;
  25746. var offset = 0;
  25747. //-- aplique la subdivision en fonction du tableau d'indices
  25748. while (index < indiceArray.length) {
  25749. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25750. offset += indiceArray[index];
  25751. index++;
  25752. }
  25753. }
  25754. return meshSubclass;
  25755. };
  25756. // Consts
  25757. Mesh._FRONTSIDE = 0;
  25758. Mesh._BACKSIDE = 1;
  25759. Mesh._DOUBLESIDE = 2;
  25760. Mesh._DEFAULTSIDE = 0;
  25761. Mesh._NO_CAP = 0;
  25762. Mesh._CAP_START = 1;
  25763. Mesh._CAP_END = 2;
  25764. Mesh._CAP_ALL = 3;
  25765. return Mesh;
  25766. }(BABYLON.AbstractMesh));
  25767. BABYLON.Mesh = Mesh;
  25768. })(BABYLON || (BABYLON = {}));
  25769. //# sourceMappingURL=babylon.mesh.js.map
  25770. var BABYLON;
  25771. (function (BABYLON) {
  25772. var BaseSubMesh = /** @class */ (function () {
  25773. function BaseSubMesh() {
  25774. }
  25775. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25776. get: function () {
  25777. return this._materialEffect;
  25778. },
  25779. enumerable: true,
  25780. configurable: true
  25781. });
  25782. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25783. if (defines === void 0) { defines = null; }
  25784. if (this._materialEffect === effect) {
  25785. if (!effect) {
  25786. this._materialDefines = null;
  25787. }
  25788. return;
  25789. }
  25790. this._materialDefines = defines;
  25791. this._materialEffect = effect;
  25792. };
  25793. return BaseSubMesh;
  25794. }());
  25795. BABYLON.BaseSubMesh = BaseSubMesh;
  25796. var SubMesh = /** @class */ (function (_super) {
  25797. __extends(SubMesh, _super);
  25798. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25799. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25800. var _this = _super.call(this) || this;
  25801. _this.materialIndex = materialIndex;
  25802. _this.verticesStart = verticesStart;
  25803. _this.verticesCount = verticesCount;
  25804. _this.indexStart = indexStart;
  25805. _this.indexCount = indexCount;
  25806. _this._renderId = 0;
  25807. _this._mesh = mesh;
  25808. _this._renderingMesh = renderingMesh || mesh;
  25809. mesh.subMeshes.push(_this);
  25810. _this._trianglePlanes = [];
  25811. _this._id = mesh.subMeshes.length - 1;
  25812. if (createBoundingBox) {
  25813. _this.refreshBoundingInfo();
  25814. mesh.computeWorldMatrix(true);
  25815. }
  25816. return _this;
  25817. }
  25818. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25819. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25820. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25821. };
  25822. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25823. get: function () {
  25824. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25825. },
  25826. enumerable: true,
  25827. configurable: true
  25828. });
  25829. /**
  25830. * Returns the submesh BoudingInfo object.
  25831. */
  25832. SubMesh.prototype.getBoundingInfo = function () {
  25833. if (this.IsGlobal) {
  25834. return this._mesh.getBoundingInfo();
  25835. }
  25836. return this._boundingInfo;
  25837. };
  25838. /**
  25839. * Sets the submesh BoundingInfo.
  25840. * Return the SubMesh.
  25841. */
  25842. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25843. this._boundingInfo = boundingInfo;
  25844. return this;
  25845. };
  25846. /**
  25847. * Returns the mesh of the current submesh.
  25848. */
  25849. SubMesh.prototype.getMesh = function () {
  25850. return this._mesh;
  25851. };
  25852. /**
  25853. * Returns the rendering mesh of the submesh.
  25854. */
  25855. SubMesh.prototype.getRenderingMesh = function () {
  25856. return this._renderingMesh;
  25857. };
  25858. /**
  25859. * Returns the submesh material.
  25860. */
  25861. SubMesh.prototype.getMaterial = function () {
  25862. var rootMaterial = this._renderingMesh.material;
  25863. if (rootMaterial && rootMaterial.getSubMaterial) {
  25864. var multiMaterial = rootMaterial;
  25865. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25866. if (this._currentMaterial !== effectiveMaterial) {
  25867. this._currentMaterial = effectiveMaterial;
  25868. this._materialDefines = null;
  25869. }
  25870. return effectiveMaterial;
  25871. }
  25872. if (!rootMaterial) {
  25873. return this._mesh.getScene().defaultMaterial;
  25874. }
  25875. return rootMaterial;
  25876. };
  25877. // Methods
  25878. /**
  25879. * Sets a new updated BoundingInfo object to the submesh.
  25880. * Returns the SubMesh.
  25881. */
  25882. SubMesh.prototype.refreshBoundingInfo = function () {
  25883. this._lastColliderWorldVertices = null;
  25884. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25885. return this;
  25886. }
  25887. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25888. if (!data) {
  25889. this._boundingInfo = this._mesh._boundingInfo;
  25890. return this;
  25891. }
  25892. var indices = this._renderingMesh.getIndices();
  25893. var extend;
  25894. //is this the only submesh?
  25895. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25896. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25897. if (!boundingInfo) {
  25898. return this;
  25899. }
  25900. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25901. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25902. }
  25903. else {
  25904. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25905. }
  25906. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25907. return this;
  25908. };
  25909. SubMesh.prototype._checkCollision = function (collider) {
  25910. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25911. if (!boundingInfo) {
  25912. return false;
  25913. }
  25914. return boundingInfo._checkCollision(collider);
  25915. };
  25916. /**
  25917. * Updates the submesh BoundingInfo.
  25918. * Returns the Submesh.
  25919. */
  25920. SubMesh.prototype.updateBoundingInfo = function (world) {
  25921. var boundingInfo = this.getBoundingInfo();
  25922. if (!boundingInfo) {
  25923. this.refreshBoundingInfo();
  25924. boundingInfo = this.getBoundingInfo();
  25925. }
  25926. boundingInfo.update(world);
  25927. return this;
  25928. };
  25929. /**
  25930. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25931. * Boolean returned.
  25932. */
  25933. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25934. var boundingInfo = this.getBoundingInfo();
  25935. if (!boundingInfo) {
  25936. return false;
  25937. }
  25938. return boundingInfo.isInFrustum(frustumPlanes);
  25939. };
  25940. /**
  25941. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25942. * Boolean returned.
  25943. */
  25944. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25945. var boundingInfo = this.getBoundingInfo();
  25946. if (!boundingInfo) {
  25947. return false;
  25948. }
  25949. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  25950. };
  25951. /**
  25952. * Renders the submesh.
  25953. * Returns it.
  25954. */
  25955. SubMesh.prototype.render = function (enableAlphaMode) {
  25956. this._renderingMesh.render(this, enableAlphaMode);
  25957. return this;
  25958. };
  25959. /**
  25960. * Returns a new Index Buffer.
  25961. * Type returned : WebGLBuffer.
  25962. */
  25963. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25964. if (!this._linesIndexBuffer) {
  25965. var linesIndices = [];
  25966. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25967. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25968. }
  25969. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25970. this.linesIndexCount = linesIndices.length;
  25971. }
  25972. return this._linesIndexBuffer;
  25973. };
  25974. /**
  25975. * True is the passed Ray intersects the submesh bounding box.
  25976. * Boolean returned.
  25977. */
  25978. SubMesh.prototype.canIntersects = function (ray) {
  25979. var boundingInfo = this.getBoundingInfo();
  25980. if (!boundingInfo) {
  25981. return false;
  25982. }
  25983. return ray.intersectsBox(boundingInfo.boundingBox);
  25984. };
  25985. /**
  25986. * Returns an object IntersectionInfo.
  25987. */
  25988. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25989. var intersectInfo = null;
  25990. // LineMesh first as it's also a Mesh...
  25991. if (this._mesh instanceof BABYLON.LinesMesh) {
  25992. var lineMesh = this._mesh;
  25993. // Line test
  25994. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25995. var p0 = positions[indices[index]];
  25996. var p1 = positions[indices[index + 1]];
  25997. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25998. if (length < 0) {
  25999. continue;
  26000. }
  26001. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26002. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26003. if (fastCheck) {
  26004. break;
  26005. }
  26006. }
  26007. }
  26008. }
  26009. else {
  26010. // Triangles test
  26011. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26012. var p0 = positions[indices[index]];
  26013. var p1 = positions[indices[index + 1]];
  26014. var p2 = positions[indices[index + 2]];
  26015. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26016. if (currentIntersectInfo) {
  26017. if (currentIntersectInfo.distance < 0) {
  26018. continue;
  26019. }
  26020. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26021. intersectInfo = currentIntersectInfo;
  26022. intersectInfo.faceId = index / 3;
  26023. if (fastCheck) {
  26024. break;
  26025. }
  26026. }
  26027. }
  26028. }
  26029. }
  26030. return intersectInfo;
  26031. };
  26032. SubMesh.prototype._rebuild = function () {
  26033. if (this._linesIndexBuffer) {
  26034. this._linesIndexBuffer = null;
  26035. }
  26036. };
  26037. // Clone
  26038. /**
  26039. * Creates a new Submesh from the passed Mesh.
  26040. */
  26041. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26042. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26043. if (!this.IsGlobal) {
  26044. var boundingInfo = this.getBoundingInfo();
  26045. if (!boundingInfo) {
  26046. return result;
  26047. }
  26048. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  26049. }
  26050. return result;
  26051. };
  26052. // Dispose
  26053. /**
  26054. * Disposes the Submesh.
  26055. * Returns nothing.
  26056. */
  26057. SubMesh.prototype.dispose = function () {
  26058. if (this._linesIndexBuffer) {
  26059. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26060. this._linesIndexBuffer = null;
  26061. }
  26062. // Remove from mesh
  26063. var index = this._mesh.subMeshes.indexOf(this);
  26064. this._mesh.subMeshes.splice(index, 1);
  26065. };
  26066. // Statics
  26067. /**
  26068. * Creates a new Submesh from the passed parameters :
  26069. * - materialIndex (integer) : the index of the main mesh material.
  26070. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26071. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26072. * - mesh (Mesh) : the main mesh to create the submesh from.
  26073. * - renderingMesh (optional Mesh) : rendering mesh.
  26074. */
  26075. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26076. var minVertexIndex = Number.MAX_VALUE;
  26077. var maxVertexIndex = -Number.MAX_VALUE;
  26078. renderingMesh = (renderingMesh || mesh);
  26079. var indices = renderingMesh.getIndices();
  26080. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26081. var vertexIndex = indices[index];
  26082. if (vertexIndex < minVertexIndex)
  26083. minVertexIndex = vertexIndex;
  26084. if (vertexIndex > maxVertexIndex)
  26085. maxVertexIndex = vertexIndex;
  26086. }
  26087. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26088. };
  26089. return SubMesh;
  26090. }(BaseSubMesh));
  26091. BABYLON.SubMesh = SubMesh;
  26092. })(BABYLON || (BABYLON = {}));
  26093. //# sourceMappingURL=babylon.subMesh.js.map
  26094. var BABYLON;
  26095. (function (BABYLON) {
  26096. var EffectFallbacks = /** @class */ (function () {
  26097. function EffectFallbacks() {
  26098. this._defines = {};
  26099. this._currentRank = 32;
  26100. this._maxRank = -1;
  26101. }
  26102. EffectFallbacks.prototype.unBindMesh = function () {
  26103. this._mesh = null;
  26104. };
  26105. EffectFallbacks.prototype.addFallback = function (rank, define) {
  26106. if (!this._defines[rank]) {
  26107. if (rank < this._currentRank) {
  26108. this._currentRank = rank;
  26109. }
  26110. if (rank > this._maxRank) {
  26111. this._maxRank = rank;
  26112. }
  26113. this._defines[rank] = new Array();
  26114. }
  26115. this._defines[rank].push(define);
  26116. };
  26117. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  26118. this._meshRank = rank;
  26119. this._mesh = mesh;
  26120. if (rank < this._currentRank) {
  26121. this._currentRank = rank;
  26122. }
  26123. if (rank > this._maxRank) {
  26124. this._maxRank = rank;
  26125. }
  26126. };
  26127. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  26128. get: function () {
  26129. return this._currentRank <= this._maxRank;
  26130. },
  26131. enumerable: true,
  26132. configurable: true
  26133. });
  26134. EffectFallbacks.prototype.reduce = function (currentDefines) {
  26135. // First we try to switch to CPU skinning
  26136. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  26137. this._mesh.computeBonesUsingShaders = false;
  26138. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  26139. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  26140. var scene = this._mesh.getScene();
  26141. for (var index = 0; index < scene.meshes.length; index++) {
  26142. var otherMesh = scene.meshes[index];
  26143. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  26144. otherMesh.computeBonesUsingShaders = false;
  26145. }
  26146. }
  26147. }
  26148. else {
  26149. var currentFallbacks = this._defines[this._currentRank];
  26150. if (currentFallbacks) {
  26151. for (var index = 0; index < currentFallbacks.length; index++) {
  26152. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  26153. }
  26154. }
  26155. this._currentRank++;
  26156. }
  26157. return currentDefines;
  26158. };
  26159. return EffectFallbacks;
  26160. }());
  26161. BABYLON.EffectFallbacks = EffectFallbacks;
  26162. var EffectCreationOptions = /** @class */ (function () {
  26163. function EffectCreationOptions() {
  26164. }
  26165. return EffectCreationOptions;
  26166. }());
  26167. BABYLON.EffectCreationOptions = EffectCreationOptions;
  26168. var Effect = /** @class */ (function () {
  26169. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  26170. if (samplers === void 0) { samplers = null; }
  26171. if (defines === void 0) { defines = null; }
  26172. if (fallbacks === void 0) { fallbacks = null; }
  26173. if (onCompiled === void 0) { onCompiled = null; }
  26174. if (onError === void 0) { onError = null; }
  26175. var _this = this;
  26176. this.uniqueId = 0;
  26177. this.onCompileObservable = new BABYLON.Observable();
  26178. this.onErrorObservable = new BABYLON.Observable();
  26179. this.onBindObservable = new BABYLON.Observable();
  26180. this._uniformBuffersNames = {};
  26181. this._isReady = false;
  26182. this._compilationError = "";
  26183. this.name = baseName;
  26184. if (attributesNamesOrOptions.attributes) {
  26185. var options = attributesNamesOrOptions;
  26186. this._engine = uniformsNamesOrEngine;
  26187. this._attributesNames = options.attributes;
  26188. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  26189. this._samplers = options.samplers;
  26190. this.defines = options.defines;
  26191. this.onError = options.onError;
  26192. this.onCompiled = options.onCompiled;
  26193. this._fallbacks = options.fallbacks;
  26194. this._indexParameters = options.indexParameters;
  26195. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  26196. if (options.uniformBuffersNames) {
  26197. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  26198. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  26199. }
  26200. }
  26201. }
  26202. else {
  26203. this._engine = engine;
  26204. this.defines = defines;
  26205. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  26206. this._samplers = samplers;
  26207. this._attributesNames = attributesNamesOrOptions;
  26208. this.onError = onError;
  26209. this.onCompiled = onCompiled;
  26210. this._indexParameters = indexParameters;
  26211. this._fallbacks = fallbacks;
  26212. }
  26213. this.uniqueId = Effect._uniqueIdSeed++;
  26214. var vertexSource;
  26215. var fragmentSource;
  26216. if (baseName.vertexElement) {
  26217. vertexSource = document.getElementById(baseName.vertexElement);
  26218. if (!vertexSource) {
  26219. vertexSource = baseName.vertexElement;
  26220. }
  26221. }
  26222. else {
  26223. vertexSource = baseName.vertex || baseName;
  26224. }
  26225. if (baseName.fragmentElement) {
  26226. fragmentSource = document.getElementById(baseName.fragmentElement);
  26227. if (!fragmentSource) {
  26228. fragmentSource = baseName.fragmentElement;
  26229. }
  26230. }
  26231. else {
  26232. fragmentSource = baseName.fragment || baseName;
  26233. }
  26234. this._loadVertexShader(vertexSource, function (vertexCode) {
  26235. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  26236. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  26237. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  26238. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  26239. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  26240. if (baseName) {
  26241. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  26242. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  26243. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  26244. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  26245. }
  26246. else {
  26247. _this._vertexSourceCode = migratedVertexCode;
  26248. _this._fragmentSourceCode = migratedFragmentCode;
  26249. }
  26250. _this._prepareEffect();
  26251. });
  26252. });
  26253. });
  26254. });
  26255. });
  26256. });
  26257. }
  26258. Object.defineProperty(Effect.prototype, "key", {
  26259. get: function () {
  26260. return this._key;
  26261. },
  26262. enumerable: true,
  26263. configurable: true
  26264. });
  26265. // Properties
  26266. Effect.prototype.isReady = function () {
  26267. return this._isReady;
  26268. };
  26269. Effect.prototype.getEngine = function () {
  26270. return this._engine;
  26271. };
  26272. Effect.prototype.getProgram = function () {
  26273. return this._program;
  26274. };
  26275. Effect.prototype.getAttributesNames = function () {
  26276. return this._attributesNames;
  26277. };
  26278. Effect.prototype.getAttributeLocation = function (index) {
  26279. return this._attributes[index];
  26280. };
  26281. Effect.prototype.getAttributeLocationByName = function (name) {
  26282. var index = this._attributesNames.indexOf(name);
  26283. return this._attributes[index];
  26284. };
  26285. Effect.prototype.getAttributesCount = function () {
  26286. return this._attributes.length;
  26287. };
  26288. Effect.prototype.getUniformIndex = function (uniformName) {
  26289. return this._uniformsNames.indexOf(uniformName);
  26290. };
  26291. Effect.prototype.getUniform = function (uniformName) {
  26292. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  26293. };
  26294. Effect.prototype.getSamplers = function () {
  26295. return this._samplers;
  26296. };
  26297. Effect.prototype.getCompilationError = function () {
  26298. return this._compilationError;
  26299. };
  26300. // Methods
  26301. Effect.prototype.executeWhenCompiled = function (func) {
  26302. if (this.isReady()) {
  26303. func(this);
  26304. return;
  26305. }
  26306. this.onCompileObservable.add(function (effect) {
  26307. func(effect);
  26308. });
  26309. };
  26310. Effect.prototype._loadVertexShader = function (vertex, callback) {
  26311. if (BABYLON.Tools.IsWindowObjectExist()) {
  26312. // DOM element ?
  26313. if (vertex instanceof HTMLElement) {
  26314. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  26315. callback(vertexCode);
  26316. return;
  26317. }
  26318. }
  26319. // Base64 encoded ?
  26320. if (vertex.substr(0, 7) === "base64:") {
  26321. var vertexBinary = window.atob(vertex.substr(7));
  26322. callback(vertexBinary);
  26323. return;
  26324. }
  26325. // Is in local store ?
  26326. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  26327. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  26328. return;
  26329. }
  26330. var vertexShaderUrl;
  26331. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  26332. vertexShaderUrl = vertex;
  26333. }
  26334. else {
  26335. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  26336. }
  26337. // Vertex shader
  26338. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  26339. };
  26340. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  26341. if (BABYLON.Tools.IsWindowObjectExist()) {
  26342. // DOM element ?
  26343. if (fragment instanceof HTMLElement) {
  26344. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  26345. callback(fragmentCode);
  26346. return;
  26347. }
  26348. }
  26349. // Base64 encoded ?
  26350. if (fragment.substr(0, 7) === "base64:") {
  26351. var fragmentBinary = window.atob(fragment.substr(7));
  26352. callback(fragmentBinary);
  26353. return;
  26354. }
  26355. // Is in local store ?
  26356. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  26357. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  26358. return;
  26359. }
  26360. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  26361. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  26362. return;
  26363. }
  26364. var fragmentShaderUrl;
  26365. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  26366. fragmentShaderUrl = fragment;
  26367. }
  26368. else {
  26369. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  26370. }
  26371. // Fragment shader
  26372. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  26373. };
  26374. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  26375. // Rebuild shaders source code
  26376. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  26377. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  26378. vertexCode = prefix + vertexCode;
  26379. fragmentCode = prefix + fragmentCode;
  26380. // Number lines of shaders source code
  26381. var i = 2;
  26382. var regex = /\n/gm;
  26383. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26384. i = 2;
  26385. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  26386. // Dump shaders name and formatted source code
  26387. if (this.name.vertexElement) {
  26388. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  26389. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  26390. }
  26391. else if (this.name.vertex) {
  26392. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  26393. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  26394. }
  26395. else {
  26396. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  26397. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  26398. }
  26399. };
  26400. ;
  26401. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  26402. var preparedSourceCode = this._processPrecision(sourceCode);
  26403. if (this._engine.webGLVersion == 1) {
  26404. callback(preparedSourceCode);
  26405. return;
  26406. }
  26407. // Already converted
  26408. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  26409. callback(preparedSourceCode.replace("#version 300 es", ""));
  26410. return;
  26411. }
  26412. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  26413. // Remove extensions
  26414. // #extension GL_OES_standard_derivatives : enable
  26415. // #extension GL_EXT_shader_texture_lod : enable
  26416. // #extension GL_EXT_frag_depth : enable
  26417. // #extension GL_EXT_draw_buffers : require
  26418. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  26419. var result = preparedSourceCode.replace(regex, "");
  26420. // Migrate to GLSL v300
  26421. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  26422. result = result.replace(/attribute[ \t]/g, "in ");
  26423. result = result.replace(/[ \t]attribute/g, " in");
  26424. if (isFragment) {
  26425. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  26426. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  26427. result = result.replace(/texture2D\s*\(/g, "texture(");
  26428. result = result.replace(/textureCube\s*\(/g, "texture(");
  26429. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  26430. result = result.replace(/gl_FragColor/g, "glFragColor");
  26431. result = result.replace(/gl_FragData/g, "glFragData");
  26432. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  26433. }
  26434. callback(result);
  26435. };
  26436. Effect.prototype._processIncludes = function (sourceCode, callback) {
  26437. var _this = this;
  26438. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  26439. var match = regex.exec(sourceCode);
  26440. var returnValue = new String(sourceCode);
  26441. while (match != null) {
  26442. var includeFile = match[1];
  26443. // Uniform declaration
  26444. if (includeFile.indexOf("__decl__") !== -1) {
  26445. includeFile = includeFile.replace(/__decl__/, "");
  26446. if (this._engine.supportsUniformBuffers) {
  26447. includeFile = includeFile.replace(/Vertex/, "Ubo");
  26448. includeFile = includeFile.replace(/Fragment/, "Ubo");
  26449. }
  26450. includeFile = includeFile + "Declaration";
  26451. }
  26452. if (Effect.IncludesShadersStore[includeFile]) {
  26453. // Substitution
  26454. var includeContent = Effect.IncludesShadersStore[includeFile];
  26455. if (match[2]) {
  26456. var splits = match[3].split(",");
  26457. for (var index = 0; index < splits.length; index += 2) {
  26458. var source = new RegExp(splits[index], "g");
  26459. var dest = splits[index + 1];
  26460. includeContent = includeContent.replace(source, dest);
  26461. }
  26462. }
  26463. if (match[4]) {
  26464. var indexString = match[5];
  26465. if (indexString.indexOf("..") !== -1) {
  26466. var indexSplits = indexString.split("..");
  26467. var minIndex = parseInt(indexSplits[0]);
  26468. var maxIndex = parseInt(indexSplits[1]);
  26469. var sourceIncludeContent = includeContent.slice(0);
  26470. includeContent = "";
  26471. if (isNaN(maxIndex)) {
  26472. maxIndex = this._indexParameters[indexSplits[1]];
  26473. }
  26474. for (var i = minIndex; i < maxIndex; i++) {
  26475. if (!this._engine.supportsUniformBuffers) {
  26476. // Ubo replacement
  26477. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26478. return p1 + "{X}";
  26479. });
  26480. }
  26481. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26482. }
  26483. }
  26484. else {
  26485. if (!this._engine.supportsUniformBuffers) {
  26486. // Ubo replacement
  26487. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26488. return p1 + "{X}";
  26489. });
  26490. }
  26491. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26492. }
  26493. }
  26494. // Replace
  26495. returnValue = returnValue.replace(match[0], includeContent);
  26496. }
  26497. else {
  26498. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26499. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26500. Effect.IncludesShadersStore[includeFile] = fileContent;
  26501. _this._processIncludes(returnValue, callback);
  26502. });
  26503. return;
  26504. }
  26505. match = regex.exec(sourceCode);
  26506. }
  26507. callback(returnValue);
  26508. };
  26509. Effect.prototype._processPrecision = function (source) {
  26510. if (source.indexOf("precision highp float") === -1) {
  26511. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26512. source = "precision mediump float;\n" + source;
  26513. }
  26514. else {
  26515. source = "precision highp float;\n" + source;
  26516. }
  26517. }
  26518. else {
  26519. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26520. source = source.replace("precision highp float", "precision mediump float");
  26521. }
  26522. }
  26523. return source;
  26524. };
  26525. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26526. var _this = this;
  26527. this._isReady = false;
  26528. this._vertexSourceCodeOverride = vertexSourceCode;
  26529. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26530. this.onError = function (effect, error) {
  26531. if (onError) {
  26532. onError(error);
  26533. }
  26534. };
  26535. this.onCompiled = function () {
  26536. var scenes = _this.getEngine().scenes;
  26537. for (var i = 0; i < scenes.length; i++) {
  26538. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26539. }
  26540. if (onCompiled) {
  26541. onCompiled(_this._program);
  26542. }
  26543. };
  26544. this._fallbacks = null;
  26545. this._prepareEffect();
  26546. };
  26547. Effect.prototype._prepareEffect = function () {
  26548. var attributesNames = this._attributesNames;
  26549. var defines = this.defines;
  26550. var fallbacks = this._fallbacks;
  26551. this._valueCache = {};
  26552. var previousProgram = this._program;
  26553. try {
  26554. var engine = this._engine;
  26555. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26556. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26557. }
  26558. else {
  26559. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26560. }
  26561. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26562. if (engine.webGLVersion > 1) {
  26563. for (var name in this._uniformBuffersNames) {
  26564. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26565. }
  26566. }
  26567. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26568. this._attributes = engine.getAttributes(this._program, attributesNames);
  26569. var index;
  26570. for (index = 0; index < this._samplers.length; index++) {
  26571. var sampler = this.getUniform(this._samplers[index]);
  26572. if (sampler == null) {
  26573. this._samplers.splice(index, 1);
  26574. index--;
  26575. }
  26576. }
  26577. engine.bindSamplers(this);
  26578. this._compilationError = "";
  26579. this._isReady = true;
  26580. if (this.onCompiled) {
  26581. this.onCompiled(this);
  26582. }
  26583. this.onCompileObservable.notifyObservers(this);
  26584. this.onCompileObservable.clear();
  26585. // Unbind mesh reference in fallbacks
  26586. if (this._fallbacks) {
  26587. this._fallbacks.unBindMesh();
  26588. }
  26589. if (previousProgram) {
  26590. this.getEngine()._deleteProgram(previousProgram);
  26591. }
  26592. }
  26593. catch (e) {
  26594. this._compilationError = e.message;
  26595. // Let's go through fallbacks then
  26596. BABYLON.Tools.Error("Unable to compile effect:");
  26597. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26598. return " " + uniform;
  26599. }));
  26600. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26601. return " " + attribute;
  26602. }));
  26603. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26604. BABYLON.Tools.Error("Error: " + this._compilationError);
  26605. if (previousProgram) {
  26606. this._program = previousProgram;
  26607. this._isReady = true;
  26608. if (this.onError) {
  26609. this.onError(this, this._compilationError);
  26610. }
  26611. this.onErrorObservable.notifyObservers(this);
  26612. }
  26613. if (fallbacks && fallbacks.isMoreFallbacks) {
  26614. BABYLON.Tools.Error("Trying next fallback.");
  26615. this.defines = fallbacks.reduce(this.defines);
  26616. this._prepareEffect();
  26617. }
  26618. else {
  26619. if (this.onError) {
  26620. this.onError(this, this._compilationError);
  26621. }
  26622. this.onErrorObservable.notifyObservers(this);
  26623. this.onErrorObservable.clear();
  26624. // Unbind mesh reference in fallbacks
  26625. if (this._fallbacks) {
  26626. this._fallbacks.unBindMesh();
  26627. }
  26628. }
  26629. }
  26630. };
  26631. Object.defineProperty(Effect.prototype, "isSupported", {
  26632. get: function () {
  26633. return this._compilationError === "";
  26634. },
  26635. enumerable: true,
  26636. configurable: true
  26637. });
  26638. Effect.prototype._bindTexture = function (channel, texture) {
  26639. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26640. };
  26641. Effect.prototype.setTexture = function (channel, texture) {
  26642. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26643. };
  26644. Effect.prototype.setTextureArray = function (channel, textures) {
  26645. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26646. var initialPos = this._samplers.indexOf(channel);
  26647. for (var index = 1; index < textures.length; index++) {
  26648. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26649. }
  26650. }
  26651. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26652. };
  26653. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26654. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26655. };
  26656. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26657. var cache = this._valueCache[uniformName];
  26658. var flag = matrix.updateFlag;
  26659. if (cache !== undefined && cache === flag) {
  26660. return false;
  26661. }
  26662. this._valueCache[uniformName] = flag;
  26663. return true;
  26664. };
  26665. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26666. var cache = this._valueCache[uniformName];
  26667. if (!cache) {
  26668. cache = [x, y];
  26669. this._valueCache[uniformName] = cache;
  26670. return true;
  26671. }
  26672. var changed = false;
  26673. if (cache[0] !== x) {
  26674. cache[0] = x;
  26675. changed = true;
  26676. }
  26677. if (cache[1] !== y) {
  26678. cache[1] = y;
  26679. changed = true;
  26680. }
  26681. return changed;
  26682. };
  26683. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26684. var cache = this._valueCache[uniformName];
  26685. if (!cache) {
  26686. cache = [x, y, z];
  26687. this._valueCache[uniformName] = cache;
  26688. return true;
  26689. }
  26690. var changed = false;
  26691. if (cache[0] !== x) {
  26692. cache[0] = x;
  26693. changed = true;
  26694. }
  26695. if (cache[1] !== y) {
  26696. cache[1] = y;
  26697. changed = true;
  26698. }
  26699. if (cache[2] !== z) {
  26700. cache[2] = z;
  26701. changed = true;
  26702. }
  26703. return changed;
  26704. };
  26705. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26706. var cache = this._valueCache[uniformName];
  26707. if (!cache) {
  26708. cache = [x, y, z, w];
  26709. this._valueCache[uniformName] = cache;
  26710. return true;
  26711. }
  26712. var changed = false;
  26713. if (cache[0] !== x) {
  26714. cache[0] = x;
  26715. changed = true;
  26716. }
  26717. if (cache[1] !== y) {
  26718. cache[1] = y;
  26719. changed = true;
  26720. }
  26721. if (cache[2] !== z) {
  26722. cache[2] = z;
  26723. changed = true;
  26724. }
  26725. if (cache[3] !== w) {
  26726. cache[3] = w;
  26727. changed = true;
  26728. }
  26729. return changed;
  26730. };
  26731. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26732. var bufferName = this._uniformBuffersNames[name];
  26733. if (Effect._baseCache[bufferName] === buffer) {
  26734. return;
  26735. }
  26736. Effect._baseCache[bufferName] = buffer;
  26737. this._engine.bindUniformBufferBase(buffer, bufferName);
  26738. };
  26739. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26740. this._engine.bindUniformBlock(this._program, blockName, index);
  26741. };
  26742. Effect.prototype.setIntArray = function (uniformName, array) {
  26743. this._valueCache[uniformName] = null;
  26744. this._engine.setIntArray(this.getUniform(uniformName), array);
  26745. return this;
  26746. };
  26747. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26748. this._valueCache[uniformName] = null;
  26749. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26750. return this;
  26751. };
  26752. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26753. this._valueCache[uniformName] = null;
  26754. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26755. return this;
  26756. };
  26757. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26758. this._valueCache[uniformName] = null;
  26759. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26760. return this;
  26761. };
  26762. Effect.prototype.setFloatArray = function (uniformName, array) {
  26763. this._valueCache[uniformName] = null;
  26764. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26765. return this;
  26766. };
  26767. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26768. this._valueCache[uniformName] = null;
  26769. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26770. return this;
  26771. };
  26772. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26773. this._valueCache[uniformName] = null;
  26774. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26775. return this;
  26776. };
  26777. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26778. this._valueCache[uniformName] = null;
  26779. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26780. return this;
  26781. };
  26782. Effect.prototype.setArray = function (uniformName, array) {
  26783. this._valueCache[uniformName] = null;
  26784. this._engine.setArray(this.getUniform(uniformName), array);
  26785. return this;
  26786. };
  26787. Effect.prototype.setArray2 = function (uniformName, array) {
  26788. this._valueCache[uniformName] = null;
  26789. this._engine.setArray2(this.getUniform(uniformName), array);
  26790. return this;
  26791. };
  26792. Effect.prototype.setArray3 = function (uniformName, array) {
  26793. this._valueCache[uniformName] = null;
  26794. this._engine.setArray3(this.getUniform(uniformName), array);
  26795. return this;
  26796. };
  26797. Effect.prototype.setArray4 = function (uniformName, array) {
  26798. this._valueCache[uniformName] = null;
  26799. this._engine.setArray4(this.getUniform(uniformName), array);
  26800. return this;
  26801. };
  26802. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26803. if (!matrices) {
  26804. return this;
  26805. }
  26806. this._valueCache[uniformName] = null;
  26807. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26808. return this;
  26809. };
  26810. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26811. if (this._cacheMatrix(uniformName, matrix)) {
  26812. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26813. }
  26814. return this;
  26815. };
  26816. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26817. this._valueCache[uniformName] = null;
  26818. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26819. return this;
  26820. };
  26821. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26822. this._valueCache[uniformName] = null;
  26823. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26824. return this;
  26825. };
  26826. Effect.prototype.setFloat = function (uniformName, value) {
  26827. var cache = this._valueCache[uniformName];
  26828. if (cache !== undefined && cache === value)
  26829. return this;
  26830. this._valueCache[uniformName] = value;
  26831. this._engine.setFloat(this.getUniform(uniformName), value);
  26832. return this;
  26833. };
  26834. Effect.prototype.setBool = function (uniformName, bool) {
  26835. var cache = this._valueCache[uniformName];
  26836. if (cache !== undefined && cache === bool)
  26837. return this;
  26838. this._valueCache[uniformName] = bool;
  26839. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26840. return this;
  26841. };
  26842. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26843. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26844. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26845. }
  26846. return this;
  26847. };
  26848. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26849. if (this._cacheFloat2(uniformName, x, y)) {
  26850. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26851. }
  26852. return this;
  26853. };
  26854. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26855. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26856. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26857. }
  26858. return this;
  26859. };
  26860. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26861. if (this._cacheFloat3(uniformName, x, y, z)) {
  26862. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26863. }
  26864. return this;
  26865. };
  26866. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26867. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26868. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26869. }
  26870. return this;
  26871. };
  26872. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26873. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26874. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26875. }
  26876. return this;
  26877. };
  26878. Effect.prototype.setColor3 = function (uniformName, color3) {
  26879. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26880. this._engine.setColor3(this.getUniform(uniformName), color3);
  26881. }
  26882. return this;
  26883. };
  26884. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26885. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26886. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26887. }
  26888. return this;
  26889. };
  26890. Effect.ResetCache = function () {
  26891. Effect._baseCache = {};
  26892. };
  26893. Effect._uniqueIdSeed = 0;
  26894. Effect._baseCache = {};
  26895. // Statics
  26896. Effect.ShadersStore = {};
  26897. Effect.IncludesShadersStore = {};
  26898. return Effect;
  26899. }());
  26900. BABYLON.Effect = Effect;
  26901. })(BABYLON || (BABYLON = {}));
  26902. //# sourceMappingURL=babylon.effect.js.map
  26903. var BABYLON;
  26904. (function (BABYLON) {
  26905. var MaterialHelper = /** @class */ (function () {
  26906. function MaterialHelper() {
  26907. }
  26908. MaterialHelper.BindEyePosition = function (effect, scene) {
  26909. if (scene._forcedViewPosition) {
  26910. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  26911. return;
  26912. }
  26913. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  26914. };
  26915. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  26916. defines._needUVs = true;
  26917. defines[key] = true;
  26918. if (texture.getTextureMatrix().isIdentity(true)) {
  26919. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  26920. if (texture.coordinatesIndex === 0) {
  26921. defines["MAINUV1"] = true;
  26922. }
  26923. else {
  26924. defines["MAINUV2"] = true;
  26925. }
  26926. }
  26927. else {
  26928. defines[key + "DIRECTUV"] = 0;
  26929. }
  26930. };
  26931. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  26932. var matrix = texture.getTextureMatrix();
  26933. if (!matrix.isIdentity(true)) {
  26934. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  26935. }
  26936. };
  26937. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  26938. if (defines._areMiscDirty) {
  26939. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  26940. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  26941. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  26942. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  26943. }
  26944. };
  26945. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  26946. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  26947. var changed = false;
  26948. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  26949. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  26950. changed = true;
  26951. }
  26952. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  26953. defines["ALPHATEST"] = !defines["ALPHATEST"];
  26954. changed = true;
  26955. }
  26956. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  26957. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  26958. changed = true;
  26959. }
  26960. if (defines["INSTANCES"] !== useInstances) {
  26961. defines["INSTANCES"] = useInstances;
  26962. changed = true;
  26963. }
  26964. if (changed) {
  26965. defines.markAsUnprocessed();
  26966. }
  26967. };
  26968. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  26969. if (useMorphTargets === void 0) { useMorphTargets = false; }
  26970. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  26971. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  26972. return false;
  26973. }
  26974. defines._normals = defines._needNormals;
  26975. defines._uvs = defines._needUVs;
  26976. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  26977. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26978. defines["TANGENT"] = true;
  26979. }
  26980. if (defines._needUVs) {
  26981. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  26982. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  26983. }
  26984. else {
  26985. defines["UV1"] = false;
  26986. defines["UV2"] = false;
  26987. }
  26988. if (useVertexColor) {
  26989. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  26990. defines["VERTEXCOLOR"] = hasVertexColors;
  26991. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  26992. }
  26993. if (useBones) {
  26994. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26995. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  26996. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  26997. }
  26998. else {
  26999. defines["NUM_BONE_INFLUENCERS"] = 0;
  27000. defines["BonesPerMesh"] = 0;
  27001. }
  27002. }
  27003. if (useMorphTargets) {
  27004. var manager = mesh.morphTargetManager;
  27005. if (manager) {
  27006. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  27007. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  27008. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  27009. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  27010. }
  27011. else {
  27012. defines["MORPHTARGETS_TANGENT"] = false;
  27013. defines["MORPHTARGETS_NORMAL"] = false;
  27014. defines["MORPHTARGETS"] = false;
  27015. defines["NUM_MORPH_INFLUENCERS"] = 0;
  27016. }
  27017. }
  27018. return true;
  27019. };
  27020. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  27021. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27022. if (disableLighting === void 0) { disableLighting = false; }
  27023. if (!defines._areLightsDirty) {
  27024. return defines._needNormals;
  27025. }
  27026. var lightIndex = 0;
  27027. var needNormals = false;
  27028. var needRebuild = false;
  27029. var lightmapMode = false;
  27030. var shadowEnabled = false;
  27031. var specularEnabled = false;
  27032. if (scene.lightsEnabled && !disableLighting) {
  27033. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  27034. var light = _a[_i];
  27035. needNormals = true;
  27036. if (defines["LIGHT" + lightIndex] === undefined) {
  27037. needRebuild = true;
  27038. }
  27039. defines["LIGHT" + lightIndex] = true;
  27040. defines["SPOTLIGHT" + lightIndex] = false;
  27041. defines["HEMILIGHT" + lightIndex] = false;
  27042. defines["POINTLIGHT" + lightIndex] = false;
  27043. defines["DIRLIGHT" + lightIndex] = false;
  27044. var type;
  27045. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  27046. type = "SPOTLIGHT" + lightIndex;
  27047. }
  27048. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  27049. type = "HEMILIGHT" + lightIndex;
  27050. }
  27051. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  27052. type = "POINTLIGHT" + lightIndex;
  27053. }
  27054. else {
  27055. type = "DIRLIGHT" + lightIndex;
  27056. }
  27057. defines[type] = true;
  27058. // Specular
  27059. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  27060. specularEnabled = true;
  27061. }
  27062. // Shadows
  27063. defines["SHADOW" + lightIndex] = false;
  27064. defines["SHADOWPCF" + lightIndex] = false;
  27065. defines["SHADOWESM" + lightIndex] = false;
  27066. defines["SHADOWCUBE" + lightIndex] = false;
  27067. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  27068. var shadowGenerator = light.getShadowGenerator();
  27069. if (shadowGenerator) {
  27070. shadowEnabled = true;
  27071. shadowGenerator.prepareDefines(defines, lightIndex);
  27072. }
  27073. }
  27074. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  27075. lightmapMode = true;
  27076. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  27077. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  27078. }
  27079. else {
  27080. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  27081. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  27082. }
  27083. lightIndex++;
  27084. if (lightIndex === maxSimultaneousLights)
  27085. break;
  27086. }
  27087. }
  27088. defines["SPECULARTERM"] = specularEnabled;
  27089. defines["SHADOWS"] = shadowEnabled;
  27090. // Resetting all other lights if any
  27091. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  27092. if (defines["LIGHT" + index] !== undefined) {
  27093. defines["LIGHT" + index] = false;
  27094. defines["HEMILIGHT" + lightIndex] = false;
  27095. defines["POINTLIGHT" + lightIndex] = false;
  27096. defines["DIRLIGHT" + lightIndex] = false;
  27097. defines["SPOTLIGHT" + lightIndex] = false;
  27098. defines["SHADOW" + lightIndex] = false;
  27099. }
  27100. }
  27101. var caps = scene.getEngine().getCaps();
  27102. if (defines["SHADOWFLOAT"] === undefined) {
  27103. needRebuild = true;
  27104. }
  27105. defines["SHADOWFLOAT"] = shadowEnabled &&
  27106. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  27107. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  27108. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  27109. if (needRebuild) {
  27110. defines.rebuild();
  27111. }
  27112. return needNormals;
  27113. };
  27114. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  27115. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27116. var uniformsList;
  27117. var uniformBuffersList = null;
  27118. if (uniformsListOrOptions.uniformsNames) {
  27119. var options = uniformsListOrOptions;
  27120. uniformsList = options.uniformsNames;
  27121. uniformBuffersList = options.uniformBuffersNames;
  27122. samplersList = options.samplers;
  27123. defines = options.defines;
  27124. maxSimultaneousLights = options.maxSimultaneousLights;
  27125. }
  27126. else {
  27127. uniformsList = uniformsListOrOptions;
  27128. if (!samplersList) {
  27129. samplersList = [];
  27130. }
  27131. }
  27132. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  27133. if (!defines["LIGHT" + lightIndex]) {
  27134. break;
  27135. }
  27136. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  27137. if (uniformBuffersList) {
  27138. uniformBuffersList.push("Light" + lightIndex);
  27139. }
  27140. samplersList.push("shadowSampler" + lightIndex);
  27141. }
  27142. if (defines["NUM_MORPH_INFLUENCERS"]) {
  27143. uniformsList.push("morphTargetInfluences");
  27144. }
  27145. };
  27146. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  27147. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27148. if (rank === void 0) { rank = 0; }
  27149. var lightFallbackRank = 0;
  27150. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  27151. if (!defines["LIGHT" + lightIndex]) {
  27152. break;
  27153. }
  27154. if (lightIndex > 0) {
  27155. lightFallbackRank = rank + lightIndex;
  27156. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  27157. }
  27158. if (!defines["SHADOWS"]) {
  27159. if (defines["SHADOW" + lightIndex]) {
  27160. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  27161. }
  27162. if (defines["SHADOWPCF" + lightIndex]) {
  27163. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  27164. }
  27165. if (defines["SHADOWESM" + lightIndex]) {
  27166. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  27167. }
  27168. }
  27169. }
  27170. return lightFallbackRank++;
  27171. };
  27172. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  27173. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  27174. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  27175. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  27176. var manager = mesh.morphTargetManager;
  27177. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  27178. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  27179. for (var index = 0; index < influencers; index++) {
  27180. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  27181. if (normal) {
  27182. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  27183. }
  27184. if (tangent) {
  27185. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  27186. }
  27187. if (attribs.length > maxAttributesCount) {
  27188. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  27189. }
  27190. }
  27191. }
  27192. };
  27193. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  27194. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  27195. fallbacks.addCPUSkinningFallback(0, mesh);
  27196. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27197. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27198. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  27199. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  27200. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  27201. }
  27202. }
  27203. };
  27204. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  27205. if (defines["INSTANCES"]) {
  27206. attribs.push("world0");
  27207. attribs.push("world1");
  27208. attribs.push("world2");
  27209. attribs.push("world3");
  27210. }
  27211. };
  27212. // Bindings
  27213. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  27214. if (light.shadowEnabled && mesh.receiveShadows) {
  27215. var shadowGenerator = light.getShadowGenerator();
  27216. if (shadowGenerator) {
  27217. shadowGenerator.bindShadowLight(lightIndex, effect);
  27218. }
  27219. }
  27220. };
  27221. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  27222. light.transferToEffect(effect, lightIndex + "");
  27223. };
  27224. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  27225. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  27226. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  27227. var lightIndex = 0;
  27228. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  27229. var light = _a[_i];
  27230. var scaledIntensity = light.getScaledIntensity();
  27231. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  27232. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  27233. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  27234. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  27235. if (defines["SPECULARTERM"]) {
  27236. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  27237. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  27238. }
  27239. // Shadows
  27240. if (scene.shadowsEnabled) {
  27241. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  27242. }
  27243. light._uniformBuffer.update();
  27244. lightIndex++;
  27245. if (lightIndex === maxSimultaneousLights)
  27246. break;
  27247. }
  27248. };
  27249. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  27250. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  27251. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  27252. effect.setColor3("vFogColor", scene.fogColor);
  27253. }
  27254. };
  27255. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  27256. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  27257. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  27258. if (matrices && effect) {
  27259. effect.setMatrices("mBones", matrices);
  27260. }
  27261. }
  27262. };
  27263. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  27264. var manager = abstractMesh.morphTargetManager;
  27265. if (!abstractMesh || !manager) {
  27266. return;
  27267. }
  27268. effect.setFloatArray("morphTargetInfluences", manager.influences);
  27269. };
  27270. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  27271. if (defines["LOGARITHMICDEPTH"]) {
  27272. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  27273. }
  27274. };
  27275. MaterialHelper.BindClipPlane = function (effect, scene) {
  27276. if (scene.clipPlane) {
  27277. var clipPlane = scene.clipPlane;
  27278. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27279. }
  27280. };
  27281. return MaterialHelper;
  27282. }());
  27283. BABYLON.MaterialHelper = MaterialHelper;
  27284. })(BABYLON || (BABYLON = {}));
  27285. //# sourceMappingURL=babylon.materialHelper.js.map
  27286. var BABYLON;
  27287. (function (BABYLON) {
  27288. var MaterialDefines = /** @class */ (function () {
  27289. function MaterialDefines() {
  27290. this._isDirty = true;
  27291. this._areLightsDirty = true;
  27292. this._areAttributesDirty = true;
  27293. this._areTexturesDirty = true;
  27294. this._areFresnelDirty = true;
  27295. this._areMiscDirty = true;
  27296. this._areImageProcessingDirty = true;
  27297. this._normals = false;
  27298. this._uvs = false;
  27299. this._needNormals = false;
  27300. this._needUVs = false;
  27301. }
  27302. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27303. get: function () {
  27304. return this._isDirty;
  27305. },
  27306. enumerable: true,
  27307. configurable: true
  27308. });
  27309. MaterialDefines.prototype.markAsProcessed = function () {
  27310. this._isDirty = false;
  27311. this._areAttributesDirty = false;
  27312. this._areTexturesDirty = false;
  27313. this._areFresnelDirty = false;
  27314. this._areLightsDirty = false;
  27315. this._areMiscDirty = false;
  27316. this._areImageProcessingDirty = false;
  27317. };
  27318. MaterialDefines.prototype.markAsUnprocessed = function () {
  27319. this._isDirty = true;
  27320. };
  27321. MaterialDefines.prototype.markAllAsDirty = function () {
  27322. this._areTexturesDirty = true;
  27323. this._areAttributesDirty = true;
  27324. this._areLightsDirty = true;
  27325. this._areFresnelDirty = true;
  27326. this._areMiscDirty = true;
  27327. this._areImageProcessingDirty = true;
  27328. this._isDirty = true;
  27329. };
  27330. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27331. this._areImageProcessingDirty = true;
  27332. this._isDirty = true;
  27333. };
  27334. MaterialDefines.prototype.markAsLightDirty = function () {
  27335. this._areLightsDirty = true;
  27336. this._isDirty = true;
  27337. };
  27338. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27339. this._areAttributesDirty = true;
  27340. this._isDirty = true;
  27341. };
  27342. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27343. this._areTexturesDirty = true;
  27344. this._isDirty = true;
  27345. };
  27346. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27347. this._areFresnelDirty = true;
  27348. this._isDirty = true;
  27349. };
  27350. MaterialDefines.prototype.markAsMiscDirty = function () {
  27351. this._areMiscDirty = true;
  27352. this._isDirty = true;
  27353. };
  27354. MaterialDefines.prototype.rebuild = function () {
  27355. if (this._keys) {
  27356. delete this._keys;
  27357. }
  27358. this._keys = [];
  27359. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27360. var key = _a[_i];
  27361. if (key[0] === "_") {
  27362. continue;
  27363. }
  27364. this._keys.push(key);
  27365. }
  27366. };
  27367. MaterialDefines.prototype.isEqual = function (other) {
  27368. if (this._keys.length !== other._keys.length) {
  27369. return false;
  27370. }
  27371. for (var index = 0; index < this._keys.length; index++) {
  27372. var prop = this._keys[index];
  27373. if (this[prop] !== other[prop]) {
  27374. return false;
  27375. }
  27376. }
  27377. return true;
  27378. };
  27379. MaterialDefines.prototype.cloneTo = function (other) {
  27380. if (this._keys.length !== other._keys.length) {
  27381. other._keys = this._keys.slice(0);
  27382. }
  27383. for (var index = 0; index < this._keys.length; index++) {
  27384. var prop = this._keys[index];
  27385. other[prop] = this[prop];
  27386. }
  27387. };
  27388. MaterialDefines.prototype.reset = function () {
  27389. for (var index = 0; index < this._keys.length; index++) {
  27390. var prop = this._keys[index];
  27391. if (typeof (this[prop]) === "number") {
  27392. this[prop] = 0;
  27393. }
  27394. else {
  27395. this[prop] = false;
  27396. }
  27397. }
  27398. };
  27399. MaterialDefines.prototype.toString = function () {
  27400. var result = "";
  27401. for (var index = 0; index < this._keys.length; index++) {
  27402. var prop = this._keys[index];
  27403. var value = this[prop];
  27404. if (typeof (value) === "number") {
  27405. result += "#define " + prop + " " + this[prop] + "\n";
  27406. }
  27407. else if (value) {
  27408. result += "#define " + prop + "\n";
  27409. }
  27410. }
  27411. return result;
  27412. };
  27413. return MaterialDefines;
  27414. }());
  27415. BABYLON.MaterialDefines = MaterialDefines;
  27416. var Material = /** @class */ (function () {
  27417. function Material(name, scene, doNotAdd) {
  27418. this.checkReadyOnEveryCall = false;
  27419. this.checkReadyOnlyOnce = false;
  27420. this.state = "";
  27421. this.alpha = 1.0;
  27422. this._backFaceCulling = true;
  27423. this.doNotSerialize = false;
  27424. this.storeEffectOnSubMeshes = false;
  27425. /**
  27426. * An event triggered when the material is disposed.
  27427. * @type {BABYLON.Observable}
  27428. */
  27429. this.onDisposeObservable = new BABYLON.Observable();
  27430. /**
  27431. * An event triggered when the material is bound.
  27432. * @type {BABYLON.Observable}
  27433. */
  27434. this.onBindObservable = new BABYLON.Observable();
  27435. /**
  27436. * An event triggered when the material is unbound.
  27437. * @type {BABYLON.Observable}
  27438. */
  27439. this.onUnBindObservable = new BABYLON.Observable();
  27440. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27441. this._needDepthPrePass = false;
  27442. this.disableDepthWrite = false;
  27443. this.forceDepthWrite = false;
  27444. this.separateCullingPass = false;
  27445. this._fogEnabled = true;
  27446. this.pointSize = 1.0;
  27447. this.zOffset = 0;
  27448. this._wasPreviouslyReady = false;
  27449. this._fillMode = Material.TriangleFillMode;
  27450. this.name = name;
  27451. this.id = name || BABYLON.Tools.RandomId();
  27452. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27453. if (this._scene.useRightHandedSystem) {
  27454. this.sideOrientation = Material.ClockWiseSideOrientation;
  27455. }
  27456. else {
  27457. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27458. }
  27459. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27460. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27461. if (!doNotAdd) {
  27462. this._scene.materials.push(this);
  27463. }
  27464. }
  27465. Object.defineProperty(Material, "TriangleFillMode", {
  27466. get: function () {
  27467. return Material._TriangleFillMode;
  27468. },
  27469. enumerable: true,
  27470. configurable: true
  27471. });
  27472. Object.defineProperty(Material, "WireFrameFillMode", {
  27473. get: function () {
  27474. return Material._WireFrameFillMode;
  27475. },
  27476. enumerable: true,
  27477. configurable: true
  27478. });
  27479. Object.defineProperty(Material, "PointFillMode", {
  27480. get: function () {
  27481. return Material._PointFillMode;
  27482. },
  27483. enumerable: true,
  27484. configurable: true
  27485. });
  27486. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27487. get: function () {
  27488. return Material._ClockWiseSideOrientation;
  27489. },
  27490. enumerable: true,
  27491. configurable: true
  27492. });
  27493. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27494. get: function () {
  27495. return Material._CounterClockWiseSideOrientation;
  27496. },
  27497. enumerable: true,
  27498. configurable: true
  27499. });
  27500. Object.defineProperty(Material, "TextureDirtyFlag", {
  27501. get: function () {
  27502. return Material._TextureDirtyFlag;
  27503. },
  27504. enumerable: true,
  27505. configurable: true
  27506. });
  27507. Object.defineProperty(Material, "LightDirtyFlag", {
  27508. get: function () {
  27509. return Material._LightDirtyFlag;
  27510. },
  27511. enumerable: true,
  27512. configurable: true
  27513. });
  27514. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27515. get: function () {
  27516. return Material._FresnelDirtyFlag;
  27517. },
  27518. enumerable: true,
  27519. configurable: true
  27520. });
  27521. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27522. get: function () {
  27523. return Material._AttributesDirtyFlag;
  27524. },
  27525. enumerable: true,
  27526. configurable: true
  27527. });
  27528. Object.defineProperty(Material, "MiscDirtyFlag", {
  27529. get: function () {
  27530. return Material._MiscDirtyFlag;
  27531. },
  27532. enumerable: true,
  27533. configurable: true
  27534. });
  27535. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27536. get: function () {
  27537. return this._backFaceCulling;
  27538. },
  27539. set: function (value) {
  27540. if (this._backFaceCulling === value) {
  27541. return;
  27542. }
  27543. this._backFaceCulling = value;
  27544. this.markAsDirty(Material.TextureDirtyFlag);
  27545. },
  27546. enumerable: true,
  27547. configurable: true
  27548. });
  27549. Object.defineProperty(Material.prototype, "onDispose", {
  27550. set: function (callback) {
  27551. if (this._onDisposeObserver) {
  27552. this.onDisposeObservable.remove(this._onDisposeObserver);
  27553. }
  27554. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27555. },
  27556. enumerable: true,
  27557. configurable: true
  27558. });
  27559. Object.defineProperty(Material.prototype, "onBind", {
  27560. set: function (callback) {
  27561. if (this._onBindObserver) {
  27562. this.onBindObservable.remove(this._onBindObserver);
  27563. }
  27564. this._onBindObserver = this.onBindObservable.add(callback);
  27565. },
  27566. enumerable: true,
  27567. configurable: true
  27568. });
  27569. Object.defineProperty(Material.prototype, "alphaMode", {
  27570. get: function () {
  27571. return this._alphaMode;
  27572. },
  27573. set: function (value) {
  27574. if (this._alphaMode === value) {
  27575. return;
  27576. }
  27577. this._alphaMode = value;
  27578. this.markAsDirty(Material.TextureDirtyFlag);
  27579. },
  27580. enumerable: true,
  27581. configurable: true
  27582. });
  27583. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27584. get: function () {
  27585. return this._needDepthPrePass;
  27586. },
  27587. set: function (value) {
  27588. if (this._needDepthPrePass === value) {
  27589. return;
  27590. }
  27591. this._needDepthPrePass = value;
  27592. if (this._needDepthPrePass) {
  27593. this.checkReadyOnEveryCall = true;
  27594. }
  27595. },
  27596. enumerable: true,
  27597. configurable: true
  27598. });
  27599. Object.defineProperty(Material.prototype, "fogEnabled", {
  27600. get: function () {
  27601. return this._fogEnabled;
  27602. },
  27603. set: function (value) {
  27604. if (this._fogEnabled === value) {
  27605. return;
  27606. }
  27607. this._fogEnabled = value;
  27608. this.markAsDirty(Material.MiscDirtyFlag);
  27609. },
  27610. enumerable: true,
  27611. configurable: true
  27612. });
  27613. Object.defineProperty(Material.prototype, "wireframe", {
  27614. get: function () {
  27615. return this._fillMode === Material.WireFrameFillMode;
  27616. },
  27617. set: function (value) {
  27618. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27619. },
  27620. enumerable: true,
  27621. configurable: true
  27622. });
  27623. Object.defineProperty(Material.prototype, "pointsCloud", {
  27624. get: function () {
  27625. return this._fillMode === Material.PointFillMode;
  27626. },
  27627. set: function (value) {
  27628. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27629. },
  27630. enumerable: true,
  27631. configurable: true
  27632. });
  27633. Object.defineProperty(Material.prototype, "fillMode", {
  27634. get: function () {
  27635. return this._fillMode;
  27636. },
  27637. set: function (value) {
  27638. if (this._fillMode === value) {
  27639. return;
  27640. }
  27641. this._fillMode = value;
  27642. this.markAsDirty(Material.MiscDirtyFlag);
  27643. },
  27644. enumerable: true,
  27645. configurable: true
  27646. });
  27647. /**
  27648. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27649. * subclasses should override adding information pertainent to themselves
  27650. */
  27651. Material.prototype.toString = function (fullDetails) {
  27652. var ret = "Name: " + this.name;
  27653. if (fullDetails) {
  27654. }
  27655. return ret;
  27656. };
  27657. /**
  27658. * Child classes can use it to update shaders
  27659. */
  27660. Material.prototype.getClassName = function () {
  27661. return "Material";
  27662. };
  27663. Object.defineProperty(Material.prototype, "isFrozen", {
  27664. get: function () {
  27665. return this.checkReadyOnlyOnce;
  27666. },
  27667. enumerable: true,
  27668. configurable: true
  27669. });
  27670. Material.prototype.freeze = function () {
  27671. this.checkReadyOnlyOnce = true;
  27672. };
  27673. Material.prototype.unfreeze = function () {
  27674. this.checkReadyOnlyOnce = false;
  27675. };
  27676. Material.prototype.isReady = function (mesh, useInstances) {
  27677. return true;
  27678. };
  27679. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27680. return false;
  27681. };
  27682. Material.prototype.getEffect = function () {
  27683. return this._effect;
  27684. };
  27685. Material.prototype.getScene = function () {
  27686. return this._scene;
  27687. };
  27688. Material.prototype.needAlphaBlending = function () {
  27689. return (this.alpha < 1.0);
  27690. };
  27691. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  27692. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  27693. };
  27694. Material.prototype.needAlphaTesting = function () {
  27695. return false;
  27696. };
  27697. Material.prototype.getAlphaTestTexture = function () {
  27698. return null;
  27699. };
  27700. Material.prototype.markDirty = function () {
  27701. this._wasPreviouslyReady = false;
  27702. };
  27703. Material.prototype._preBind = function (effect, overrideOrientation) {
  27704. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27705. var engine = this._scene.getEngine();
  27706. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27707. var reverse = orientation === Material.ClockWiseSideOrientation;
  27708. engine.enableEffect(effect ? effect : this._effect);
  27709. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27710. return reverse;
  27711. };
  27712. Material.prototype.bind = function (world, mesh) {
  27713. };
  27714. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27715. };
  27716. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27717. };
  27718. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27719. sceneUbo.bindToEffect(effect, "Scene");
  27720. };
  27721. Material.prototype.bindView = function (effect) {
  27722. if (!this._useUBO) {
  27723. effect.setMatrix("view", this.getScene().getViewMatrix());
  27724. }
  27725. else {
  27726. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27727. }
  27728. };
  27729. Material.prototype.bindViewProjection = function (effect) {
  27730. if (!this._useUBO) {
  27731. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27732. }
  27733. else {
  27734. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27735. }
  27736. };
  27737. Material.prototype._afterBind = function (mesh) {
  27738. this._scene._cachedMaterial = this;
  27739. if (mesh) {
  27740. this._scene._cachedVisibility = mesh.visibility;
  27741. }
  27742. else {
  27743. this._scene._cachedVisibility = 1;
  27744. }
  27745. if (mesh) {
  27746. this.onBindObservable.notifyObservers(mesh);
  27747. }
  27748. if (this.disableDepthWrite) {
  27749. var engine = this._scene.getEngine();
  27750. this._cachedDepthWriteState = engine.getDepthWrite();
  27751. engine.setDepthWrite(false);
  27752. }
  27753. };
  27754. Material.prototype.unbind = function () {
  27755. this.onUnBindObservable.notifyObservers(this);
  27756. if (this.disableDepthWrite) {
  27757. var engine = this._scene.getEngine();
  27758. engine.setDepthWrite(this._cachedDepthWriteState);
  27759. }
  27760. };
  27761. Material.prototype.getActiveTextures = function () {
  27762. return [];
  27763. };
  27764. Material.prototype.hasTexture = function (texture) {
  27765. return false;
  27766. };
  27767. Material.prototype.clone = function (name) {
  27768. return null;
  27769. };
  27770. Material.prototype.getBindedMeshes = function () {
  27771. var result = new Array();
  27772. for (var index = 0; index < this._scene.meshes.length; index++) {
  27773. var mesh = this._scene.meshes[index];
  27774. if (mesh.material === this) {
  27775. result.push(mesh);
  27776. }
  27777. }
  27778. return result;
  27779. };
  27780. /**
  27781. * Force shader compilation including textures ready check
  27782. */
  27783. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27784. var _this = this;
  27785. var subMesh = new BABYLON.BaseSubMesh();
  27786. var scene = this.getScene();
  27787. var engine = scene.getEngine();
  27788. var checkReady = function () {
  27789. if (!_this._scene || !_this._scene.getEngine()) {
  27790. return;
  27791. }
  27792. if (subMesh._materialDefines) {
  27793. subMesh._materialDefines._renderId = -1;
  27794. }
  27795. var alphaTestState = engine.getAlphaTesting();
  27796. var clipPlaneState = scene.clipPlane;
  27797. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  27798. if (options && options.clipPlane) {
  27799. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27800. }
  27801. if (_this.storeEffectOnSubMeshes) {
  27802. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27803. if (onCompiled) {
  27804. onCompiled(_this);
  27805. }
  27806. }
  27807. else {
  27808. setTimeout(checkReady, 16);
  27809. }
  27810. }
  27811. else {
  27812. if (_this.isReady(mesh)) {
  27813. if (onCompiled) {
  27814. onCompiled(_this);
  27815. }
  27816. }
  27817. else {
  27818. setTimeout(checkReady, 16);
  27819. }
  27820. }
  27821. engine.setAlphaTesting(alphaTestState);
  27822. if (options && options.clipPlane) {
  27823. scene.clipPlane = clipPlaneState;
  27824. }
  27825. };
  27826. checkReady();
  27827. };
  27828. Material.prototype.markAsDirty = function (flag) {
  27829. if (flag & Material.TextureDirtyFlag) {
  27830. this._markAllSubMeshesAsTexturesDirty();
  27831. }
  27832. if (flag & Material.LightDirtyFlag) {
  27833. this._markAllSubMeshesAsLightsDirty();
  27834. }
  27835. if (flag & Material.FresnelDirtyFlag) {
  27836. this._markAllSubMeshesAsFresnelDirty();
  27837. }
  27838. if (flag & Material.AttributesDirtyFlag) {
  27839. this._markAllSubMeshesAsAttributesDirty();
  27840. }
  27841. if (flag & Material.MiscDirtyFlag) {
  27842. this._markAllSubMeshesAsMiscDirty();
  27843. }
  27844. this.getScene().resetCachedMaterial();
  27845. };
  27846. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27847. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27848. var mesh = _a[_i];
  27849. if (!mesh.subMeshes) {
  27850. continue;
  27851. }
  27852. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27853. var subMesh = _c[_b];
  27854. if (subMesh.getMaterial() !== this) {
  27855. continue;
  27856. }
  27857. if (!subMesh._materialDefines) {
  27858. continue;
  27859. }
  27860. func(subMesh._materialDefines);
  27861. }
  27862. }
  27863. };
  27864. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27865. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27866. };
  27867. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27868. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27869. };
  27870. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27871. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27872. };
  27873. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27874. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27875. };
  27876. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27877. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27878. };
  27879. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27880. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27881. };
  27882. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27883. // Animations
  27884. this.getScene().stopAnimation(this);
  27885. // Remove from scene
  27886. var index = this._scene.materials.indexOf(this);
  27887. if (index >= 0) {
  27888. this._scene.materials.splice(index, 1);
  27889. }
  27890. // Remove from meshes
  27891. for (index = 0; index < this._scene.meshes.length; index++) {
  27892. var mesh = this._scene.meshes[index];
  27893. if (mesh.material === this) {
  27894. mesh.material = null;
  27895. if (mesh.geometry) {
  27896. var geometry = (mesh.geometry);
  27897. if (this.storeEffectOnSubMeshes) {
  27898. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27899. var subMesh = _a[_i];
  27900. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27901. if (forceDisposeEffect && subMesh._materialEffect) {
  27902. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27903. }
  27904. }
  27905. }
  27906. else {
  27907. geometry._releaseVertexArrayObject(this._effect);
  27908. }
  27909. }
  27910. }
  27911. }
  27912. this._uniformBuffer.dispose();
  27913. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27914. if (forceDisposeEffect && this._effect) {
  27915. if (!this.storeEffectOnSubMeshes) {
  27916. this._scene.getEngine()._releaseEffect(this._effect);
  27917. }
  27918. this._effect = null;
  27919. }
  27920. // Callback
  27921. this.onDisposeObservable.notifyObservers(this);
  27922. this.onDisposeObservable.clear();
  27923. this.onBindObservable.clear();
  27924. this.onUnBindObservable.clear();
  27925. };
  27926. Material.prototype.serialize = function () {
  27927. return BABYLON.SerializationHelper.Serialize(this);
  27928. };
  27929. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27930. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27931. multiMaterial.id = parsedMultiMaterial.id;
  27932. if (BABYLON.Tags) {
  27933. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27934. }
  27935. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27936. var subMatId = parsedMultiMaterial.materials[matIndex];
  27937. if (subMatId) {
  27938. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27939. }
  27940. else {
  27941. multiMaterial.subMaterials.push(null);
  27942. }
  27943. }
  27944. return multiMaterial;
  27945. };
  27946. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27947. if (!parsedMaterial.customType) {
  27948. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27949. }
  27950. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  27951. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  27952. if (!BABYLON.LegacyPBRMaterial) {
  27953. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  27954. return;
  27955. }
  27956. }
  27957. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27958. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27959. ;
  27960. };
  27961. Material._TriangleFillMode = 0;
  27962. Material._WireFrameFillMode = 1;
  27963. Material._PointFillMode = 2;
  27964. Material._ClockWiseSideOrientation = 0;
  27965. Material._CounterClockWiseSideOrientation = 1;
  27966. Material._TextureDirtyFlag = 1;
  27967. Material._LightDirtyFlag = 2;
  27968. Material._FresnelDirtyFlag = 4;
  27969. Material._AttributesDirtyFlag = 8;
  27970. Material._MiscDirtyFlag = 16;
  27971. __decorate([
  27972. BABYLON.serialize()
  27973. ], Material.prototype, "id", void 0);
  27974. __decorate([
  27975. BABYLON.serialize()
  27976. ], Material.prototype, "name", void 0);
  27977. __decorate([
  27978. BABYLON.serialize()
  27979. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27980. __decorate([
  27981. BABYLON.serialize()
  27982. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27983. __decorate([
  27984. BABYLON.serialize()
  27985. ], Material.prototype, "state", void 0);
  27986. __decorate([
  27987. BABYLON.serialize()
  27988. ], Material.prototype, "alpha", void 0);
  27989. __decorate([
  27990. BABYLON.serialize("backFaceCulling")
  27991. ], Material.prototype, "_backFaceCulling", void 0);
  27992. __decorate([
  27993. BABYLON.serialize()
  27994. ], Material.prototype, "sideOrientation", void 0);
  27995. __decorate([
  27996. BABYLON.serialize("alphaMode")
  27997. ], Material.prototype, "_alphaMode", void 0);
  27998. __decorate([
  27999. BABYLON.serialize()
  28000. ], Material.prototype, "_needDepthPrePass", void 0);
  28001. __decorate([
  28002. BABYLON.serialize()
  28003. ], Material.prototype, "disableDepthWrite", void 0);
  28004. __decorate([
  28005. BABYLON.serialize()
  28006. ], Material.prototype, "forceDepthWrite", void 0);
  28007. __decorate([
  28008. BABYLON.serialize()
  28009. ], Material.prototype, "separateCullingPass", void 0);
  28010. __decorate([
  28011. BABYLON.serialize("fogEnabled")
  28012. ], Material.prototype, "_fogEnabled", void 0);
  28013. __decorate([
  28014. BABYLON.serialize()
  28015. ], Material.prototype, "pointSize", void 0);
  28016. __decorate([
  28017. BABYLON.serialize()
  28018. ], Material.prototype, "zOffset", void 0);
  28019. __decorate([
  28020. BABYLON.serialize()
  28021. ], Material.prototype, "wireframe", null);
  28022. __decorate([
  28023. BABYLON.serialize()
  28024. ], Material.prototype, "pointsCloud", null);
  28025. __decorate([
  28026. BABYLON.serialize()
  28027. ], Material.prototype, "fillMode", null);
  28028. return Material;
  28029. }());
  28030. BABYLON.Material = Material;
  28031. })(BABYLON || (BABYLON = {}));
  28032. //# sourceMappingURL=babylon.material.js.map
  28033. var BABYLON;
  28034. (function (BABYLON) {
  28035. var UniformBuffer = /** @class */ (function () {
  28036. /**
  28037. * Uniform buffer objects.
  28038. *
  28039. * Handles blocks of uniform on the GPU.
  28040. *
  28041. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28042. *
  28043. * For more information, please refer to :
  28044. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28045. */
  28046. function UniformBuffer(engine, data, dynamic) {
  28047. this._engine = engine;
  28048. this._noUBO = !engine.supportsUniformBuffers;
  28049. this._dynamic = dynamic;
  28050. this._data = data || [];
  28051. this._uniformLocations = {};
  28052. this._uniformSizes = {};
  28053. this._uniformLocationPointer = 0;
  28054. this._needSync = false;
  28055. if (this._noUBO) {
  28056. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28057. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28058. this.updateFloat = this._updateFloatForEffect;
  28059. this.updateFloat2 = this._updateFloat2ForEffect;
  28060. this.updateFloat3 = this._updateFloat3ForEffect;
  28061. this.updateFloat4 = this._updateFloat4ForEffect;
  28062. this.updateMatrix = this._updateMatrixForEffect;
  28063. this.updateVector3 = this._updateVector3ForEffect;
  28064. this.updateVector4 = this._updateVector4ForEffect;
  28065. this.updateColor3 = this._updateColor3ForEffect;
  28066. this.updateColor4 = this._updateColor4ForEffect;
  28067. }
  28068. else {
  28069. this._engine._uniformBuffers.push(this);
  28070. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28071. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28072. this.updateFloat = this._updateFloatForUniform;
  28073. this.updateFloat2 = this._updateFloat2ForUniform;
  28074. this.updateFloat3 = this._updateFloat3ForUniform;
  28075. this.updateFloat4 = this._updateFloat4ForUniform;
  28076. this.updateMatrix = this._updateMatrixForUniform;
  28077. this.updateVector3 = this._updateVector3ForUniform;
  28078. this.updateVector4 = this._updateVector4ForUniform;
  28079. this.updateColor3 = this._updateColor3ForUniform;
  28080. this.updateColor4 = this._updateColor4ForUniform;
  28081. }
  28082. }
  28083. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28084. // Properties
  28085. /**
  28086. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28087. * or just falling back on setUniformXXX calls.
  28088. */
  28089. get: function () {
  28090. return !this._noUBO;
  28091. },
  28092. enumerable: true,
  28093. configurable: true
  28094. });
  28095. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28096. /**
  28097. * Indicates if the WebGL underlying uniform buffer is in sync
  28098. * with the javascript cache data.
  28099. */
  28100. get: function () {
  28101. return !this._needSync;
  28102. },
  28103. enumerable: true,
  28104. configurable: true
  28105. });
  28106. /**
  28107. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28108. * Also, a dynamic UniformBuffer will disable cache verification and always
  28109. * update the underlying WebGL uniform buffer to the GPU.
  28110. */
  28111. UniformBuffer.prototype.isDynamic = function () {
  28112. return this._dynamic !== undefined;
  28113. };
  28114. /**
  28115. * The data cache on JS side.
  28116. */
  28117. UniformBuffer.prototype.getData = function () {
  28118. return this._bufferData;
  28119. };
  28120. /**
  28121. * The underlying WebGL Uniform buffer.
  28122. */
  28123. UniformBuffer.prototype.getBuffer = function () {
  28124. return this._buffer;
  28125. };
  28126. /**
  28127. * std140 layout specifies how to align data within an UBO structure.
  28128. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28129. * for specs.
  28130. */
  28131. UniformBuffer.prototype._fillAlignment = function (size) {
  28132. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28133. // and 4x4 matrices
  28134. // TODO : change if other types are used
  28135. var alignment;
  28136. if (size <= 2) {
  28137. alignment = size;
  28138. }
  28139. else {
  28140. alignment = 4;
  28141. }
  28142. if ((this._uniformLocationPointer % alignment) !== 0) {
  28143. var oldPointer = this._uniformLocationPointer;
  28144. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28145. var diff = this._uniformLocationPointer - oldPointer;
  28146. for (var i = 0; i < diff; i++) {
  28147. this._data.push(0);
  28148. }
  28149. }
  28150. };
  28151. /**
  28152. * Adds an uniform in the buffer.
  28153. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28154. * for the layout to be correct !
  28155. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28156. * @param {number|number[]} size Data size, or data directly.
  28157. */
  28158. UniformBuffer.prototype.addUniform = function (name, size) {
  28159. if (this._noUBO) {
  28160. return;
  28161. }
  28162. if (this._uniformLocations[name] !== undefined) {
  28163. // Already existing uniform
  28164. return;
  28165. }
  28166. // This function must be called in the order of the shader layout !
  28167. // size can be the size of the uniform, or data directly
  28168. var data;
  28169. if (size instanceof Array) {
  28170. data = size;
  28171. size = data.length;
  28172. }
  28173. else {
  28174. size = size;
  28175. data = [];
  28176. // Fill with zeros
  28177. for (var i = 0; i < size; i++) {
  28178. data.push(0);
  28179. }
  28180. }
  28181. this._fillAlignment(size);
  28182. this._uniformSizes[name] = size;
  28183. this._uniformLocations[name] = this._uniformLocationPointer;
  28184. this._uniformLocationPointer += size;
  28185. for (var i = 0; i < size; i++) {
  28186. this._data.push(data[i]);
  28187. }
  28188. this._needSync = true;
  28189. };
  28190. /**
  28191. * Wrapper for addUniform.
  28192. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28193. * @param {Matrix} mat A 4x4 matrix.
  28194. */
  28195. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28196. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28197. };
  28198. /**
  28199. * Wrapper for addUniform.
  28200. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28201. * @param {number} x
  28202. * @param {number} y
  28203. */
  28204. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28205. var temp = [x, y];
  28206. this.addUniform(name, temp);
  28207. };
  28208. /**
  28209. * Wrapper for addUniform.
  28210. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28211. * @param {number} x
  28212. * @param {number} y
  28213. * @param {number} z
  28214. */
  28215. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28216. var temp = [x, y, z];
  28217. this.addUniform(name, temp);
  28218. };
  28219. /**
  28220. * Wrapper for addUniform.
  28221. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28222. * @param {Color3} color
  28223. */
  28224. UniformBuffer.prototype.addColor3 = function (name, color) {
  28225. var temp = new Array();
  28226. color.toArray(temp);
  28227. this.addUniform(name, temp);
  28228. };
  28229. /**
  28230. * Wrapper for addUniform.
  28231. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28232. * @param {Color3} color
  28233. * @param {number} alpha
  28234. */
  28235. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28236. var temp = new Array();
  28237. color.toArray(temp);
  28238. temp.push(alpha);
  28239. this.addUniform(name, temp);
  28240. };
  28241. /**
  28242. * Wrapper for addUniform.
  28243. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28244. * @param {Vector3} vector
  28245. */
  28246. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28247. var temp = new Array();
  28248. vector.toArray(temp);
  28249. this.addUniform(name, temp);
  28250. };
  28251. /**
  28252. * Wrapper for addUniform.
  28253. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28254. */
  28255. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28256. this.addUniform(name, 12);
  28257. };
  28258. /**
  28259. * Wrapper for addUniform.
  28260. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28261. */
  28262. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28263. this.addUniform(name, 8);
  28264. };
  28265. /**
  28266. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28267. */
  28268. UniformBuffer.prototype.create = function () {
  28269. if (this._noUBO) {
  28270. return;
  28271. }
  28272. if (this._buffer) {
  28273. return; // nothing to do
  28274. }
  28275. // See spec, alignment must be filled as a vec4
  28276. this._fillAlignment(4);
  28277. this._bufferData = new Float32Array(this._data);
  28278. this._rebuild();
  28279. this._needSync = true;
  28280. };
  28281. UniformBuffer.prototype._rebuild = function () {
  28282. if (this._noUBO) {
  28283. return;
  28284. }
  28285. if (this._dynamic) {
  28286. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28287. }
  28288. else {
  28289. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28290. }
  28291. };
  28292. /**
  28293. * Updates the WebGL Uniform Buffer on the GPU.
  28294. * If the `dynamic` flag is set to true, no cache comparison is done.
  28295. * Otherwise, the buffer will be updated only if the cache differs.
  28296. */
  28297. UniformBuffer.prototype.update = function () {
  28298. if (!this._buffer) {
  28299. this.create();
  28300. return;
  28301. }
  28302. if (!this._dynamic && !this._needSync) {
  28303. return;
  28304. }
  28305. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28306. this._needSync = false;
  28307. };
  28308. /**
  28309. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28310. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28311. * @param {number[]|Float32Array} data Flattened data
  28312. * @param {number} size Size of the data.
  28313. */
  28314. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28315. var location = this._uniformLocations[uniformName];
  28316. if (location === undefined) {
  28317. if (this._buffer) {
  28318. // Cannot add an uniform if the buffer is already created
  28319. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28320. return;
  28321. }
  28322. this.addUniform(uniformName, size);
  28323. location = this._uniformLocations[uniformName];
  28324. }
  28325. if (!this._buffer) {
  28326. this.create();
  28327. }
  28328. if (!this._dynamic) {
  28329. // Cache for static uniform buffers
  28330. var changed = false;
  28331. for (var i = 0; i < size; i++) {
  28332. if (this._bufferData[location + i] !== data[i]) {
  28333. changed = true;
  28334. this._bufferData[location + i] = data[i];
  28335. }
  28336. }
  28337. this._needSync = this._needSync || changed;
  28338. }
  28339. else {
  28340. // No cache for dynamic
  28341. for (var i = 0; i < size; i++) {
  28342. this._bufferData[location + i] = data[i];
  28343. }
  28344. }
  28345. };
  28346. // Update methods
  28347. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28348. // To match std140, matrix must be realigned
  28349. for (var i = 0; i < 3; i++) {
  28350. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28351. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28352. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28353. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28354. }
  28355. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28356. };
  28357. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28358. this._currentEffect.setMatrix3x3(name, matrix);
  28359. };
  28360. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28361. this._currentEffect.setMatrix2x2(name, matrix);
  28362. };
  28363. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28364. // To match std140, matrix must be realigned
  28365. for (var i = 0; i < 2; i++) {
  28366. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28367. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28368. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28369. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28370. }
  28371. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28372. };
  28373. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28374. this._currentEffect.setFloat(name, x);
  28375. };
  28376. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28377. UniformBuffer._tempBuffer[0] = x;
  28378. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28379. };
  28380. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28381. if (suffix === void 0) { suffix = ""; }
  28382. this._currentEffect.setFloat2(name + suffix, x, y);
  28383. };
  28384. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28385. if (suffix === void 0) { suffix = ""; }
  28386. UniformBuffer._tempBuffer[0] = x;
  28387. UniformBuffer._tempBuffer[1] = y;
  28388. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28389. };
  28390. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28391. if (suffix === void 0) { suffix = ""; }
  28392. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28393. };
  28394. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28395. if (suffix === void 0) { suffix = ""; }
  28396. UniformBuffer._tempBuffer[0] = x;
  28397. UniformBuffer._tempBuffer[1] = y;
  28398. UniformBuffer._tempBuffer[2] = z;
  28399. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28400. };
  28401. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28402. if (suffix === void 0) { suffix = ""; }
  28403. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28404. };
  28405. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28406. if (suffix === void 0) { suffix = ""; }
  28407. UniformBuffer._tempBuffer[0] = x;
  28408. UniformBuffer._tempBuffer[1] = y;
  28409. UniformBuffer._tempBuffer[2] = z;
  28410. UniformBuffer._tempBuffer[3] = w;
  28411. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28412. };
  28413. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28414. this._currentEffect.setMatrix(name, mat);
  28415. };
  28416. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28417. this.updateUniform(name, mat.toArray(), 16);
  28418. };
  28419. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28420. this._currentEffect.setVector3(name, vector);
  28421. };
  28422. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28423. vector.toArray(UniformBuffer._tempBuffer);
  28424. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28425. };
  28426. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28427. this._currentEffect.setVector4(name, vector);
  28428. };
  28429. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28430. vector.toArray(UniformBuffer._tempBuffer);
  28431. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28432. };
  28433. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28434. if (suffix === void 0) { suffix = ""; }
  28435. this._currentEffect.setColor3(name + suffix, color);
  28436. };
  28437. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28438. if (suffix === void 0) { suffix = ""; }
  28439. color.toArray(UniformBuffer._tempBuffer);
  28440. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28441. };
  28442. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28443. if (suffix === void 0) { suffix = ""; }
  28444. this._currentEffect.setColor4(name + suffix, color, alpha);
  28445. };
  28446. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28447. if (suffix === void 0) { suffix = ""; }
  28448. color.toArray(UniformBuffer._tempBuffer);
  28449. UniformBuffer._tempBuffer[3] = alpha;
  28450. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28451. };
  28452. /**
  28453. * Sets a sampler uniform on the effect.
  28454. * @param {string} name Name of the sampler.
  28455. * @param {Texture} texture
  28456. */
  28457. UniformBuffer.prototype.setTexture = function (name, texture) {
  28458. this._currentEffect.setTexture(name, texture);
  28459. };
  28460. /**
  28461. * Directly updates the value of the uniform in the cache AND on the GPU.
  28462. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28463. * @param {number[]|Float32Array} data Flattened data
  28464. */
  28465. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28466. this.updateUniform(uniformName, data, data.length);
  28467. this.update();
  28468. };
  28469. /**
  28470. * Binds this uniform buffer to an effect.
  28471. * @param {Effect} effect
  28472. * @param {string} name Name of the uniform block in the shader.
  28473. */
  28474. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28475. this._currentEffect = effect;
  28476. if (this._noUBO || !this._buffer) {
  28477. return;
  28478. }
  28479. effect.bindUniformBuffer(this._buffer, name);
  28480. };
  28481. /**
  28482. * Disposes the uniform buffer.
  28483. */
  28484. UniformBuffer.prototype.dispose = function () {
  28485. if (this._noUBO) {
  28486. return;
  28487. }
  28488. var index = this._engine._uniformBuffers.indexOf(this);
  28489. if (index !== -1) {
  28490. this._engine._uniformBuffers.splice(index, 1);
  28491. }
  28492. if (!this._buffer) {
  28493. return;
  28494. }
  28495. if (this._engine._releaseBuffer(this._buffer)) {
  28496. this._buffer = null;
  28497. }
  28498. };
  28499. // Pool for avoiding memory leaks
  28500. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28501. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28502. return UniformBuffer;
  28503. }());
  28504. BABYLON.UniformBuffer = UniformBuffer;
  28505. })(BABYLON || (BABYLON = {}));
  28506. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28507. var BABYLON;
  28508. (function (BABYLON) {
  28509. var PushMaterial = /** @class */ (function (_super) {
  28510. __extends(PushMaterial, _super);
  28511. function PushMaterial(name, scene) {
  28512. var _this = _super.call(this, name, scene) || this;
  28513. _this.storeEffectOnSubMeshes = true;
  28514. return _this;
  28515. }
  28516. PushMaterial.prototype.getEffect = function () {
  28517. return this._activeEffect;
  28518. };
  28519. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  28520. if (!mesh) {
  28521. return false;
  28522. }
  28523. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  28524. return true;
  28525. }
  28526. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  28527. };
  28528. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28529. this._activeEffect.setMatrix("world", world);
  28530. };
  28531. PushMaterial.prototype.bind = function (world, mesh) {
  28532. if (!mesh) {
  28533. return;
  28534. }
  28535. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  28536. };
  28537. PushMaterial.prototype._afterBind = function (mesh, effect) {
  28538. if (effect === void 0) { effect = null; }
  28539. _super.prototype._afterBind.call(this, mesh);
  28540. this.getScene()._cachedEffect = effect;
  28541. };
  28542. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  28543. if (visibility === void 0) { visibility = 1; }
  28544. return scene.isCachedMaterialInvalid(this, effect, visibility);
  28545. };
  28546. return PushMaterial;
  28547. }(BABYLON.Material));
  28548. BABYLON.PushMaterial = PushMaterial;
  28549. })(BABYLON || (BABYLON = {}));
  28550. //# sourceMappingURL=babylon.pushMaterial.js.map
  28551. var BABYLON;
  28552. (function (BABYLON) {
  28553. var VertexData = /** @class */ (function () {
  28554. function VertexData() {
  28555. }
  28556. VertexData.prototype.set = function (data, kind) {
  28557. switch (kind) {
  28558. case BABYLON.VertexBuffer.PositionKind:
  28559. this.positions = data;
  28560. break;
  28561. case BABYLON.VertexBuffer.NormalKind:
  28562. this.normals = data;
  28563. break;
  28564. case BABYLON.VertexBuffer.TangentKind:
  28565. this.tangents = data;
  28566. break;
  28567. case BABYLON.VertexBuffer.UVKind:
  28568. this.uvs = data;
  28569. break;
  28570. case BABYLON.VertexBuffer.UV2Kind:
  28571. this.uvs2 = data;
  28572. break;
  28573. case BABYLON.VertexBuffer.UV3Kind:
  28574. this.uvs3 = data;
  28575. break;
  28576. case BABYLON.VertexBuffer.UV4Kind:
  28577. this.uvs4 = data;
  28578. break;
  28579. case BABYLON.VertexBuffer.UV5Kind:
  28580. this.uvs5 = data;
  28581. break;
  28582. case BABYLON.VertexBuffer.UV6Kind:
  28583. this.uvs6 = data;
  28584. break;
  28585. case BABYLON.VertexBuffer.ColorKind:
  28586. this.colors = data;
  28587. break;
  28588. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28589. this.matricesIndices = data;
  28590. break;
  28591. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28592. this.matricesWeights = data;
  28593. break;
  28594. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28595. this.matricesIndicesExtra = data;
  28596. break;
  28597. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28598. this.matricesWeightsExtra = data;
  28599. break;
  28600. }
  28601. };
  28602. /**
  28603. * Associates the vertexData to the passed Mesh.
  28604. * Sets it as updatable or not (default `false`).
  28605. * Returns the VertexData.
  28606. */
  28607. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28608. this._applyTo(mesh, updatable);
  28609. return this;
  28610. };
  28611. /**
  28612. * Associates the vertexData to the passed Geometry.
  28613. * Sets it as updatable or not (default `false`).
  28614. * Returns the VertexData.
  28615. */
  28616. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28617. this._applyTo(geometry, updatable);
  28618. return this;
  28619. };
  28620. /**
  28621. * Updates the associated mesh.
  28622. * Returns the VertexData.
  28623. */
  28624. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28625. this._update(mesh);
  28626. return this;
  28627. };
  28628. /**
  28629. * Updates the associated geometry.
  28630. * Returns the VertexData.
  28631. */
  28632. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28633. this._update(geometry);
  28634. return this;
  28635. };
  28636. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28637. if (updatable === void 0) { updatable = false; }
  28638. if (this.positions) {
  28639. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28640. }
  28641. if (this.normals) {
  28642. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28643. }
  28644. if (this.tangents) {
  28645. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28646. }
  28647. if (this.uvs) {
  28648. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28649. }
  28650. if (this.uvs2) {
  28651. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28652. }
  28653. if (this.uvs3) {
  28654. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28655. }
  28656. if (this.uvs4) {
  28657. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28658. }
  28659. if (this.uvs5) {
  28660. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28661. }
  28662. if (this.uvs6) {
  28663. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28664. }
  28665. if (this.colors) {
  28666. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28667. }
  28668. if (this.matricesIndices) {
  28669. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28670. }
  28671. if (this.matricesWeights) {
  28672. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28673. }
  28674. if (this.matricesIndicesExtra) {
  28675. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28676. }
  28677. if (this.matricesWeightsExtra) {
  28678. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28679. }
  28680. if (this.indices) {
  28681. meshOrGeometry.setIndices(this.indices, null, updatable);
  28682. }
  28683. return this;
  28684. };
  28685. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28686. if (this.positions) {
  28687. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28688. }
  28689. if (this.normals) {
  28690. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28691. }
  28692. if (this.tangents) {
  28693. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28694. }
  28695. if (this.uvs) {
  28696. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28697. }
  28698. if (this.uvs2) {
  28699. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28700. }
  28701. if (this.uvs3) {
  28702. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28703. }
  28704. if (this.uvs4) {
  28705. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28706. }
  28707. if (this.uvs5) {
  28708. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28709. }
  28710. if (this.uvs6) {
  28711. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28712. }
  28713. if (this.colors) {
  28714. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28715. }
  28716. if (this.matricesIndices) {
  28717. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28718. }
  28719. if (this.matricesWeights) {
  28720. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28721. }
  28722. if (this.matricesIndicesExtra) {
  28723. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28724. }
  28725. if (this.matricesWeightsExtra) {
  28726. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28727. }
  28728. if (this.indices) {
  28729. meshOrGeometry.setIndices(this.indices, null);
  28730. }
  28731. return this;
  28732. };
  28733. /**
  28734. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28735. * Returns the VertexData.
  28736. */
  28737. VertexData.prototype.transform = function (matrix) {
  28738. var transformed = BABYLON.Vector3.Zero();
  28739. var index;
  28740. if (this.positions) {
  28741. var position = BABYLON.Vector3.Zero();
  28742. for (index = 0; index < this.positions.length; index += 3) {
  28743. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28744. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28745. this.positions[index] = transformed.x;
  28746. this.positions[index + 1] = transformed.y;
  28747. this.positions[index + 2] = transformed.z;
  28748. }
  28749. }
  28750. if (this.normals) {
  28751. var normal = BABYLON.Vector3.Zero();
  28752. for (index = 0; index < this.normals.length; index += 3) {
  28753. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28754. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28755. this.normals[index] = transformed.x;
  28756. this.normals[index + 1] = transformed.y;
  28757. this.normals[index + 2] = transformed.z;
  28758. }
  28759. }
  28760. if (this.tangents) {
  28761. var tangent = BABYLON.Vector4.Zero();
  28762. var tangentTransformed = BABYLON.Vector4.Zero();
  28763. for (index = 0; index < this.tangents.length; index += 4) {
  28764. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28765. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28766. this.tangents[index] = tangentTransformed.x;
  28767. this.tangents[index + 1] = tangentTransformed.y;
  28768. this.tangents[index + 2] = tangentTransformed.z;
  28769. this.tangents[index + 3] = tangentTransformed.w;
  28770. }
  28771. }
  28772. return this;
  28773. };
  28774. /**
  28775. * Merges the passed VertexData into the current one.
  28776. * Returns the modified VertexData.
  28777. */
  28778. VertexData.prototype.merge = function (other, options) {
  28779. options = options || {};
  28780. if (other.indices) {
  28781. if (!this.indices) {
  28782. this.indices = [];
  28783. }
  28784. var offset = this.positions ? this.positions.length / 3 : 0;
  28785. for (var index = 0; index < other.indices.length; index++) {
  28786. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28787. this.indices.push(other.indices[index] + offset);
  28788. }
  28789. }
  28790. this.positions = this._mergeElement(this.positions, other.positions);
  28791. if (!this.positions) {
  28792. return this;
  28793. }
  28794. var count = this.positions.length / 3;
  28795. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28796. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28797. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28798. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28799. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28800. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28801. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28802. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28803. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28804. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28805. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28806. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28807. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28808. return this;
  28809. };
  28810. VertexData.prototype._mergeElement = function (source, other, length) {
  28811. if (length === void 0) { length = 0; }
  28812. if (!other && !source) {
  28813. return null;
  28814. }
  28815. if (!other) {
  28816. return this._mergeElement(source, new Float32Array(source.length), length);
  28817. }
  28818. if (!source) {
  28819. if (length === 0 || length === other.length) {
  28820. return other;
  28821. }
  28822. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28823. }
  28824. var len = other.length + source.length;
  28825. var isSrcTypedArray = source instanceof Float32Array;
  28826. var isOthTypedArray = other instanceof Float32Array;
  28827. // use non-loop method when the source is Float32Array
  28828. if (isSrcTypedArray) {
  28829. var ret32 = new Float32Array(len);
  28830. ret32.set(source);
  28831. ret32.set(other, source.length);
  28832. return ret32;
  28833. // source is number[], when other is also use concat
  28834. }
  28835. else if (!isOthTypedArray) {
  28836. return source.concat(other);
  28837. // source is a number[], but other is a Float32Array, loop required
  28838. }
  28839. else {
  28840. var ret = source.slice(0); // copy source to a separate array
  28841. for (var i = 0, len = other.length; i < len; i++) {
  28842. ret.push(other[i]);
  28843. }
  28844. return ret;
  28845. }
  28846. };
  28847. /**
  28848. * Serializes the VertexData.
  28849. * Returns a serialized object.
  28850. */
  28851. VertexData.prototype.serialize = function () {
  28852. var serializationObject = this.serialize();
  28853. if (this.positions) {
  28854. serializationObject.positions = this.positions;
  28855. }
  28856. if (this.normals) {
  28857. serializationObject.normals = this.normals;
  28858. }
  28859. if (this.tangents) {
  28860. serializationObject.tangents = this.tangents;
  28861. }
  28862. if (this.uvs) {
  28863. serializationObject.uvs = this.uvs;
  28864. }
  28865. if (this.uvs2) {
  28866. serializationObject.uvs2 = this.uvs2;
  28867. }
  28868. if (this.uvs3) {
  28869. serializationObject.uvs3 = this.uvs3;
  28870. }
  28871. if (this.uvs4) {
  28872. serializationObject.uvs4 = this.uvs4;
  28873. }
  28874. if (this.uvs5) {
  28875. serializationObject.uvs5 = this.uvs5;
  28876. }
  28877. if (this.uvs6) {
  28878. serializationObject.uvs6 = this.uvs6;
  28879. }
  28880. if (this.colors) {
  28881. serializationObject.colors = this.colors;
  28882. }
  28883. if (this.matricesIndices) {
  28884. serializationObject.matricesIndices = this.matricesIndices;
  28885. serializationObject.matricesIndices._isExpanded = true;
  28886. }
  28887. if (this.matricesWeights) {
  28888. serializationObject.matricesWeights = this.matricesWeights;
  28889. }
  28890. if (this.matricesIndicesExtra) {
  28891. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28892. serializationObject.matricesIndicesExtra._isExpanded = true;
  28893. }
  28894. if (this.matricesWeightsExtra) {
  28895. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28896. }
  28897. serializationObject.indices = this.indices;
  28898. return serializationObject;
  28899. };
  28900. // Statics
  28901. /**
  28902. * Returns the object VertexData associated to the passed mesh.
  28903. */
  28904. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28905. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28906. };
  28907. /**
  28908. * Returns the object VertexData associated to the passed geometry.
  28909. */
  28910. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28911. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28912. };
  28913. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28914. var result = new VertexData();
  28915. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28916. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28917. }
  28918. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28919. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28920. }
  28921. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28922. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28923. }
  28924. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28925. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28926. }
  28927. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28928. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28929. }
  28930. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28931. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28932. }
  28933. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28934. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28935. }
  28936. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28937. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28938. }
  28939. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28940. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28941. }
  28942. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28943. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28944. }
  28945. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28946. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28947. }
  28948. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28949. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28950. }
  28951. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28952. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28953. }
  28954. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28955. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28956. }
  28957. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28958. return result;
  28959. };
  28960. /**
  28961. * Creates the vertexData of the Ribbon.
  28962. */
  28963. VertexData.CreateRibbon = function (options) {
  28964. var pathArray = options.pathArray;
  28965. var closeArray = options.closeArray || false;
  28966. var closePath = options.closePath || false;
  28967. var invertUV = options.invertUV || false;
  28968. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28969. var offset = options.offset || defaultOffset;
  28970. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28971. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28972. var customUV = options.uvs;
  28973. var customColors = options.colors;
  28974. var positions = [];
  28975. var indices = [];
  28976. var normals = [];
  28977. var uvs = [];
  28978. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28979. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28980. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28981. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28982. var minlg; // minimal length among all paths from pathArray
  28983. var lg = []; // array of path lengths : nb of vertex per path
  28984. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28985. var p; // path iterator
  28986. var i; // point iterator
  28987. var j; // point iterator
  28988. // if single path in pathArray
  28989. if (pathArray.length < 2) {
  28990. var ar1 = [];
  28991. var ar2 = [];
  28992. for (i = 0; i < pathArray[0].length - offset; i++) {
  28993. ar1.push(pathArray[0][i]);
  28994. ar2.push(pathArray[0][i + offset]);
  28995. }
  28996. pathArray = [ar1, ar2];
  28997. }
  28998. // positions and horizontal distances (u)
  28999. var idc = 0;
  29000. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29001. var path;
  29002. var l;
  29003. minlg = pathArray[0].length;
  29004. var vectlg;
  29005. var dist;
  29006. for (p = 0; p < pathArray.length; p++) {
  29007. uTotalDistance[p] = 0;
  29008. us[p] = [0];
  29009. path = pathArray[p];
  29010. l = path.length;
  29011. minlg = (minlg < l) ? minlg : l;
  29012. j = 0;
  29013. while (j < l) {
  29014. positions.push(path[j].x, path[j].y, path[j].z);
  29015. if (j > 0) {
  29016. vectlg = path[j].subtract(path[j - 1]).length();
  29017. dist = vectlg + uTotalDistance[p];
  29018. us[p].push(dist);
  29019. uTotalDistance[p] = dist;
  29020. }
  29021. j++;
  29022. }
  29023. if (closePath) {
  29024. j--;
  29025. positions.push(path[0].x, path[0].y, path[0].z);
  29026. vectlg = path[j].subtract(path[0]).length();
  29027. dist = vectlg + uTotalDistance[p];
  29028. us[p].push(dist);
  29029. uTotalDistance[p] = dist;
  29030. }
  29031. lg[p] = l + closePathCorr;
  29032. idx[p] = idc;
  29033. idc += (l + closePathCorr);
  29034. }
  29035. // vertical distances (v)
  29036. var path1;
  29037. var path2;
  29038. var vertex1 = null;
  29039. var vertex2 = null;
  29040. for (i = 0; i < minlg + closePathCorr; i++) {
  29041. vTotalDistance[i] = 0;
  29042. vs[i] = [0];
  29043. for (p = 0; p < pathArray.length - 1; p++) {
  29044. path1 = pathArray[p];
  29045. path2 = pathArray[p + 1];
  29046. if (i === minlg) {
  29047. vertex1 = path1[0];
  29048. vertex2 = path2[0];
  29049. }
  29050. else {
  29051. vertex1 = path1[i];
  29052. vertex2 = path2[i];
  29053. }
  29054. vectlg = vertex2.subtract(vertex1).length();
  29055. dist = vectlg + vTotalDistance[i];
  29056. vs[i].push(dist);
  29057. vTotalDistance[i] = dist;
  29058. }
  29059. if (closeArray && vertex2 && vertex1) {
  29060. path1 = pathArray[p];
  29061. path2 = pathArray[0];
  29062. if (i === minlg) {
  29063. vertex2 = path2[0];
  29064. }
  29065. vectlg = vertex2.subtract(vertex1).length();
  29066. dist = vectlg + vTotalDistance[i];
  29067. vTotalDistance[i] = dist;
  29068. }
  29069. }
  29070. // uvs
  29071. var u;
  29072. var v;
  29073. if (customUV) {
  29074. for (p = 0; p < customUV.length; p++) {
  29075. uvs.push(customUV[p].x, customUV[p].y);
  29076. }
  29077. }
  29078. else {
  29079. for (p = 0; p < pathArray.length; p++) {
  29080. for (i = 0; i < minlg + closePathCorr; i++) {
  29081. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29082. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29083. if (invertUV) {
  29084. uvs.push(v, u);
  29085. }
  29086. else {
  29087. uvs.push(u, v);
  29088. }
  29089. }
  29090. }
  29091. }
  29092. // indices
  29093. p = 0; // path index
  29094. var pi = 0; // positions array index
  29095. var l1 = lg[p] - 1; // path1 length
  29096. var l2 = lg[p + 1] - 1; // path2 length
  29097. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29098. var shft = idx[1] - idx[0]; // shift
  29099. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29100. while (pi <= min && p < path1nb) {
  29101. // 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
  29102. indices.push(pi, pi + shft, pi + 1);
  29103. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29104. pi += 1;
  29105. if (pi === min) {
  29106. p++;
  29107. if (p === lg.length - 1) {
  29108. shft = idx[0] - idx[p];
  29109. l1 = lg[p] - 1;
  29110. l2 = lg[0] - 1;
  29111. }
  29112. else {
  29113. shft = idx[p + 1] - idx[p];
  29114. l1 = lg[p] - 1;
  29115. l2 = lg[p + 1] - 1;
  29116. }
  29117. pi = idx[p];
  29118. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29119. }
  29120. }
  29121. // normals
  29122. VertexData.ComputeNormals(positions, indices, normals);
  29123. if (closePath) {
  29124. var indexFirst = 0;
  29125. var indexLast = 0;
  29126. for (p = 0; p < pathArray.length; p++) {
  29127. indexFirst = idx[p] * 3;
  29128. if (p + 1 < pathArray.length) {
  29129. indexLast = (idx[p + 1] - 1) * 3;
  29130. }
  29131. else {
  29132. indexLast = normals.length - 3;
  29133. }
  29134. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29135. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29136. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29137. normals[indexLast] = normals[indexFirst];
  29138. normals[indexLast + 1] = normals[indexFirst + 1];
  29139. normals[indexLast + 2] = normals[indexFirst + 2];
  29140. }
  29141. }
  29142. // sides
  29143. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29144. // Colors
  29145. var colors = null;
  29146. if (customColors) {
  29147. colors = new Float32Array(customColors.length * 4);
  29148. for (var c = 0; c < customColors.length; c++) {
  29149. colors[c * 4] = customColors[c].r;
  29150. colors[c * 4 + 1] = customColors[c].g;
  29151. colors[c * 4 + 2] = customColors[c].b;
  29152. colors[c * 4 + 3] = customColors[c].a;
  29153. }
  29154. }
  29155. // Result
  29156. var vertexData = new VertexData();
  29157. var positions32 = new Float32Array(positions);
  29158. var normals32 = new Float32Array(normals);
  29159. var uvs32 = new Float32Array(uvs);
  29160. vertexData.indices = indices;
  29161. vertexData.positions = positions32;
  29162. vertexData.normals = normals32;
  29163. vertexData.uvs = uvs32;
  29164. if (colors) {
  29165. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29166. }
  29167. if (closePath) {
  29168. vertexData._idx = idx;
  29169. }
  29170. return vertexData;
  29171. };
  29172. /**
  29173. * Creates the VertexData of the Box.
  29174. */
  29175. VertexData.CreateBox = function (options) {
  29176. var normalsSource = [
  29177. new BABYLON.Vector3(0, 0, 1),
  29178. new BABYLON.Vector3(0, 0, -1),
  29179. new BABYLON.Vector3(1, 0, 0),
  29180. new BABYLON.Vector3(-1, 0, 0),
  29181. new BABYLON.Vector3(0, 1, 0),
  29182. new BABYLON.Vector3(0, -1, 0)
  29183. ];
  29184. var indices = [];
  29185. var positions = [];
  29186. var normals = [];
  29187. var uvs = [];
  29188. var width = options.width || options.size || 1;
  29189. var height = options.height || options.size || 1;
  29190. var depth = options.depth || options.size || 1;
  29191. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29192. var faceUV = options.faceUV || new Array(6);
  29193. var faceColors = options.faceColors;
  29194. var colors = [];
  29195. // default face colors and UV if undefined
  29196. for (var f = 0; f < 6; f++) {
  29197. if (faceUV[f] === undefined) {
  29198. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29199. }
  29200. if (faceColors && faceColors[f] === undefined) {
  29201. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29202. }
  29203. }
  29204. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29205. // Create each face in turn.
  29206. for (var index = 0; index < normalsSource.length; index++) {
  29207. var normal = normalsSource[index];
  29208. // Get two vectors perpendicular to the face normal and to each other.
  29209. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29210. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29211. // Six indices (two triangles) per face.
  29212. var verticesLength = positions.length / 3;
  29213. indices.push(verticesLength);
  29214. indices.push(verticesLength + 1);
  29215. indices.push(verticesLength + 2);
  29216. indices.push(verticesLength);
  29217. indices.push(verticesLength + 2);
  29218. indices.push(verticesLength + 3);
  29219. // Four vertices per face.
  29220. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29221. positions.push(vertex.x, vertex.y, vertex.z);
  29222. normals.push(normal.x, normal.y, normal.z);
  29223. uvs.push(faceUV[index].z, faceUV[index].w);
  29224. if (faceColors) {
  29225. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29226. }
  29227. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29228. positions.push(vertex.x, vertex.y, vertex.z);
  29229. normals.push(normal.x, normal.y, normal.z);
  29230. uvs.push(faceUV[index].x, faceUV[index].w);
  29231. if (faceColors) {
  29232. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29233. }
  29234. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29235. positions.push(vertex.x, vertex.y, vertex.z);
  29236. normals.push(normal.x, normal.y, normal.z);
  29237. uvs.push(faceUV[index].x, faceUV[index].y);
  29238. if (faceColors) {
  29239. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29240. }
  29241. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29242. positions.push(vertex.x, vertex.y, vertex.z);
  29243. normals.push(normal.x, normal.y, normal.z);
  29244. uvs.push(faceUV[index].z, faceUV[index].y);
  29245. if (faceColors) {
  29246. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29247. }
  29248. }
  29249. // sides
  29250. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29251. // Result
  29252. var vertexData = new VertexData();
  29253. vertexData.indices = indices;
  29254. vertexData.positions = positions;
  29255. vertexData.normals = normals;
  29256. vertexData.uvs = uvs;
  29257. if (faceColors) {
  29258. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29259. vertexData.colors = totalColors;
  29260. }
  29261. return vertexData;
  29262. };
  29263. /**
  29264. * Creates the VertexData of the Sphere.
  29265. */
  29266. VertexData.CreateSphere = function (options) {
  29267. var segments = options.segments || 32;
  29268. var diameterX = options.diameterX || options.diameter || 1;
  29269. var diameterY = options.diameterY || options.diameter || 1;
  29270. var diameterZ = options.diameterZ || options.diameter || 1;
  29271. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29272. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29273. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29274. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29275. var totalZRotationSteps = 2 + segments;
  29276. var totalYRotationSteps = 2 * totalZRotationSteps;
  29277. var indices = [];
  29278. var positions = [];
  29279. var normals = [];
  29280. var uvs = [];
  29281. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29282. var normalizedZ = zRotationStep / totalZRotationSteps;
  29283. var angleZ = normalizedZ * Math.PI * slice;
  29284. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29285. var normalizedY = yRotationStep / totalYRotationSteps;
  29286. var angleY = normalizedY * Math.PI * 2 * arc;
  29287. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29288. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29289. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29290. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29291. var vertex = complete.multiply(radius);
  29292. var normal = complete.divide(radius).normalize();
  29293. positions.push(vertex.x, vertex.y, vertex.z);
  29294. normals.push(normal.x, normal.y, normal.z);
  29295. uvs.push(normalizedY, normalizedZ);
  29296. }
  29297. if (zRotationStep > 0) {
  29298. var verticesCount = positions.length / 3;
  29299. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29300. indices.push((firstIndex));
  29301. indices.push((firstIndex + 1));
  29302. indices.push(firstIndex + totalYRotationSteps + 1);
  29303. indices.push((firstIndex + totalYRotationSteps + 1));
  29304. indices.push((firstIndex + 1));
  29305. indices.push((firstIndex + totalYRotationSteps + 2));
  29306. }
  29307. }
  29308. }
  29309. // Sides
  29310. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29311. // Result
  29312. var vertexData = new VertexData();
  29313. vertexData.indices = indices;
  29314. vertexData.positions = positions;
  29315. vertexData.normals = normals;
  29316. vertexData.uvs = uvs;
  29317. return vertexData;
  29318. };
  29319. /**
  29320. * Creates the VertexData of the Cylinder or Cone.
  29321. */
  29322. VertexData.CreateCylinder = function (options) {
  29323. var height = options.height || 2;
  29324. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29325. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29326. var tessellation = options.tessellation || 24;
  29327. var subdivisions = options.subdivisions || 1;
  29328. var hasRings = options.hasRings ? true : false;
  29329. var enclose = options.enclose ? true : false;
  29330. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29331. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29332. var faceUV = options.faceUV || new Array(3);
  29333. var faceColors = options.faceColors;
  29334. // default face colors and UV if undefined
  29335. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29336. var ringNb = (hasRings) ? subdivisions : 1;
  29337. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29338. var f;
  29339. for (f = 0; f < surfaceNb; f++) {
  29340. if (faceColors && faceColors[f] === undefined) {
  29341. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29342. }
  29343. }
  29344. for (f = 0; f < surfaceNb; f++) {
  29345. if (faceUV && faceUV[f] === undefined) {
  29346. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29347. }
  29348. }
  29349. var indices = new Array();
  29350. var positions = new Array();
  29351. var normals = new Array();
  29352. var uvs = new Array();
  29353. var colors = new Array();
  29354. var angle_step = Math.PI * 2 * arc / tessellation;
  29355. var angle;
  29356. var h;
  29357. var radius;
  29358. var tan = (diameterBottom - diameterTop) / 2 / height;
  29359. var ringVertex = BABYLON.Vector3.Zero();
  29360. var ringNormal = BABYLON.Vector3.Zero();
  29361. var ringFirstVertex = BABYLON.Vector3.Zero();
  29362. var ringFirstNormal = BABYLON.Vector3.Zero();
  29363. var quadNormal = BABYLON.Vector3.Zero();
  29364. var Y = BABYLON.Axis.Y;
  29365. // positions, normals, uvs
  29366. var i;
  29367. var j;
  29368. var r;
  29369. var ringIdx = 1;
  29370. var s = 1; // surface index
  29371. var cs = 0;
  29372. var v = 0;
  29373. for (i = 0; i <= subdivisions; i++) {
  29374. h = i / subdivisions;
  29375. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29376. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29377. for (r = 0; r < ringIdx; r++) {
  29378. if (hasRings) {
  29379. s += r;
  29380. }
  29381. if (enclose) {
  29382. s += 2 * r;
  29383. }
  29384. for (j = 0; j <= tessellation; j++) {
  29385. angle = j * angle_step;
  29386. // position
  29387. ringVertex.x = Math.cos(-angle) * radius;
  29388. ringVertex.y = -height / 2 + h * height;
  29389. ringVertex.z = Math.sin(-angle) * radius;
  29390. // normal
  29391. if (diameterTop === 0 && i === subdivisions) {
  29392. // if no top cap, reuse former normals
  29393. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29394. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29395. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29396. }
  29397. else {
  29398. ringNormal.x = ringVertex.x;
  29399. ringNormal.z = ringVertex.z;
  29400. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29401. ringNormal.normalize();
  29402. }
  29403. // keep first ring vertex values for enclose
  29404. if (j === 0) {
  29405. ringFirstVertex.copyFrom(ringVertex);
  29406. ringFirstNormal.copyFrom(ringNormal);
  29407. }
  29408. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29409. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29410. if (hasRings) {
  29411. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29412. }
  29413. else {
  29414. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29415. }
  29416. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29417. if (faceColors) {
  29418. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29419. }
  29420. }
  29421. // if enclose, add four vertices and their dedicated normals
  29422. if (arc !== 1 && enclose) {
  29423. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29424. positions.push(0, ringVertex.y, 0);
  29425. positions.push(0, ringVertex.y, 0);
  29426. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29427. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29428. quadNormal.normalize();
  29429. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29430. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29431. quadNormal.normalize();
  29432. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29433. if (hasRings) {
  29434. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29435. }
  29436. else {
  29437. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29438. }
  29439. uvs.push(faceUV[s + 1].x, v);
  29440. uvs.push(faceUV[s + 1].z, v);
  29441. if (hasRings) {
  29442. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29443. }
  29444. else {
  29445. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29446. }
  29447. uvs.push(faceUV[s + 2].x, v);
  29448. uvs.push(faceUV[s + 2].z, v);
  29449. if (faceColors) {
  29450. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29451. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29452. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29453. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29454. }
  29455. }
  29456. if (cs !== s) {
  29457. cs = s;
  29458. }
  29459. }
  29460. }
  29461. // indices
  29462. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29463. var s;
  29464. i = 0;
  29465. for (s = 0; s < subdivisions; s++) {
  29466. var i0 = 0;
  29467. var i1 = 0;
  29468. var i2 = 0;
  29469. var i3 = 0;
  29470. for (j = 0; j < tessellation; j++) {
  29471. i0 = i * (e + 1) + j;
  29472. i1 = (i + 1) * (e + 1) + j;
  29473. i2 = i * (e + 1) + (j + 1);
  29474. i3 = (i + 1) * (e + 1) + (j + 1);
  29475. indices.push(i0, i1, i2);
  29476. indices.push(i3, i2, i1);
  29477. }
  29478. if (arc !== 1 && enclose) {
  29479. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29480. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29481. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29482. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29483. }
  29484. i = (hasRings) ? (i + 2) : (i + 1);
  29485. }
  29486. // Caps
  29487. var createCylinderCap = function (isTop) {
  29488. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29489. if (radius === 0) {
  29490. return;
  29491. }
  29492. // Cap positions, normals & uvs
  29493. var angle;
  29494. var circleVector;
  29495. var i;
  29496. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29497. var c = null;
  29498. if (faceColors) {
  29499. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29500. }
  29501. // cap center
  29502. var vbase = positions.length / 3;
  29503. var offset = isTop ? height / 2 : -height / 2;
  29504. var center = new BABYLON.Vector3(0, offset, 0);
  29505. positions.push(center.x, center.y, center.z);
  29506. normals.push(0, isTop ? 1 : -1, 0);
  29507. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29508. if (c) {
  29509. colors.push(c.r, c.g, c.b, c.a);
  29510. }
  29511. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29512. for (i = 0; i <= tessellation; i++) {
  29513. angle = Math.PI * 2 * i * arc / tessellation;
  29514. var cos = Math.cos(-angle);
  29515. var sin = Math.sin(-angle);
  29516. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29517. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29518. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29519. normals.push(0, isTop ? 1 : -1, 0);
  29520. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29521. if (c) {
  29522. colors.push(c.r, c.g, c.b, c.a);
  29523. }
  29524. }
  29525. // Cap indices
  29526. for (i = 0; i < tessellation; i++) {
  29527. if (!isTop) {
  29528. indices.push(vbase);
  29529. indices.push(vbase + (i + 1));
  29530. indices.push(vbase + (i + 2));
  29531. }
  29532. else {
  29533. indices.push(vbase);
  29534. indices.push(vbase + (i + 2));
  29535. indices.push(vbase + (i + 1));
  29536. }
  29537. }
  29538. };
  29539. // add caps to geometry
  29540. createCylinderCap(false);
  29541. createCylinderCap(true);
  29542. // Sides
  29543. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29544. var vertexData = new VertexData();
  29545. vertexData.indices = indices;
  29546. vertexData.positions = positions;
  29547. vertexData.normals = normals;
  29548. vertexData.uvs = uvs;
  29549. if (faceColors) {
  29550. vertexData.colors = colors;
  29551. }
  29552. return vertexData;
  29553. };
  29554. /**
  29555. * Creates the VertexData of the Torus.
  29556. */
  29557. VertexData.CreateTorus = function (options) {
  29558. var indices = [];
  29559. var positions = [];
  29560. var normals = [];
  29561. var uvs = [];
  29562. var diameter = options.diameter || 1;
  29563. var thickness = options.thickness || 0.5;
  29564. var tessellation = options.tessellation || 16;
  29565. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29566. var stride = tessellation + 1;
  29567. for (var i = 0; i <= tessellation; i++) {
  29568. var u = i / tessellation;
  29569. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29570. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29571. for (var j = 0; j <= tessellation; j++) {
  29572. var v = 1 - j / tessellation;
  29573. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29574. var dx = Math.cos(innerAngle);
  29575. var dy = Math.sin(innerAngle);
  29576. // Create a vertex.
  29577. var normal = new BABYLON.Vector3(dx, dy, 0);
  29578. var position = normal.scale(thickness / 2);
  29579. var textureCoordinate = new BABYLON.Vector2(u, v);
  29580. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29581. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29582. positions.push(position.x, position.y, position.z);
  29583. normals.push(normal.x, normal.y, normal.z);
  29584. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29585. // And create indices for two triangles.
  29586. var nextI = (i + 1) % stride;
  29587. var nextJ = (j + 1) % stride;
  29588. indices.push(i * stride + j);
  29589. indices.push(i * stride + nextJ);
  29590. indices.push(nextI * stride + j);
  29591. indices.push(i * stride + nextJ);
  29592. indices.push(nextI * stride + nextJ);
  29593. indices.push(nextI * stride + j);
  29594. }
  29595. }
  29596. // Sides
  29597. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29598. // Result
  29599. var vertexData = new VertexData();
  29600. vertexData.indices = indices;
  29601. vertexData.positions = positions;
  29602. vertexData.normals = normals;
  29603. vertexData.uvs = uvs;
  29604. return vertexData;
  29605. };
  29606. /**
  29607. * Creates the VertexData of the LineSystem.
  29608. */
  29609. VertexData.CreateLineSystem = function (options) {
  29610. var indices = [];
  29611. var positions = [];
  29612. var lines = options.lines;
  29613. var idx = 0;
  29614. for (var l = 0; l < lines.length; l++) {
  29615. var points = lines[l];
  29616. for (var index = 0; index < points.length; index++) {
  29617. positions.push(points[index].x, points[index].y, points[index].z);
  29618. if (index > 0) {
  29619. indices.push(idx - 1);
  29620. indices.push(idx);
  29621. }
  29622. idx++;
  29623. }
  29624. }
  29625. var vertexData = new VertexData();
  29626. vertexData.indices = indices;
  29627. vertexData.positions = positions;
  29628. return vertexData;
  29629. };
  29630. /**
  29631. * Create the VertexData of the DashedLines.
  29632. */
  29633. VertexData.CreateDashedLines = function (options) {
  29634. var dashSize = options.dashSize || 3;
  29635. var gapSize = options.gapSize || 1;
  29636. var dashNb = options.dashNb || 200;
  29637. var points = options.points;
  29638. var positions = new Array();
  29639. var indices = new Array();
  29640. var curvect = BABYLON.Vector3.Zero();
  29641. var lg = 0;
  29642. var nb = 0;
  29643. var shft = 0;
  29644. var dashshft = 0;
  29645. var curshft = 0;
  29646. var idx = 0;
  29647. var i = 0;
  29648. for (i = 0; i < points.length - 1; i++) {
  29649. points[i + 1].subtractToRef(points[i], curvect);
  29650. lg += curvect.length();
  29651. }
  29652. shft = lg / dashNb;
  29653. dashshft = dashSize * shft / (dashSize + gapSize);
  29654. for (i = 0; i < points.length - 1; i++) {
  29655. points[i + 1].subtractToRef(points[i], curvect);
  29656. nb = Math.floor(curvect.length() / shft);
  29657. curvect.normalize();
  29658. for (var j = 0; j < nb; j++) {
  29659. curshft = shft * j;
  29660. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29661. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29662. indices.push(idx, idx + 1);
  29663. idx += 2;
  29664. }
  29665. }
  29666. // Result
  29667. var vertexData = new VertexData();
  29668. vertexData.positions = positions;
  29669. vertexData.indices = indices;
  29670. return vertexData;
  29671. };
  29672. /**
  29673. * Creates the VertexData of the Ground.
  29674. */
  29675. VertexData.CreateGround = function (options) {
  29676. var indices = [];
  29677. var positions = [];
  29678. var normals = [];
  29679. var uvs = [];
  29680. var row, col;
  29681. var width = options.width || 1;
  29682. var height = options.height || 1;
  29683. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29684. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29685. for (row = 0; row <= subdivisionsY; row++) {
  29686. for (col = 0; col <= subdivisionsX; col++) {
  29687. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29688. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29689. positions.push(position.x, position.y, position.z);
  29690. normals.push(normal.x, normal.y, normal.z);
  29691. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29692. }
  29693. }
  29694. for (row = 0; row < subdivisionsY; row++) {
  29695. for (col = 0; col < subdivisionsX; col++) {
  29696. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29697. indices.push(col + 1 + row * (subdivisionsX + 1));
  29698. indices.push(col + row * (subdivisionsX + 1));
  29699. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29700. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29701. indices.push(col + row * (subdivisionsX + 1));
  29702. }
  29703. }
  29704. // Result
  29705. var vertexData = new VertexData();
  29706. vertexData.indices = indices;
  29707. vertexData.positions = positions;
  29708. vertexData.normals = normals;
  29709. vertexData.uvs = uvs;
  29710. return vertexData;
  29711. };
  29712. /**
  29713. * Creates the VertexData of the TiledGround.
  29714. */
  29715. VertexData.CreateTiledGround = function (options) {
  29716. var xmin = options.xmin || -1.0;
  29717. var zmin = options.zmin || -1.0;
  29718. var xmax = options.xmax || 1.0;
  29719. var zmax = options.zmax || 1.0;
  29720. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29721. var precision = options.precision || { w: 1, h: 1 };
  29722. var indices = new Array();
  29723. var positions = new Array();
  29724. var normals = new Array();
  29725. var uvs = new Array();
  29726. var row, col, tileRow, tileCol;
  29727. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29728. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29729. precision.w = (precision.w < 1) ? 1 : precision.w;
  29730. precision.h = (precision.h < 1) ? 1 : precision.h;
  29731. var tileSize = {
  29732. 'w': (xmax - xmin) / subdivisions.w,
  29733. 'h': (zmax - zmin) / subdivisions.h
  29734. };
  29735. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29736. // Indices
  29737. var base = positions.length / 3;
  29738. var rowLength = precision.w + 1;
  29739. for (row = 0; row < precision.h; row++) {
  29740. for (col = 0; col < precision.w; col++) {
  29741. var square = [
  29742. base + col + row * rowLength,
  29743. base + (col + 1) + row * rowLength,
  29744. base + (col + 1) + (row + 1) * rowLength,
  29745. base + col + (row + 1) * rowLength
  29746. ];
  29747. indices.push(square[1]);
  29748. indices.push(square[2]);
  29749. indices.push(square[3]);
  29750. indices.push(square[0]);
  29751. indices.push(square[1]);
  29752. indices.push(square[3]);
  29753. }
  29754. }
  29755. // Position, normals and uvs
  29756. var position = BABYLON.Vector3.Zero();
  29757. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29758. for (row = 0; row <= precision.h; row++) {
  29759. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29760. for (col = 0; col <= precision.w; col++) {
  29761. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29762. position.y = 0;
  29763. positions.push(position.x, position.y, position.z);
  29764. normals.push(normal.x, normal.y, normal.z);
  29765. uvs.push(col / precision.w, row / precision.h);
  29766. }
  29767. }
  29768. }
  29769. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29770. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29771. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29772. }
  29773. }
  29774. // Result
  29775. var vertexData = new VertexData();
  29776. vertexData.indices = indices;
  29777. vertexData.positions = positions;
  29778. vertexData.normals = normals;
  29779. vertexData.uvs = uvs;
  29780. return vertexData;
  29781. };
  29782. /**
  29783. * Creates the VertexData of the Ground designed from a heightmap.
  29784. */
  29785. VertexData.CreateGroundFromHeightMap = function (options) {
  29786. var indices = [];
  29787. var positions = [];
  29788. var normals = [];
  29789. var uvs = [];
  29790. var row, col;
  29791. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29792. // Vertices
  29793. for (row = 0; row <= options.subdivisions; row++) {
  29794. for (col = 0; col <= options.subdivisions; col++) {
  29795. 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));
  29796. // Compute height
  29797. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29798. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29799. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29800. var r = options.buffer[pos] / 255.0;
  29801. var g = options.buffer[pos + 1] / 255.0;
  29802. var b = options.buffer[pos + 2] / 255.0;
  29803. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29804. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29805. // Add vertex
  29806. positions.push(position.x, position.y, position.z);
  29807. normals.push(0, 0, 0);
  29808. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29809. }
  29810. }
  29811. // Indices
  29812. for (row = 0; row < options.subdivisions; row++) {
  29813. for (col = 0; col < options.subdivisions; col++) {
  29814. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29815. indices.push(col + 1 + row * (options.subdivisions + 1));
  29816. indices.push(col + row * (options.subdivisions + 1));
  29817. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29818. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29819. indices.push(col + row * (options.subdivisions + 1));
  29820. }
  29821. }
  29822. // Normals
  29823. VertexData.ComputeNormals(positions, indices, normals);
  29824. // Result
  29825. var vertexData = new VertexData();
  29826. vertexData.indices = indices;
  29827. vertexData.positions = positions;
  29828. vertexData.normals = normals;
  29829. vertexData.uvs = uvs;
  29830. return vertexData;
  29831. };
  29832. /**
  29833. * Creates the VertexData of the Plane.
  29834. */
  29835. VertexData.CreatePlane = function (options) {
  29836. var indices = [];
  29837. var positions = [];
  29838. var normals = [];
  29839. var uvs = [];
  29840. var width = options.width || options.size || 1;
  29841. var height = options.height || options.size || 1;
  29842. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29843. // Vertices
  29844. var halfWidth = width / 2.0;
  29845. var halfHeight = height / 2.0;
  29846. positions.push(-halfWidth, -halfHeight, 0);
  29847. normals.push(0, 0, -1.0);
  29848. uvs.push(0.0, 0.0);
  29849. positions.push(halfWidth, -halfHeight, 0);
  29850. normals.push(0, 0, -1.0);
  29851. uvs.push(1.0, 0.0);
  29852. positions.push(halfWidth, halfHeight, 0);
  29853. normals.push(0, 0, -1.0);
  29854. uvs.push(1.0, 1.0);
  29855. positions.push(-halfWidth, halfHeight, 0);
  29856. normals.push(0, 0, -1.0);
  29857. uvs.push(0.0, 1.0);
  29858. // Indices
  29859. indices.push(0);
  29860. indices.push(1);
  29861. indices.push(2);
  29862. indices.push(0);
  29863. indices.push(2);
  29864. indices.push(3);
  29865. // Sides
  29866. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29867. // Result
  29868. var vertexData = new VertexData();
  29869. vertexData.indices = indices;
  29870. vertexData.positions = positions;
  29871. vertexData.normals = normals;
  29872. vertexData.uvs = uvs;
  29873. return vertexData;
  29874. };
  29875. /**
  29876. * Creates the VertexData of the Disc or regular Polygon.
  29877. */
  29878. VertexData.CreateDisc = function (options) {
  29879. var positions = new Array();
  29880. var indices = new Array();
  29881. var normals = new Array();
  29882. var uvs = new Array();
  29883. var radius = options.radius || 0.5;
  29884. var tessellation = options.tessellation || 64;
  29885. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29886. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29887. // positions and uvs
  29888. positions.push(0, 0, 0); // disc center first
  29889. uvs.push(0.5, 0.5);
  29890. var theta = Math.PI * 2 * arc;
  29891. var step = theta / tessellation;
  29892. for (var a = 0; a < theta; a += step) {
  29893. var x = Math.cos(a);
  29894. var y = Math.sin(a);
  29895. var u = (x + 1) / 2;
  29896. var v = (1 - y) / 2;
  29897. positions.push(radius * x, radius * y, 0);
  29898. uvs.push(u, v);
  29899. }
  29900. if (arc === 1) {
  29901. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29902. uvs.push(uvs[2], uvs[3]);
  29903. }
  29904. //indices
  29905. var vertexNb = positions.length / 3;
  29906. for (var i = 1; i < vertexNb - 1; i++) {
  29907. indices.push(i + 1, 0, i);
  29908. }
  29909. // result
  29910. VertexData.ComputeNormals(positions, indices, normals);
  29911. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29912. var vertexData = new VertexData();
  29913. vertexData.indices = indices;
  29914. vertexData.positions = positions;
  29915. vertexData.normals = normals;
  29916. vertexData.uvs = uvs;
  29917. return vertexData;
  29918. };
  29919. /**
  29920. * Re-creates the VertexData of the Polygon for sideOrientation.
  29921. */
  29922. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29923. var faceUV = fUV || new Array(3);
  29924. var faceColors = fColors;
  29925. var colors = [];
  29926. // default face colors and UV if undefined
  29927. for (var f = 0; f < 3; f++) {
  29928. if (faceUV[f] === undefined) {
  29929. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29930. }
  29931. if (faceColors && faceColors[f] === undefined) {
  29932. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29933. }
  29934. }
  29935. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29936. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29937. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29938. var indices = polygon.getIndices();
  29939. // set face colours and textures
  29940. var idx = 0;
  29941. var face = 0;
  29942. for (var index = 0; index < normals.length; index += 3) {
  29943. //Edge Face no. 1
  29944. if (Math.abs(normals[index + 1]) < 0.001) {
  29945. face = 1;
  29946. }
  29947. //Top Face no. 0
  29948. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29949. face = 0;
  29950. }
  29951. //Bottom Face no. 2
  29952. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29953. face = 2;
  29954. }
  29955. idx = index / 3;
  29956. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29957. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29958. if (faceColors) {
  29959. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29960. }
  29961. }
  29962. // sides
  29963. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  29964. // Result
  29965. var vertexData = new VertexData();
  29966. vertexData.indices = indices;
  29967. vertexData.positions = positions;
  29968. vertexData.normals = normals;
  29969. vertexData.uvs = uvs;
  29970. if (faceColors) {
  29971. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29972. vertexData.colors = totalColors;
  29973. }
  29974. return vertexData;
  29975. };
  29976. /**
  29977. * Creates the VertexData of the IcoSphere.
  29978. */
  29979. VertexData.CreateIcoSphere = function (options) {
  29980. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29981. var radius = options.radius || 1;
  29982. var flat = (options.flat === undefined) ? true : options.flat;
  29983. var subdivisions = options.subdivisions || 4;
  29984. var radiusX = options.radiusX || radius;
  29985. var radiusY = options.radiusY || radius;
  29986. var radiusZ = options.radiusZ || radius;
  29987. var t = (1 + Math.sqrt(5)) / 2;
  29988. // 12 vertex x,y,z
  29989. var ico_vertices = [
  29990. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29991. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29992. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29993. ];
  29994. // index of 3 vertex makes a face of icopshere
  29995. var ico_indices = [
  29996. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29997. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29998. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29999. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30000. ];
  30001. // vertex for uv have aliased position, not for UV
  30002. var vertices_unalias_id = [
  30003. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30004. // vertex alias
  30005. 0,
  30006. 2,
  30007. 3,
  30008. 3,
  30009. 3,
  30010. 4,
  30011. 7,
  30012. 8,
  30013. 9,
  30014. 9,
  30015. 10,
  30016. 11 // 23: B + 12
  30017. ];
  30018. // uv as integer step (not pixels !)
  30019. var ico_vertexuv = [
  30020. 5, 1, 3, 1, 6, 4, 0, 0,
  30021. 5, 3, 4, 2, 2, 2, 4, 0,
  30022. 2, 0, 1, 1, 6, 0, 6, 2,
  30023. // vertex alias (for same vertex on different faces)
  30024. 0, 4,
  30025. 3, 3,
  30026. 4, 4,
  30027. 3, 1,
  30028. 4, 2,
  30029. 4, 4,
  30030. 0, 2,
  30031. 1, 1,
  30032. 2, 2,
  30033. 3, 3,
  30034. 1, 3,
  30035. 2, 4 // 23: B + 12
  30036. ];
  30037. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30038. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30039. // First island of uv mapping
  30040. // v = 4h 3+ 2
  30041. // v = 3h 9+ 4
  30042. // v = 2h 9+ 5 B
  30043. // v = 1h 9 1 0
  30044. // v = 0h 3 8 7 A
  30045. // u = 0 1 2 3 4 5 6 *a
  30046. // Second island of uv mapping
  30047. // v = 4h 0+ B+ 4+
  30048. // v = 3h A+ 2+
  30049. // v = 2h 7+ 6 3+
  30050. // v = 1h 8+ 3+
  30051. // v = 0h
  30052. // u = 0 1 2 3 4 5 6 *a
  30053. // Face layout on texture UV mapping
  30054. // ============
  30055. // \ 4 /\ 16 / ======
  30056. // \ / \ / /\ 11 /
  30057. // \/ 7 \/ / \ /
  30058. // ======= / 10 \/
  30059. // /\ 17 /\ =======
  30060. // / \ / \ \ 15 /\
  30061. // / 8 \/ 12 \ \ / \
  30062. // ============ \/ 6 \
  30063. // \ 18 /\ ============
  30064. // \ / \ \ 5 /\ 0 /
  30065. // \/ 13 \ \ / \ /
  30066. // ======= \/ 1 \/
  30067. // =============
  30068. // /\ 19 /\ 2 /\
  30069. // / \ / \ / \
  30070. // / 14 \/ 9 \/ 3 \
  30071. // ===================
  30072. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30073. var ustep = 138 / 1024;
  30074. var vstep = 239 / 1024;
  30075. var uoffset = 60 / 1024;
  30076. var voffset = 26 / 1024;
  30077. // Second island should have margin, not to touch the first island
  30078. // avoid any borderline artefact in pixel rounding
  30079. var island_u_offset = -40 / 1024;
  30080. var island_v_offset = +20 / 1024;
  30081. // face is either island 0 or 1 :
  30082. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30083. var island = [
  30084. 0, 0, 0, 0, 1,
  30085. 0, 0, 1, 1, 0,
  30086. 0, 0, 1, 1, 0,
  30087. 0, 1, 1, 1, 0 // 15 - 19
  30088. ];
  30089. var indices = new Array();
  30090. var positions = new Array();
  30091. var normals = new Array();
  30092. var uvs = new Array();
  30093. var current_indice = 0;
  30094. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30095. var face_vertex_pos = new Array(3);
  30096. var face_vertex_uv = new Array(3);
  30097. var v012;
  30098. for (v012 = 0; v012 < 3; v012++) {
  30099. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30100. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30101. }
  30102. // create all with normals
  30103. for (var face = 0; face < 20; face++) {
  30104. // 3 vertex per face
  30105. for (v012 = 0; v012 < 3; v012++) {
  30106. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30107. var v_id = ico_indices[3 * face + v012];
  30108. // vertex have 3D position (x,y,z)
  30109. 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]);
  30110. // Normalize to get normal, then scale to radius
  30111. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30112. // uv Coordinates from vertex ID
  30113. 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);
  30114. }
  30115. // Subdivide the face (interpolate pos, norm, uv)
  30116. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30117. // - norm is linear interpolation of vertex corner normal
  30118. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30119. // - uv is linear interpolation
  30120. //
  30121. // Topology is as below for sub-divide by 2
  30122. // vertex shown as v0,v1,v2
  30123. // interp index is i1 to progress in range [v0,v1[
  30124. // interp index is i2 to progress in range [v0,v2[
  30125. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30126. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30127. //
  30128. //
  30129. // i2 v2
  30130. // ^ ^
  30131. // / / \
  30132. // / / \
  30133. // / / \
  30134. // / / (0,1) \
  30135. // / #---------\
  30136. // / / \ (0,0)'/ \
  30137. // / / \ / \
  30138. // / / \ / \
  30139. // / / (0,0) \ / (1,0) \
  30140. // / #---------#---------\
  30141. // v0 v1
  30142. //
  30143. // --------------------> i1
  30144. //
  30145. // interp of (i1,i2):
  30146. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30147. // along i1 : lerp(x0,x1, i1/(S-i2))
  30148. //
  30149. // centroid of triangle is needed to get help normal computation
  30150. // (c1,c2) are used for centroid location
  30151. var interp_vertex = function (i1, i2, c1, c2) {
  30152. // vertex is interpolated from
  30153. // - face_vertex_pos[0..2]
  30154. // - face_vertex_uv[0..2]
  30155. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30156. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30157. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30158. pos_interp.normalize();
  30159. var vertex_normal;
  30160. if (flat) {
  30161. // in flat mode, recalculate normal as face centroid normal
  30162. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30163. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30164. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30165. }
  30166. else {
  30167. // in smooth mode, recalculate normal from each single vertex position
  30168. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30169. }
  30170. // Vertex normal need correction due to X,Y,Z radius scaling
  30171. vertex_normal.x /= radiusX;
  30172. vertex_normal.y /= radiusY;
  30173. vertex_normal.z /= radiusZ;
  30174. vertex_normal.normalize();
  30175. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30176. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30177. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30178. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30179. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30180. uvs.push(uv_interp.x, uv_interp.y);
  30181. // push each vertex has member of a face
  30182. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30183. indices.push(current_indice);
  30184. current_indice++;
  30185. };
  30186. for (var i2 = 0; i2 < subdivisions; i2++) {
  30187. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30188. // face : (i1,i2) for /\ :
  30189. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30190. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30191. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30192. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30193. if (i1 + i2 + 1 < subdivisions) {
  30194. // face : (i1,i2)' for \/ :
  30195. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30196. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30197. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30198. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30199. }
  30200. }
  30201. }
  30202. }
  30203. // Sides
  30204. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30205. // Result
  30206. var vertexData = new VertexData();
  30207. vertexData.indices = indices;
  30208. vertexData.positions = positions;
  30209. vertexData.normals = normals;
  30210. vertexData.uvs = uvs;
  30211. return vertexData;
  30212. };
  30213. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30214. /**
  30215. * Creates the VertexData of the Polyhedron.
  30216. */
  30217. VertexData.CreatePolyhedron = function (options) {
  30218. // provided polyhedron types :
  30219. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30220. // 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)
  30221. var polyhedra = [];
  30222. 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]] };
  30223. 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]] };
  30224. polyhedra[2] = {
  30225. 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]],
  30226. 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]]
  30227. };
  30228. polyhedra[3] = {
  30229. 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]],
  30230. 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]]
  30231. };
  30232. polyhedra[4] = {
  30233. 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]],
  30234. 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]]
  30235. };
  30236. 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]] };
  30237. 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]] };
  30238. 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]] };
  30239. 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]] };
  30240. 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]] };
  30241. 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]] };
  30242. 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]] };
  30243. 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]] };
  30244. 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]] };
  30245. polyhedra[14] = {
  30246. 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]],
  30247. 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]]
  30248. };
  30249. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30250. var size = options.size;
  30251. var sizeX = options.sizeX || size || 1;
  30252. var sizeY = options.sizeY || size || 1;
  30253. var sizeZ = options.sizeZ || size || 1;
  30254. var data = options.custom || polyhedra[type];
  30255. var nbfaces = data.face.length;
  30256. var faceUV = options.faceUV || new Array(nbfaces);
  30257. var faceColors = options.faceColors;
  30258. var flat = (options.flat === undefined) ? true : options.flat;
  30259. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30260. var positions = new Array();
  30261. var indices = new Array();
  30262. var normals = new Array();
  30263. var uvs = new Array();
  30264. var colors = new Array();
  30265. var index = 0;
  30266. var faceIdx = 0; // face cursor in the array "indexes"
  30267. var indexes = new Array();
  30268. var i = 0;
  30269. var f = 0;
  30270. var u, v, ang, x, y, tmp;
  30271. // default face colors and UV if undefined
  30272. if (flat) {
  30273. for (f = 0; f < nbfaces; f++) {
  30274. if (faceColors && faceColors[f] === undefined) {
  30275. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30276. }
  30277. if (faceUV && faceUV[f] === undefined) {
  30278. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30279. }
  30280. }
  30281. }
  30282. if (!flat) {
  30283. for (i = 0; i < data.vertex.length; i++) {
  30284. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30285. uvs.push(0, 0);
  30286. }
  30287. for (f = 0; f < nbfaces; f++) {
  30288. for (i = 0; i < data.face[f].length - 2; i++) {
  30289. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30290. }
  30291. }
  30292. }
  30293. else {
  30294. for (f = 0; f < nbfaces; f++) {
  30295. var fl = data.face[f].length; // number of vertices of the current face
  30296. ang = 2 * Math.PI / fl;
  30297. x = 0.5 * Math.tan(ang / 2);
  30298. y = 0.5;
  30299. // positions, uvs, colors
  30300. for (i = 0; i < fl; i++) {
  30301. // positions
  30302. 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);
  30303. indexes.push(index);
  30304. index++;
  30305. // uvs
  30306. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30307. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30308. uvs.push(u, v);
  30309. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30310. y = x * Math.sin(ang) + y * Math.cos(ang);
  30311. x = tmp;
  30312. // colors
  30313. if (faceColors) {
  30314. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30315. }
  30316. }
  30317. // indices from indexes
  30318. for (i = 0; i < fl - 2; i++) {
  30319. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30320. }
  30321. faceIdx += fl;
  30322. }
  30323. }
  30324. VertexData.ComputeNormals(positions, indices, normals);
  30325. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30326. var vertexData = new VertexData();
  30327. vertexData.positions = positions;
  30328. vertexData.indices = indices;
  30329. vertexData.normals = normals;
  30330. vertexData.uvs = uvs;
  30331. if (faceColors && flat) {
  30332. vertexData.colors = colors;
  30333. }
  30334. return vertexData;
  30335. };
  30336. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30337. /**
  30338. * Creates the VertexData of the Torus Knot.
  30339. */
  30340. VertexData.CreateTorusKnot = function (options) {
  30341. var indices = new Array();
  30342. var positions = new Array();
  30343. var normals = new Array();
  30344. var uvs = new Array();
  30345. var radius = options.radius || 2;
  30346. var tube = options.tube || 0.5;
  30347. var radialSegments = options.radialSegments || 32;
  30348. var tubularSegments = options.tubularSegments || 32;
  30349. var p = options.p || 2;
  30350. var q = options.q || 3;
  30351. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30352. // Helper
  30353. var getPos = function (angle) {
  30354. var cu = Math.cos(angle);
  30355. var su = Math.sin(angle);
  30356. var quOverP = q / p * angle;
  30357. var cs = Math.cos(quOverP);
  30358. var tx = radius * (2 + cs) * 0.5 * cu;
  30359. var ty = radius * (2 + cs) * su * 0.5;
  30360. var tz = radius * Math.sin(quOverP) * 0.5;
  30361. return new BABYLON.Vector3(tx, ty, tz);
  30362. };
  30363. // Vertices
  30364. var i;
  30365. var j;
  30366. for (i = 0; i <= radialSegments; i++) {
  30367. var modI = i % radialSegments;
  30368. var u = modI / radialSegments * 2 * p * Math.PI;
  30369. var p1 = getPos(u);
  30370. var p2 = getPos(u + 0.01);
  30371. var tang = p2.subtract(p1);
  30372. var n = p2.add(p1);
  30373. var bitan = BABYLON.Vector3.Cross(tang, n);
  30374. n = BABYLON.Vector3.Cross(bitan, tang);
  30375. bitan.normalize();
  30376. n.normalize();
  30377. for (j = 0; j < tubularSegments; j++) {
  30378. var modJ = j % tubularSegments;
  30379. var v = modJ / tubularSegments * 2 * Math.PI;
  30380. var cx = -tube * Math.cos(v);
  30381. var cy = tube * Math.sin(v);
  30382. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30383. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30384. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30385. uvs.push(i / radialSegments);
  30386. uvs.push(j / tubularSegments);
  30387. }
  30388. }
  30389. for (i = 0; i < radialSegments; i++) {
  30390. for (j = 0; j < tubularSegments; j++) {
  30391. var jNext = (j + 1) % tubularSegments;
  30392. var a = i * tubularSegments + j;
  30393. var b = (i + 1) * tubularSegments + j;
  30394. var c = (i + 1) * tubularSegments + jNext;
  30395. var d = i * tubularSegments + jNext;
  30396. indices.push(d);
  30397. indices.push(b);
  30398. indices.push(a);
  30399. indices.push(d);
  30400. indices.push(c);
  30401. indices.push(b);
  30402. }
  30403. }
  30404. // Normals
  30405. VertexData.ComputeNormals(positions, indices, normals);
  30406. // Sides
  30407. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30408. // Result
  30409. var vertexData = new VertexData();
  30410. vertexData.indices = indices;
  30411. vertexData.positions = positions;
  30412. vertexData.normals = normals;
  30413. vertexData.uvs = uvs;
  30414. return vertexData;
  30415. };
  30416. // Tools
  30417. /**
  30418. * @param {any} - positions (number[] or Float32Array)
  30419. * @param {any} - indices (number[] or Uint16Array)
  30420. * @param {any} - normals (number[] or Float32Array)
  30421. * options (optional) :
  30422. * facetPositions : optional array of facet positions (vector3)
  30423. * facetNormals : optional array of facet normals (vector3)
  30424. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30425. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30426. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30427. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30428. * bInfo : optional bounding info, required for facetPartitioning computation
  30429. * useRightHandedSystem: optional boolean to for right handed system computation
  30430. * depthSort : optional boolean to enable the facet depth sort computation
  30431. * distanceTo : optional Vector3 to compute the facet depth from this location
  30432. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30433. */
  30434. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30435. // temporary scalar variables
  30436. var index = 0; // facet index
  30437. var p1p2x = 0.0; // p1p2 vector x coordinate
  30438. var p1p2y = 0.0; // p1p2 vector y coordinate
  30439. var p1p2z = 0.0; // p1p2 vector z coordinate
  30440. var p3p2x = 0.0; // p3p2 vector x coordinate
  30441. var p3p2y = 0.0; // p3p2 vector y coordinate
  30442. var p3p2z = 0.0; // p3p2 vector z coordinate
  30443. var faceNormalx = 0.0; // facet normal x coordinate
  30444. var faceNormaly = 0.0; // facet normal y coordinate
  30445. var faceNormalz = 0.0; // facet normal z coordinate
  30446. var length = 0.0; // facet normal length before normalization
  30447. var v1x = 0; // vector1 x index in the positions array
  30448. var v1y = 0; // vector1 y index in the positions array
  30449. var v1z = 0; // vector1 z index in the positions array
  30450. var v2x = 0; // vector2 x index in the positions array
  30451. var v2y = 0; // vector2 y index in the positions array
  30452. var v2z = 0; // vector2 z index in the positions array
  30453. var v3x = 0; // vector3 x index in the positions array
  30454. var v3y = 0; // vector3 y index in the positions array
  30455. var v3z = 0; // vector3 z index in the positions array
  30456. var computeFacetNormals = false;
  30457. var computeFacetPositions = false;
  30458. var computeFacetPartitioning = false;
  30459. var computeDepthSort = false;
  30460. var faceNormalSign = 1;
  30461. var ratio = 0;
  30462. var distanceTo = null;
  30463. if (options) {
  30464. computeFacetNormals = (options.facetNormals) ? true : false;
  30465. computeFacetPositions = (options.facetPositions) ? true : false;
  30466. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30467. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30468. ratio = options.ratio || 0;
  30469. computeDepthSort = (options.depthSort) ? true : false;
  30470. distanceTo = (options.distanceTo);
  30471. if (computeDepthSort) {
  30472. if (distanceTo === undefined) {
  30473. distanceTo = BABYLON.Vector3.Zero();
  30474. }
  30475. var depthSortedFacets = options.depthSortedFacets;
  30476. }
  30477. }
  30478. // facetPartitioning reinit if needed
  30479. var xSubRatio = 0;
  30480. var ySubRatio = 0;
  30481. var zSubRatio = 0;
  30482. var subSq = 0;
  30483. if (computeFacetPartitioning && options && options.bbSize) {
  30484. var ox = 0; // X partitioning index for facet position
  30485. var oy = 0; // Y partinioning index for facet position
  30486. var oz = 0; // Z partinioning index for facet position
  30487. var b1x = 0; // X partitioning index for facet v1 vertex
  30488. var b1y = 0; // Y partitioning index for facet v1 vertex
  30489. var b1z = 0; // z partitioning index for facet v1 vertex
  30490. var b2x = 0; // X partitioning index for facet v2 vertex
  30491. var b2y = 0; // Y partitioning index for facet v2 vertex
  30492. var b2z = 0; // Z partitioning index for facet v2 vertex
  30493. var b3x = 0; // X partitioning index for facet v3 vertex
  30494. var b3y = 0; // Y partitioning index for facet v3 vertex
  30495. var b3z = 0; // Z partitioning index for facet v3 vertex
  30496. var block_idx_o = 0; // facet barycenter block index
  30497. var block_idx_v1 = 0; // v1 vertex block index
  30498. var block_idx_v2 = 0; // v2 vertex block index
  30499. var block_idx_v3 = 0; // v3 vertex block index
  30500. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30501. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30502. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30503. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30504. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30505. subSq = options.subDiv.max * options.subDiv.max;
  30506. options.facetPartitioning.length = 0;
  30507. }
  30508. // reset the normals
  30509. for (index = 0; index < positions.length; index++) {
  30510. normals[index] = 0.0;
  30511. }
  30512. // Loop : 1 indice triplet = 1 facet
  30513. var nbFaces = indices.length / 3;
  30514. for (index = 0; index < nbFaces; index++) {
  30515. // get the indexes of the coordinates of each vertex of the facet
  30516. v1x = indices[index * 3] * 3;
  30517. v1y = v1x + 1;
  30518. v1z = v1x + 2;
  30519. v2x = indices[index * 3 + 1] * 3;
  30520. v2y = v2x + 1;
  30521. v2z = v2x + 2;
  30522. v3x = indices[index * 3 + 2] * 3;
  30523. v3y = v3x + 1;
  30524. v3z = v3x + 2;
  30525. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30526. p1p2y = positions[v1y] - positions[v2y];
  30527. p1p2z = positions[v1z] - positions[v2z];
  30528. p3p2x = positions[v3x] - positions[v2x];
  30529. p3p2y = positions[v3y] - positions[v2y];
  30530. p3p2z = positions[v3z] - positions[v2z];
  30531. // compute the face normal with the cross product
  30532. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30533. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30534. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30535. // normalize this normal and store it in the array facetData
  30536. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30537. length = (length === 0) ? 1.0 : length;
  30538. faceNormalx /= length;
  30539. faceNormaly /= length;
  30540. faceNormalz /= length;
  30541. if (computeFacetNormals && options) {
  30542. options.facetNormals[index].x = faceNormalx;
  30543. options.facetNormals[index].y = faceNormaly;
  30544. options.facetNormals[index].z = faceNormalz;
  30545. }
  30546. if (computeFacetPositions && options) {
  30547. // compute and the facet barycenter coordinates in the array facetPositions
  30548. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30549. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30550. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30551. }
  30552. if (computeFacetPartitioning && options) {
  30553. // store the facet indexes in arrays in the main facetPartitioning array :
  30554. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30555. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30556. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30557. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30558. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30559. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30560. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30561. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30562. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30563. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30564. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30565. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30566. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30567. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30568. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30569. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30570. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30571. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30572. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30573. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30574. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30575. // push each facet index in each block containing the vertex
  30576. options.facetPartitioning[block_idx_v1].push(index);
  30577. if (block_idx_v2 != block_idx_v1) {
  30578. options.facetPartitioning[block_idx_v2].push(index);
  30579. }
  30580. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30581. options.facetPartitioning[block_idx_v3].push(index);
  30582. }
  30583. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30584. options.facetPartitioning[block_idx_o].push(index);
  30585. }
  30586. }
  30587. if (computeDepthSort && options && options.facetPositions) {
  30588. var dsf = depthSortedFacets[index];
  30589. dsf.ind = index * 3;
  30590. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  30591. }
  30592. // compute the normals anyway
  30593. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30594. normals[v1y] += faceNormaly;
  30595. normals[v1z] += faceNormalz;
  30596. normals[v2x] += faceNormalx;
  30597. normals[v2y] += faceNormaly;
  30598. normals[v2z] += faceNormalz;
  30599. normals[v3x] += faceNormalx;
  30600. normals[v3y] += faceNormaly;
  30601. normals[v3z] += faceNormalz;
  30602. }
  30603. // last normalization of each normal
  30604. for (index = 0; index < normals.length / 3; index++) {
  30605. faceNormalx = normals[index * 3];
  30606. faceNormaly = normals[index * 3 + 1];
  30607. faceNormalz = normals[index * 3 + 2];
  30608. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30609. length = (length === 0) ? 1.0 : length;
  30610. faceNormalx /= length;
  30611. faceNormaly /= length;
  30612. faceNormalz /= length;
  30613. normals[index * 3] = faceNormalx;
  30614. normals[index * 3 + 1] = faceNormaly;
  30615. normals[index * 3 + 2] = faceNormalz;
  30616. }
  30617. };
  30618. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30619. var li = indices.length;
  30620. var ln = normals.length;
  30621. var i;
  30622. var n;
  30623. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30624. switch (sideOrientation) {
  30625. case BABYLON.Mesh.FRONTSIDE:
  30626. // nothing changed
  30627. break;
  30628. case BABYLON.Mesh.BACKSIDE:
  30629. var tmp;
  30630. // indices
  30631. for (i = 0; i < li; i += 3) {
  30632. tmp = indices[i];
  30633. indices[i] = indices[i + 2];
  30634. indices[i + 2] = tmp;
  30635. }
  30636. // normals
  30637. for (n = 0; n < ln; n++) {
  30638. normals[n] = -normals[n];
  30639. }
  30640. break;
  30641. case BABYLON.Mesh.DOUBLESIDE:
  30642. // positions
  30643. var lp = positions.length;
  30644. var l = lp / 3;
  30645. for (var p = 0; p < lp; p++) {
  30646. positions[lp + p] = positions[p];
  30647. }
  30648. // indices
  30649. for (i = 0; i < li; i += 3) {
  30650. indices[i + li] = indices[i + 2] + l;
  30651. indices[i + 1 + li] = indices[i + 1] + l;
  30652. indices[i + 2 + li] = indices[i] + l;
  30653. }
  30654. // normals
  30655. for (n = 0; n < ln; n++) {
  30656. normals[ln + n] = -normals[n];
  30657. }
  30658. // uvs
  30659. var lu = uvs.length;
  30660. var u = 0;
  30661. for (u = 0; u < lu; u++) {
  30662. uvs[u + lu] = uvs[u];
  30663. }
  30664. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30665. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30666. u = 0;
  30667. for (i = 0; i < lu / 2; i++) {
  30668. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30669. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30670. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30671. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30672. u += 2;
  30673. }
  30674. break;
  30675. }
  30676. };
  30677. /**
  30678. * Creates a new VertexData from the imported parameters.
  30679. */
  30680. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30681. var vertexData = new VertexData();
  30682. // positions
  30683. var positions = parsedVertexData.positions;
  30684. if (positions) {
  30685. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30686. }
  30687. // normals
  30688. var normals = parsedVertexData.normals;
  30689. if (normals) {
  30690. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30691. }
  30692. // tangents
  30693. var tangents = parsedVertexData.tangents;
  30694. if (tangents) {
  30695. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30696. }
  30697. // uvs
  30698. var uvs = parsedVertexData.uvs;
  30699. if (uvs) {
  30700. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30701. }
  30702. // uv2s
  30703. var uv2s = parsedVertexData.uv2s;
  30704. if (uv2s) {
  30705. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30706. }
  30707. // uv3s
  30708. var uv3s = parsedVertexData.uv3s;
  30709. if (uv3s) {
  30710. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30711. }
  30712. // uv4s
  30713. var uv4s = parsedVertexData.uv4s;
  30714. if (uv4s) {
  30715. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30716. }
  30717. // uv5s
  30718. var uv5s = parsedVertexData.uv5s;
  30719. if (uv5s) {
  30720. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30721. }
  30722. // uv6s
  30723. var uv6s = parsedVertexData.uv6s;
  30724. if (uv6s) {
  30725. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30726. }
  30727. // colors
  30728. var colors = parsedVertexData.colors;
  30729. if (colors) {
  30730. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30731. }
  30732. // matricesIndices
  30733. var matricesIndices = parsedVertexData.matricesIndices;
  30734. if (matricesIndices) {
  30735. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30736. }
  30737. // matricesWeights
  30738. var matricesWeights = parsedVertexData.matricesWeights;
  30739. if (matricesWeights) {
  30740. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30741. }
  30742. // indices
  30743. var indices = parsedVertexData.indices;
  30744. if (indices) {
  30745. vertexData.indices = indices;
  30746. }
  30747. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30748. };
  30749. return VertexData;
  30750. }());
  30751. BABYLON.VertexData = VertexData;
  30752. })(BABYLON || (BABYLON = {}));
  30753. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30754. var BABYLON;
  30755. (function (BABYLON) {
  30756. var Geometry = /** @class */ (function () {
  30757. function Geometry(id, scene, vertexData, updatable, mesh) {
  30758. if (updatable === void 0) { updatable = false; }
  30759. if (mesh === void 0) { mesh = null; }
  30760. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30761. this._totalVertices = 0;
  30762. this._isDisposed = false;
  30763. this._indexBufferIsUpdatable = false;
  30764. this.id = id;
  30765. this._engine = scene.getEngine();
  30766. this._meshes = [];
  30767. this._scene = scene;
  30768. //Init vertex buffer cache
  30769. this._vertexBuffers = {};
  30770. this._indices = [];
  30771. this._updatable = updatable;
  30772. // vertexData
  30773. if (vertexData) {
  30774. this.setAllVerticesData(vertexData, updatable);
  30775. }
  30776. else {
  30777. this._totalVertices = 0;
  30778. this._indices = [];
  30779. }
  30780. if (this._engine.getCaps().vertexArrayObject) {
  30781. this._vertexArrayObjects = {};
  30782. }
  30783. // applyToMesh
  30784. if (mesh) {
  30785. if (mesh.getClassName() === "LinesMesh") {
  30786. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30787. this.updateExtend();
  30788. }
  30789. this.applyToMesh(mesh);
  30790. mesh.computeWorldMatrix(true);
  30791. }
  30792. }
  30793. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30794. /**
  30795. * 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
  30796. * @returns The Bias Vector
  30797. */
  30798. get: function () {
  30799. return this._boundingBias;
  30800. },
  30801. set: function (value) {
  30802. if (this._boundingBias && this._boundingBias.equals(value)) {
  30803. return;
  30804. }
  30805. this._boundingBias = value.clone();
  30806. this.updateBoundingInfo(true, null);
  30807. },
  30808. enumerable: true,
  30809. configurable: true
  30810. });
  30811. Geometry.CreateGeometryForMesh = function (mesh) {
  30812. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30813. geometry.applyToMesh(mesh);
  30814. return geometry;
  30815. };
  30816. Object.defineProperty(Geometry.prototype, "extend", {
  30817. get: function () {
  30818. return this._extend;
  30819. },
  30820. enumerable: true,
  30821. configurable: true
  30822. });
  30823. Geometry.prototype.getScene = function () {
  30824. return this._scene;
  30825. };
  30826. Geometry.prototype.getEngine = function () {
  30827. return this._engine;
  30828. };
  30829. Geometry.prototype.isReady = function () {
  30830. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30831. };
  30832. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30833. get: function () {
  30834. for (var index = 0; index < this._meshes.length; index++) {
  30835. if (!this._meshes[index].doNotSerialize) {
  30836. return false;
  30837. }
  30838. }
  30839. return true;
  30840. },
  30841. enumerable: true,
  30842. configurable: true
  30843. });
  30844. Geometry.prototype._rebuild = function () {
  30845. if (this._vertexArrayObjects) {
  30846. this._vertexArrayObjects = {};
  30847. }
  30848. // Index buffer
  30849. if (this._meshes.length !== 0 && this._indices) {
  30850. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30851. }
  30852. // Vertex buffers
  30853. for (var key in this._vertexBuffers) {
  30854. var vertexBuffer = this._vertexBuffers[key];
  30855. vertexBuffer._rebuild();
  30856. }
  30857. };
  30858. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30859. vertexData.applyToGeometry(this, updatable);
  30860. this.notifyUpdate();
  30861. };
  30862. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30863. if (updatable === void 0) { updatable = false; }
  30864. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30865. this.setVerticesBuffer(buffer);
  30866. };
  30867. Geometry.prototype.removeVerticesData = function (kind) {
  30868. if (this._vertexBuffers[kind]) {
  30869. this._vertexBuffers[kind].dispose();
  30870. delete this._vertexBuffers[kind];
  30871. }
  30872. };
  30873. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30874. var kind = buffer.getKind();
  30875. if (this._vertexBuffers[kind]) {
  30876. this._vertexBuffers[kind].dispose();
  30877. }
  30878. this._vertexBuffers[kind] = buffer;
  30879. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30880. var data = buffer.getData();
  30881. var stride = buffer.getStrideSize();
  30882. this._totalVertices = data.length / stride;
  30883. this.updateExtend(data, stride);
  30884. this._resetPointsArrayCache();
  30885. var meshes = this._meshes;
  30886. var numOfMeshes = meshes.length;
  30887. for (var index = 0; index < numOfMeshes; index++) {
  30888. var mesh = meshes[index];
  30889. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30890. mesh._createGlobalSubMesh(false);
  30891. mesh.computeWorldMatrix(true);
  30892. }
  30893. }
  30894. this.notifyUpdate(kind);
  30895. if (this._vertexArrayObjects) {
  30896. this._disposeVertexArrayObjects();
  30897. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30898. }
  30899. };
  30900. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30901. var vertexBuffer = this.getVertexBuffer(kind);
  30902. if (!vertexBuffer) {
  30903. return;
  30904. }
  30905. vertexBuffer.updateDirectly(data, offset);
  30906. this.notifyUpdate(kind);
  30907. };
  30908. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30909. if (updateExtends === void 0) { updateExtends = false; }
  30910. var vertexBuffer = this.getVertexBuffer(kind);
  30911. if (!vertexBuffer) {
  30912. return;
  30913. }
  30914. vertexBuffer.update(data);
  30915. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30916. var stride = vertexBuffer.getStrideSize();
  30917. this._totalVertices = data.length / stride;
  30918. this.updateBoundingInfo(updateExtends, data);
  30919. }
  30920. this.notifyUpdate(kind);
  30921. };
  30922. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30923. if (updateExtends) {
  30924. this.updateExtend(data);
  30925. }
  30926. var meshes = this._meshes;
  30927. var numOfMeshes = meshes.length;
  30928. this._resetPointsArrayCache();
  30929. for (var index = 0; index < numOfMeshes; index++) {
  30930. var mesh = meshes[index];
  30931. if (updateExtends) {
  30932. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30933. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30934. var subMesh = mesh.subMeshes[subIndex];
  30935. subMesh.refreshBoundingInfo();
  30936. }
  30937. }
  30938. }
  30939. };
  30940. Geometry.prototype._bind = function (effect, indexToBind) {
  30941. if (!effect) {
  30942. return;
  30943. }
  30944. if (indexToBind === undefined) {
  30945. indexToBind = this._indexBuffer;
  30946. }
  30947. var vbs = this.getVertexBuffers();
  30948. if (!vbs) {
  30949. return;
  30950. }
  30951. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30952. this._engine.bindBuffers(vbs, indexToBind, effect);
  30953. return;
  30954. }
  30955. // Using VAO
  30956. if (!this._vertexArrayObjects[effect.key]) {
  30957. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30958. }
  30959. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30960. };
  30961. Geometry.prototype.getTotalVertices = function () {
  30962. if (!this.isReady()) {
  30963. return 0;
  30964. }
  30965. return this._totalVertices;
  30966. };
  30967. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30968. var vertexBuffer = this.getVertexBuffer(kind);
  30969. if (!vertexBuffer) {
  30970. return null;
  30971. }
  30972. var orig = vertexBuffer.getData();
  30973. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  30974. return orig;
  30975. }
  30976. else {
  30977. var len = orig.length;
  30978. var copy = [];
  30979. for (var i = 0; i < len; i++) {
  30980. copy.push(orig[i]);
  30981. }
  30982. return copy;
  30983. }
  30984. };
  30985. /**
  30986. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30987. * Possible `kind` values :
  30988. * - BABYLON.VertexBuffer.PositionKind
  30989. * - BABYLON.VertexBuffer.UVKind
  30990. * - BABYLON.VertexBuffer.UV2Kind
  30991. * - BABYLON.VertexBuffer.UV3Kind
  30992. * - BABYLON.VertexBuffer.UV4Kind
  30993. * - BABYLON.VertexBuffer.UV5Kind
  30994. * - BABYLON.VertexBuffer.UV6Kind
  30995. * - BABYLON.VertexBuffer.ColorKind
  30996. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30997. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30998. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30999. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31000. */
  31001. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31002. var vb = this._vertexBuffers[kind];
  31003. if (!vb) {
  31004. return false;
  31005. }
  31006. return vb.isUpdatable();
  31007. };
  31008. Geometry.prototype.getVertexBuffer = function (kind) {
  31009. if (!this.isReady()) {
  31010. return null;
  31011. }
  31012. return this._vertexBuffers[kind];
  31013. };
  31014. Geometry.prototype.getVertexBuffers = function () {
  31015. if (!this.isReady()) {
  31016. return null;
  31017. }
  31018. return this._vertexBuffers;
  31019. };
  31020. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31021. if (!this._vertexBuffers) {
  31022. if (this._delayInfo) {
  31023. return this._delayInfo.indexOf(kind) !== -1;
  31024. }
  31025. return false;
  31026. }
  31027. return this._vertexBuffers[kind] !== undefined;
  31028. };
  31029. Geometry.prototype.getVerticesDataKinds = function () {
  31030. var result = [];
  31031. var kind;
  31032. if (!this._vertexBuffers && this._delayInfo) {
  31033. for (kind in this._delayInfo) {
  31034. result.push(kind);
  31035. }
  31036. }
  31037. else {
  31038. for (kind in this._vertexBuffers) {
  31039. result.push(kind);
  31040. }
  31041. }
  31042. return result;
  31043. };
  31044. Geometry.prototype.updateIndices = function (indices, offset) {
  31045. if (!this._indexBuffer) {
  31046. return;
  31047. }
  31048. if (!this._indexBufferIsUpdatable) {
  31049. this.setIndices(indices, null, true);
  31050. }
  31051. else {
  31052. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31053. }
  31054. };
  31055. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31056. if (totalVertices === void 0) { totalVertices = null; }
  31057. if (updatable === void 0) { updatable = false; }
  31058. if (this._indexBuffer) {
  31059. this._engine._releaseBuffer(this._indexBuffer);
  31060. }
  31061. this._disposeVertexArrayObjects();
  31062. this._indices = indices;
  31063. this._indexBufferIsUpdatable = updatable;
  31064. if (this._meshes.length !== 0 && this._indices) {
  31065. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31066. }
  31067. if (totalVertices != undefined) {
  31068. this._totalVertices = totalVertices;
  31069. }
  31070. var meshes = this._meshes;
  31071. var numOfMeshes = meshes.length;
  31072. for (var index = 0; index < numOfMeshes; index++) {
  31073. meshes[index]._createGlobalSubMesh(true);
  31074. }
  31075. this.notifyUpdate();
  31076. };
  31077. Geometry.prototype.getTotalIndices = function () {
  31078. if (!this.isReady()) {
  31079. return 0;
  31080. }
  31081. return this._indices.length;
  31082. };
  31083. Geometry.prototype.getIndices = function (copyWhenShared) {
  31084. if (!this.isReady()) {
  31085. return null;
  31086. }
  31087. var orig = this._indices;
  31088. if (!copyWhenShared || this._meshes.length === 1) {
  31089. return orig;
  31090. }
  31091. else {
  31092. var len = orig.length;
  31093. var copy = [];
  31094. for (var i = 0; i < len; i++) {
  31095. copy.push(orig[i]);
  31096. }
  31097. return copy;
  31098. }
  31099. };
  31100. Geometry.prototype.getIndexBuffer = function () {
  31101. if (!this.isReady()) {
  31102. return null;
  31103. }
  31104. return this._indexBuffer;
  31105. };
  31106. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31107. if (effect === void 0) { effect = null; }
  31108. if (!effect || !this._vertexArrayObjects) {
  31109. return;
  31110. }
  31111. if (this._vertexArrayObjects[effect.key]) {
  31112. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31113. delete this._vertexArrayObjects[effect.key];
  31114. }
  31115. };
  31116. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31117. var meshes = this._meshes;
  31118. var index = meshes.indexOf(mesh);
  31119. if (index === -1) {
  31120. return;
  31121. }
  31122. meshes.splice(index, 1);
  31123. mesh._geometry = null;
  31124. if (meshes.length === 0 && shouldDispose) {
  31125. this.dispose();
  31126. }
  31127. };
  31128. Geometry.prototype.applyToMesh = function (mesh) {
  31129. if (mesh._geometry === this) {
  31130. return;
  31131. }
  31132. var previousGeometry = mesh._geometry;
  31133. if (previousGeometry) {
  31134. previousGeometry.releaseForMesh(mesh);
  31135. }
  31136. var meshes = this._meshes;
  31137. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31138. mesh._geometry = this;
  31139. this._scene.pushGeometry(this);
  31140. meshes.push(mesh);
  31141. if (this.isReady()) {
  31142. this._applyToMesh(mesh);
  31143. }
  31144. else {
  31145. mesh._boundingInfo = this._boundingInfo;
  31146. }
  31147. };
  31148. Geometry.prototype.updateExtend = function (data, stride) {
  31149. if (data === void 0) { data = null; }
  31150. if (!data) {
  31151. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31152. }
  31153. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31154. };
  31155. Geometry.prototype._applyToMesh = function (mesh) {
  31156. var numOfMeshes = this._meshes.length;
  31157. // vertexBuffers
  31158. for (var kind in this._vertexBuffers) {
  31159. if (numOfMeshes === 1) {
  31160. this._vertexBuffers[kind].create();
  31161. }
  31162. var buffer = this._vertexBuffers[kind].getBuffer();
  31163. if (buffer)
  31164. buffer.references = numOfMeshes;
  31165. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31166. if (!this._extend) {
  31167. this.updateExtend(this._vertexBuffers[kind].getData());
  31168. }
  31169. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31170. mesh._createGlobalSubMesh(false);
  31171. //bounding info was just created again, world matrix should be applied again.
  31172. mesh._updateBoundingInfo();
  31173. }
  31174. }
  31175. // indexBuffer
  31176. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31177. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31178. }
  31179. if (this._indexBuffer) {
  31180. this._indexBuffer.references = numOfMeshes;
  31181. }
  31182. };
  31183. Geometry.prototype.notifyUpdate = function (kind) {
  31184. if (this.onGeometryUpdated) {
  31185. this.onGeometryUpdated(this, kind);
  31186. }
  31187. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31188. var mesh = _a[_i];
  31189. mesh._markSubMeshesAsAttributesDirty();
  31190. }
  31191. };
  31192. Geometry.prototype.load = function (scene, onLoaded) {
  31193. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31194. return;
  31195. }
  31196. if (this.isReady()) {
  31197. if (onLoaded) {
  31198. onLoaded();
  31199. }
  31200. return;
  31201. }
  31202. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31203. this._queueLoad(scene, onLoaded);
  31204. };
  31205. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31206. var _this = this;
  31207. if (!this.delayLoadingFile) {
  31208. return;
  31209. }
  31210. scene._addPendingData(this);
  31211. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31212. if (!_this._delayLoadingFunction) {
  31213. return;
  31214. }
  31215. _this._delayLoadingFunction(JSON.parse(data), _this);
  31216. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31217. _this._delayInfo = [];
  31218. scene._removePendingData(_this);
  31219. var meshes = _this._meshes;
  31220. var numOfMeshes = meshes.length;
  31221. for (var index = 0; index < numOfMeshes; index++) {
  31222. _this._applyToMesh(meshes[index]);
  31223. }
  31224. if (onLoaded) {
  31225. onLoaded();
  31226. }
  31227. }, function () { }, scene.database);
  31228. };
  31229. /**
  31230. * Invert the geometry to move from a right handed system to a left handed one.
  31231. */
  31232. Geometry.prototype.toLeftHanded = function () {
  31233. // Flip faces
  31234. var tIndices = this.getIndices(false);
  31235. if (tIndices != null && tIndices.length > 0) {
  31236. for (var i = 0; i < tIndices.length; i += 3) {
  31237. var tTemp = tIndices[i + 0];
  31238. tIndices[i + 0] = tIndices[i + 2];
  31239. tIndices[i + 2] = tTemp;
  31240. }
  31241. this.setIndices(tIndices);
  31242. }
  31243. // Negate position.z
  31244. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31245. if (tPositions != null && tPositions.length > 0) {
  31246. for (var i = 0; i < tPositions.length; i += 3) {
  31247. tPositions[i + 2] = -tPositions[i + 2];
  31248. }
  31249. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31250. }
  31251. // Negate normal.z
  31252. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31253. if (tNormals != null && tNormals.length > 0) {
  31254. for (var i = 0; i < tNormals.length; i += 3) {
  31255. tNormals[i + 2] = -tNormals[i + 2];
  31256. }
  31257. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31258. }
  31259. };
  31260. // Cache
  31261. Geometry.prototype._resetPointsArrayCache = function () {
  31262. this._positions = null;
  31263. };
  31264. Geometry.prototype._generatePointsArray = function () {
  31265. if (this._positions)
  31266. return true;
  31267. this._positions = [];
  31268. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31269. if (!data) {
  31270. return false;
  31271. }
  31272. for (var index = 0; index < data.length; index += 3) {
  31273. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31274. }
  31275. return true;
  31276. };
  31277. Geometry.prototype.isDisposed = function () {
  31278. return this._isDisposed;
  31279. };
  31280. Geometry.prototype._disposeVertexArrayObjects = function () {
  31281. if (this._vertexArrayObjects) {
  31282. for (var kind in this._vertexArrayObjects) {
  31283. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31284. }
  31285. this._vertexArrayObjects = {};
  31286. }
  31287. };
  31288. Geometry.prototype.dispose = function () {
  31289. var meshes = this._meshes;
  31290. var numOfMeshes = meshes.length;
  31291. var index;
  31292. for (index = 0; index < numOfMeshes; index++) {
  31293. this.releaseForMesh(meshes[index]);
  31294. }
  31295. this._meshes = [];
  31296. this._disposeVertexArrayObjects();
  31297. for (var kind in this._vertexBuffers) {
  31298. this._vertexBuffers[kind].dispose();
  31299. }
  31300. this._vertexBuffers = {};
  31301. this._totalVertices = 0;
  31302. if (this._indexBuffer) {
  31303. this._engine._releaseBuffer(this._indexBuffer);
  31304. }
  31305. this._indexBuffer = null;
  31306. this._indices = [];
  31307. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31308. this.delayLoadingFile = null;
  31309. this._delayLoadingFunction = null;
  31310. this._delayInfo = [];
  31311. this._boundingInfo = null;
  31312. this._scene.removeGeometry(this);
  31313. this._isDisposed = true;
  31314. };
  31315. Geometry.prototype.copy = function (id) {
  31316. var vertexData = new BABYLON.VertexData();
  31317. vertexData.indices = [];
  31318. var indices = this.getIndices();
  31319. if (indices) {
  31320. for (var index = 0; index < indices.length; index++) {
  31321. vertexData.indices.push(indices[index]);
  31322. }
  31323. }
  31324. var updatable = false;
  31325. var stopChecking = false;
  31326. var kind;
  31327. for (kind in this._vertexBuffers) {
  31328. // using slice() to make a copy of the array and not just reference it
  31329. var data = this.getVerticesData(kind);
  31330. if (data instanceof Float32Array) {
  31331. vertexData.set(new Float32Array(data), kind);
  31332. }
  31333. else {
  31334. vertexData.set(data.slice(0), kind);
  31335. }
  31336. if (!stopChecking) {
  31337. var vb = this.getVertexBuffer(kind);
  31338. if (vb) {
  31339. updatable = vb.isUpdatable();
  31340. stopChecking = !updatable;
  31341. }
  31342. }
  31343. }
  31344. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31345. geometry.delayLoadState = this.delayLoadState;
  31346. geometry.delayLoadingFile = this.delayLoadingFile;
  31347. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31348. for (kind in this._delayInfo) {
  31349. geometry._delayInfo = geometry._delayInfo || [];
  31350. geometry._delayInfo.push(kind);
  31351. }
  31352. // Bounding info
  31353. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31354. return geometry;
  31355. };
  31356. Geometry.prototype.serialize = function () {
  31357. var serializationObject = {};
  31358. serializationObject.id = this.id;
  31359. serializationObject.updatable = this._updatable;
  31360. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31361. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31362. }
  31363. return serializationObject;
  31364. };
  31365. Geometry.prototype.toNumberArray = function (origin) {
  31366. if (Array.isArray(origin)) {
  31367. return origin;
  31368. }
  31369. else {
  31370. return Array.prototype.slice.call(origin);
  31371. }
  31372. };
  31373. Geometry.prototype.serializeVerticeData = function () {
  31374. var serializationObject = this.serialize();
  31375. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31376. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31377. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31378. serializationObject.positions._updatable = true;
  31379. }
  31380. }
  31381. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31382. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31383. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31384. serializationObject.normals._updatable = true;
  31385. }
  31386. }
  31387. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31388. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31389. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31390. serializationObject.uvs._updatable = true;
  31391. }
  31392. }
  31393. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31394. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31395. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31396. serializationObject.uv2s._updatable = true;
  31397. }
  31398. }
  31399. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31400. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31401. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31402. serializationObject.uv3s._updatable = true;
  31403. }
  31404. }
  31405. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31406. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31407. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31408. serializationObject.uv4s._updatable = true;
  31409. }
  31410. }
  31411. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31412. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31413. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31414. serializationObject.uv5s._updatable = true;
  31415. }
  31416. }
  31417. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31418. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31419. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31420. serializationObject.uv6s._updatable = true;
  31421. }
  31422. }
  31423. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31424. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31425. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31426. serializationObject.colors._updatable = true;
  31427. }
  31428. }
  31429. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31430. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31431. serializationObject.matricesIndices._isExpanded = true;
  31432. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31433. serializationObject.matricesIndices._updatable = true;
  31434. }
  31435. }
  31436. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31437. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31438. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31439. serializationObject.matricesWeights._updatable = true;
  31440. }
  31441. }
  31442. serializationObject.indices = this.toNumberArray(this.getIndices());
  31443. return serializationObject;
  31444. };
  31445. // Statics
  31446. Geometry.ExtractFromMesh = function (mesh, id) {
  31447. var geometry = mesh._geometry;
  31448. if (!geometry) {
  31449. return null;
  31450. }
  31451. return geometry.copy(id);
  31452. };
  31453. /**
  31454. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31455. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31456. * Be aware Math.random() could cause collisions, but:
  31457. * "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"
  31458. */
  31459. Geometry.RandomId = function () {
  31460. return BABYLON.Tools.RandomId();
  31461. };
  31462. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31463. var scene = mesh.getScene();
  31464. // Geometry
  31465. var geometryId = parsedGeometry.geometryId;
  31466. if (geometryId) {
  31467. var geometry = scene.getGeometryByID(geometryId);
  31468. if (geometry) {
  31469. geometry.applyToMesh(mesh);
  31470. }
  31471. }
  31472. else if (parsedGeometry instanceof ArrayBuffer) {
  31473. var binaryInfo = mesh._binaryInfo;
  31474. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31475. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31476. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31477. }
  31478. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31479. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31480. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31481. }
  31482. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31483. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31484. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31485. }
  31486. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31487. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31488. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31489. }
  31490. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31491. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31492. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31493. }
  31494. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31495. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31496. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31497. }
  31498. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31499. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31500. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31501. }
  31502. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31503. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31504. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31505. }
  31506. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31507. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31508. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31509. }
  31510. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31511. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31512. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31513. }
  31514. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31515. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31516. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31517. }
  31518. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31519. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31520. mesh.setIndices(indicesData, null);
  31521. }
  31522. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31523. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31524. mesh.subMeshes = [];
  31525. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31526. var materialIndex = subMeshesData[(i * 5) + 0];
  31527. var verticesStart = subMeshesData[(i * 5) + 1];
  31528. var verticesCount = subMeshesData[(i * 5) + 2];
  31529. var indexStart = subMeshesData[(i * 5) + 3];
  31530. var indexCount = subMeshesData[(i * 5) + 4];
  31531. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31532. }
  31533. }
  31534. }
  31535. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31536. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31537. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31538. if (parsedGeometry.uvs) {
  31539. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31540. }
  31541. if (parsedGeometry.uvs2) {
  31542. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31543. }
  31544. if (parsedGeometry.uvs3) {
  31545. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31546. }
  31547. if (parsedGeometry.uvs4) {
  31548. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31549. }
  31550. if (parsedGeometry.uvs5) {
  31551. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31552. }
  31553. if (parsedGeometry.uvs6) {
  31554. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31555. }
  31556. if (parsedGeometry.colors) {
  31557. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31558. }
  31559. if (parsedGeometry.matricesIndices) {
  31560. if (!parsedGeometry.matricesIndices._isExpanded) {
  31561. var floatIndices = [];
  31562. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31563. var matricesIndex = parsedGeometry.matricesIndices[i];
  31564. floatIndices.push(matricesIndex & 0x000000FF);
  31565. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31566. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31567. floatIndices.push(matricesIndex >> 24);
  31568. }
  31569. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31570. }
  31571. else {
  31572. delete parsedGeometry.matricesIndices._isExpanded;
  31573. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31574. }
  31575. }
  31576. if (parsedGeometry.matricesIndicesExtra) {
  31577. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31578. var floatIndices = [];
  31579. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31580. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31581. floatIndices.push(matricesIndex & 0x000000FF);
  31582. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31583. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31584. floatIndices.push(matricesIndex >> 24);
  31585. }
  31586. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31587. }
  31588. else {
  31589. delete parsedGeometry.matricesIndices._isExpanded;
  31590. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31591. }
  31592. }
  31593. if (parsedGeometry.matricesWeights) {
  31594. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31595. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31596. }
  31597. if (parsedGeometry.matricesWeightsExtra) {
  31598. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31599. }
  31600. mesh.setIndices(parsedGeometry.indices, null);
  31601. }
  31602. // SubMeshes
  31603. if (parsedGeometry.subMeshes) {
  31604. mesh.subMeshes = [];
  31605. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31606. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31607. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31608. }
  31609. }
  31610. // Flat shading
  31611. if (mesh._shouldGenerateFlatShading) {
  31612. mesh.convertToFlatShadedMesh();
  31613. delete mesh._shouldGenerateFlatShading;
  31614. }
  31615. // Update
  31616. mesh.computeWorldMatrix(true);
  31617. // Octree
  31618. if (scene['_selectionOctree']) {
  31619. scene['_selectionOctree'].addMesh(mesh);
  31620. }
  31621. };
  31622. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31623. var epsilon = 1e-3;
  31624. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31625. return;
  31626. }
  31627. var noInfluenceBoneIndex = 0.0;
  31628. if (parsedGeometry.skeletonId > -1) {
  31629. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31630. if (!skeleton) {
  31631. return;
  31632. }
  31633. noInfluenceBoneIndex = skeleton.bones.length;
  31634. }
  31635. else {
  31636. return;
  31637. }
  31638. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31639. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31640. var matricesWeights = parsedGeometry.matricesWeights;
  31641. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31642. var influencers = parsedGeometry.numBoneInfluencer;
  31643. var size = matricesWeights.length;
  31644. for (var i = 0; i < size; i += 4) {
  31645. var weight = 0.0;
  31646. var firstZeroWeight = -1;
  31647. for (var j = 0; j < 4; j++) {
  31648. var w = matricesWeights[i + j];
  31649. weight += w;
  31650. if (w < epsilon && firstZeroWeight < 0) {
  31651. firstZeroWeight = j;
  31652. }
  31653. }
  31654. if (matricesWeightsExtra) {
  31655. for (var j = 0; j < 4; j++) {
  31656. var w = matricesWeightsExtra[i + j];
  31657. weight += w;
  31658. if (w < epsilon && firstZeroWeight < 0) {
  31659. firstZeroWeight = j + 4;
  31660. }
  31661. }
  31662. }
  31663. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31664. firstZeroWeight = influencers - 1;
  31665. }
  31666. if (weight > epsilon) {
  31667. var mweight = 1.0 / weight;
  31668. for (var j = 0; j < 4; j++) {
  31669. matricesWeights[i + j] *= mweight;
  31670. }
  31671. if (matricesWeightsExtra) {
  31672. for (var j = 0; j < 4; j++) {
  31673. matricesWeightsExtra[i + j] *= mweight;
  31674. }
  31675. }
  31676. }
  31677. else {
  31678. if (firstZeroWeight >= 4) {
  31679. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31680. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31681. }
  31682. else {
  31683. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31684. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31685. }
  31686. }
  31687. }
  31688. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31689. if (parsedGeometry.matricesWeightsExtra) {
  31690. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31691. }
  31692. };
  31693. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31694. if (scene.getGeometryByID(parsedVertexData.id)) {
  31695. return null; // null since geometry could be something else than a box...
  31696. }
  31697. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31698. if (BABYLON.Tags) {
  31699. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31700. }
  31701. if (parsedVertexData.delayLoadingFile) {
  31702. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31703. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31704. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31705. geometry._delayInfo = [];
  31706. if (parsedVertexData.hasUVs) {
  31707. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31708. }
  31709. if (parsedVertexData.hasUVs2) {
  31710. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31711. }
  31712. if (parsedVertexData.hasUVs3) {
  31713. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31714. }
  31715. if (parsedVertexData.hasUVs4) {
  31716. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31717. }
  31718. if (parsedVertexData.hasUVs5) {
  31719. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31720. }
  31721. if (parsedVertexData.hasUVs6) {
  31722. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31723. }
  31724. if (parsedVertexData.hasColors) {
  31725. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31726. }
  31727. if (parsedVertexData.hasMatricesIndices) {
  31728. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31729. }
  31730. if (parsedVertexData.hasMatricesWeights) {
  31731. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31732. }
  31733. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31734. }
  31735. else {
  31736. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31737. }
  31738. scene.pushGeometry(geometry, true);
  31739. return geometry;
  31740. };
  31741. return Geometry;
  31742. }());
  31743. BABYLON.Geometry = Geometry;
  31744. /////// Primitives //////////////////////////////////////////////
  31745. (function (Geometry) {
  31746. var Primitives;
  31747. (function (Primitives) {
  31748. /// Abstract class
  31749. var _Primitive = /** @class */ (function (_super) {
  31750. __extends(_Primitive, _super);
  31751. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31752. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31753. if (mesh === void 0) { mesh = null; }
  31754. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31755. _this._canBeRegenerated = _canBeRegenerated;
  31756. _this._beingRegenerated = true;
  31757. _this.regenerate();
  31758. _this._beingRegenerated = false;
  31759. return _this;
  31760. }
  31761. _Primitive.prototype.canBeRegenerated = function () {
  31762. return this._canBeRegenerated;
  31763. };
  31764. _Primitive.prototype.regenerate = function () {
  31765. if (!this._canBeRegenerated) {
  31766. return;
  31767. }
  31768. this._beingRegenerated = true;
  31769. this.setAllVerticesData(this._regenerateVertexData(), false);
  31770. this._beingRegenerated = false;
  31771. };
  31772. _Primitive.prototype.asNewGeometry = function (id) {
  31773. return _super.prototype.copy.call(this, id);
  31774. };
  31775. // overrides
  31776. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31777. if (!this._beingRegenerated) {
  31778. return;
  31779. }
  31780. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31781. };
  31782. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31783. if (!this._beingRegenerated) {
  31784. return;
  31785. }
  31786. _super.prototype.setVerticesData.call(this, kind, data, false);
  31787. };
  31788. // to override
  31789. // protected
  31790. _Primitive.prototype._regenerateVertexData = function () {
  31791. throw new Error("Abstract method");
  31792. };
  31793. _Primitive.prototype.copy = function (id) {
  31794. throw new Error("Must be overriden in sub-classes.");
  31795. };
  31796. _Primitive.prototype.serialize = function () {
  31797. var serializationObject = _super.prototype.serialize.call(this);
  31798. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31799. return serializationObject;
  31800. };
  31801. return _Primitive;
  31802. }(Geometry));
  31803. Primitives._Primitive = _Primitive;
  31804. var Ribbon = /** @class */ (function (_super) {
  31805. __extends(Ribbon, _super);
  31806. // Members
  31807. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31808. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31809. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31810. _this.pathArray = pathArray;
  31811. _this.closeArray = closeArray;
  31812. _this.closePath = closePath;
  31813. _this.offset = offset;
  31814. _this.side = side;
  31815. return _this;
  31816. }
  31817. Ribbon.prototype._regenerateVertexData = function () {
  31818. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31819. };
  31820. Ribbon.prototype.copy = function (id) {
  31821. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31822. };
  31823. return Ribbon;
  31824. }(_Primitive));
  31825. Primitives.Ribbon = Ribbon;
  31826. var Box = /** @class */ (function (_super) {
  31827. __extends(Box, _super);
  31828. // Members
  31829. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31830. if (mesh === void 0) { mesh = null; }
  31831. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31832. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31833. _this.size = size;
  31834. _this.side = side;
  31835. return _this;
  31836. }
  31837. Box.prototype._regenerateVertexData = function () {
  31838. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31839. };
  31840. Box.prototype.copy = function (id) {
  31841. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31842. };
  31843. Box.prototype.serialize = function () {
  31844. var serializationObject = _super.prototype.serialize.call(this);
  31845. serializationObject.size = this.size;
  31846. return serializationObject;
  31847. };
  31848. Box.Parse = function (parsedBox, scene) {
  31849. if (scene.getGeometryByID(parsedBox.id)) {
  31850. return null; // null since geometry could be something else than a box...
  31851. }
  31852. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31853. if (BABYLON.Tags) {
  31854. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31855. }
  31856. scene.pushGeometry(box, true);
  31857. return box;
  31858. };
  31859. return Box;
  31860. }(_Primitive));
  31861. Primitives.Box = Box;
  31862. var Sphere = /** @class */ (function (_super) {
  31863. __extends(Sphere, _super);
  31864. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31865. if (mesh === void 0) { mesh = null; }
  31866. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31867. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31868. _this.segments = segments;
  31869. _this.diameter = diameter;
  31870. _this.side = side;
  31871. return _this;
  31872. }
  31873. Sphere.prototype._regenerateVertexData = function () {
  31874. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31875. };
  31876. Sphere.prototype.copy = function (id) {
  31877. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31878. };
  31879. Sphere.prototype.serialize = function () {
  31880. var serializationObject = _super.prototype.serialize.call(this);
  31881. serializationObject.segments = this.segments;
  31882. serializationObject.diameter = this.diameter;
  31883. return serializationObject;
  31884. };
  31885. Sphere.Parse = function (parsedSphere, scene) {
  31886. if (scene.getGeometryByID(parsedSphere.id)) {
  31887. return null; // null since geometry could be something else than a sphere...
  31888. }
  31889. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31890. if (BABYLON.Tags) {
  31891. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31892. }
  31893. scene.pushGeometry(sphere, true);
  31894. return sphere;
  31895. };
  31896. return Sphere;
  31897. }(_Primitive));
  31898. Primitives.Sphere = Sphere;
  31899. var Disc = /** @class */ (function (_super) {
  31900. __extends(Disc, _super);
  31901. // Members
  31902. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31903. if (mesh === void 0) { mesh = null; }
  31904. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31905. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31906. _this.radius = radius;
  31907. _this.tessellation = tessellation;
  31908. _this.side = side;
  31909. return _this;
  31910. }
  31911. Disc.prototype._regenerateVertexData = function () {
  31912. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31913. };
  31914. Disc.prototype.copy = function (id) {
  31915. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31916. };
  31917. return Disc;
  31918. }(_Primitive));
  31919. Primitives.Disc = Disc;
  31920. var Cylinder = /** @class */ (function (_super) {
  31921. __extends(Cylinder, _super);
  31922. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31923. if (subdivisions === void 0) { subdivisions = 1; }
  31924. if (mesh === void 0) { mesh = null; }
  31925. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31926. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31927. _this.height = height;
  31928. _this.diameterTop = diameterTop;
  31929. _this.diameterBottom = diameterBottom;
  31930. _this.tessellation = tessellation;
  31931. _this.subdivisions = subdivisions;
  31932. _this.side = side;
  31933. return _this;
  31934. }
  31935. Cylinder.prototype._regenerateVertexData = function () {
  31936. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31937. };
  31938. Cylinder.prototype.copy = function (id) {
  31939. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31940. };
  31941. Cylinder.prototype.serialize = function () {
  31942. var serializationObject = _super.prototype.serialize.call(this);
  31943. serializationObject.height = this.height;
  31944. serializationObject.diameterTop = this.diameterTop;
  31945. serializationObject.diameterBottom = this.diameterBottom;
  31946. serializationObject.tessellation = this.tessellation;
  31947. return serializationObject;
  31948. };
  31949. Cylinder.Parse = function (parsedCylinder, scene) {
  31950. if (scene.getGeometryByID(parsedCylinder.id)) {
  31951. return null; // null since geometry could be something else than a cylinder...
  31952. }
  31953. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31954. if (BABYLON.Tags) {
  31955. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31956. }
  31957. scene.pushGeometry(cylinder, true);
  31958. return cylinder;
  31959. };
  31960. return Cylinder;
  31961. }(_Primitive));
  31962. Primitives.Cylinder = Cylinder;
  31963. var Torus = /** @class */ (function (_super) {
  31964. __extends(Torus, _super);
  31965. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31966. if (mesh === void 0) { mesh = null; }
  31967. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31968. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31969. _this.diameter = diameter;
  31970. _this.thickness = thickness;
  31971. _this.tessellation = tessellation;
  31972. _this.side = side;
  31973. return _this;
  31974. }
  31975. Torus.prototype._regenerateVertexData = function () {
  31976. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31977. };
  31978. Torus.prototype.copy = function (id) {
  31979. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31980. };
  31981. Torus.prototype.serialize = function () {
  31982. var serializationObject = _super.prototype.serialize.call(this);
  31983. serializationObject.diameter = this.diameter;
  31984. serializationObject.thickness = this.thickness;
  31985. serializationObject.tessellation = this.tessellation;
  31986. return serializationObject;
  31987. };
  31988. Torus.Parse = function (parsedTorus, scene) {
  31989. if (scene.getGeometryByID(parsedTorus.id)) {
  31990. return null; // null since geometry could be something else than a torus...
  31991. }
  31992. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31993. if (BABYLON.Tags) {
  31994. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31995. }
  31996. scene.pushGeometry(torus, true);
  31997. return torus;
  31998. };
  31999. return Torus;
  32000. }(_Primitive));
  32001. Primitives.Torus = Torus;
  32002. var Ground = /** @class */ (function (_super) {
  32003. __extends(Ground, _super);
  32004. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32005. if (mesh === void 0) { mesh = null; }
  32006. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32007. _this.width = width;
  32008. _this.height = height;
  32009. _this.subdivisions = subdivisions;
  32010. return _this;
  32011. }
  32012. Ground.prototype._regenerateVertexData = function () {
  32013. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32014. };
  32015. Ground.prototype.copy = function (id) {
  32016. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32017. };
  32018. Ground.prototype.serialize = function () {
  32019. var serializationObject = _super.prototype.serialize.call(this);
  32020. serializationObject.width = this.width;
  32021. serializationObject.height = this.height;
  32022. serializationObject.subdivisions = this.subdivisions;
  32023. return serializationObject;
  32024. };
  32025. Ground.Parse = function (parsedGround, scene) {
  32026. if (scene.getGeometryByID(parsedGround.id)) {
  32027. return null; // null since geometry could be something else than a ground...
  32028. }
  32029. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32030. if (BABYLON.Tags) {
  32031. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32032. }
  32033. scene.pushGeometry(ground, true);
  32034. return ground;
  32035. };
  32036. return Ground;
  32037. }(_Primitive));
  32038. Primitives.Ground = Ground;
  32039. var TiledGround = /** @class */ (function (_super) {
  32040. __extends(TiledGround, _super);
  32041. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32042. if (mesh === void 0) { mesh = null; }
  32043. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32044. _this.xmin = xmin;
  32045. _this.zmin = zmin;
  32046. _this.xmax = xmax;
  32047. _this.zmax = zmax;
  32048. _this.subdivisions = subdivisions;
  32049. _this.precision = precision;
  32050. return _this;
  32051. }
  32052. TiledGround.prototype._regenerateVertexData = function () {
  32053. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32054. };
  32055. TiledGround.prototype.copy = function (id) {
  32056. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32057. };
  32058. return TiledGround;
  32059. }(_Primitive));
  32060. Primitives.TiledGround = TiledGround;
  32061. var Plane = /** @class */ (function (_super) {
  32062. __extends(Plane, _super);
  32063. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32064. if (mesh === void 0) { mesh = null; }
  32065. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32066. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32067. _this.size = size;
  32068. _this.side = side;
  32069. return _this;
  32070. }
  32071. Plane.prototype._regenerateVertexData = function () {
  32072. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32073. };
  32074. Plane.prototype.copy = function (id) {
  32075. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32076. };
  32077. Plane.prototype.serialize = function () {
  32078. var serializationObject = _super.prototype.serialize.call(this);
  32079. serializationObject.size = this.size;
  32080. return serializationObject;
  32081. };
  32082. Plane.Parse = function (parsedPlane, scene) {
  32083. if (scene.getGeometryByID(parsedPlane.id)) {
  32084. return null; // null since geometry could be something else than a ground...
  32085. }
  32086. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32087. if (BABYLON.Tags) {
  32088. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32089. }
  32090. scene.pushGeometry(plane, true);
  32091. return plane;
  32092. };
  32093. return Plane;
  32094. }(_Primitive));
  32095. Primitives.Plane = Plane;
  32096. var TorusKnot = /** @class */ (function (_super) {
  32097. __extends(TorusKnot, _super);
  32098. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32099. if (mesh === void 0) { mesh = null; }
  32100. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32101. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32102. _this.radius = radius;
  32103. _this.tube = tube;
  32104. _this.radialSegments = radialSegments;
  32105. _this.tubularSegments = tubularSegments;
  32106. _this.p = p;
  32107. _this.q = q;
  32108. _this.side = side;
  32109. return _this;
  32110. }
  32111. TorusKnot.prototype._regenerateVertexData = function () {
  32112. 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 });
  32113. };
  32114. TorusKnot.prototype.copy = function (id) {
  32115. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32116. };
  32117. TorusKnot.prototype.serialize = function () {
  32118. var serializationObject = _super.prototype.serialize.call(this);
  32119. serializationObject.radius = this.radius;
  32120. serializationObject.tube = this.tube;
  32121. serializationObject.radialSegments = this.radialSegments;
  32122. serializationObject.tubularSegments = this.tubularSegments;
  32123. serializationObject.p = this.p;
  32124. serializationObject.q = this.q;
  32125. return serializationObject;
  32126. };
  32127. ;
  32128. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32129. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32130. return null; // null since geometry could be something else than a ground...
  32131. }
  32132. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32133. if (BABYLON.Tags) {
  32134. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32135. }
  32136. scene.pushGeometry(torusKnot, true);
  32137. return torusKnot;
  32138. };
  32139. return TorusKnot;
  32140. }(_Primitive));
  32141. Primitives.TorusKnot = TorusKnot;
  32142. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32143. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32144. })(BABYLON || (BABYLON = {}));
  32145. //# sourceMappingURL=babylon.geometry.js.map
  32146. var BABYLON;
  32147. (function (BABYLON) {
  32148. var PostProcessManager = /** @class */ (function () {
  32149. function PostProcessManager(scene) {
  32150. this._vertexBuffers = {};
  32151. this._scene = scene;
  32152. }
  32153. PostProcessManager.prototype._prepareBuffers = function () {
  32154. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32155. return;
  32156. }
  32157. // VBO
  32158. var vertices = [];
  32159. vertices.push(1, 1);
  32160. vertices.push(-1, 1);
  32161. vertices.push(-1, -1);
  32162. vertices.push(1, -1);
  32163. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32164. this._buildIndexBuffer();
  32165. };
  32166. PostProcessManager.prototype._buildIndexBuffer = function () {
  32167. // Indices
  32168. var indices = [];
  32169. indices.push(0);
  32170. indices.push(1);
  32171. indices.push(2);
  32172. indices.push(0);
  32173. indices.push(2);
  32174. indices.push(3);
  32175. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32176. };
  32177. PostProcessManager.prototype._rebuild = function () {
  32178. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32179. if (!vb) {
  32180. return;
  32181. }
  32182. vb._rebuild();
  32183. this._buildIndexBuffer();
  32184. };
  32185. // Methods
  32186. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32187. if (sourceTexture === void 0) { sourceTexture = null; }
  32188. if (postProcesses === void 0) { postProcesses = null; }
  32189. var camera = this._scene.activeCamera;
  32190. if (!camera) {
  32191. return false;
  32192. }
  32193. var postProcesses = postProcesses || camera._postProcesses;
  32194. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32195. return false;
  32196. }
  32197. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32198. return true;
  32199. };
  32200. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32201. if (targetTexture === void 0) { targetTexture = null; }
  32202. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32203. if (!this._scene.activeCamera) {
  32204. return;
  32205. }
  32206. var engine = this._scene.getEngine();
  32207. for (var index = 0; index < postProcesses.length; index++) {
  32208. if (index < postProcesses.length - 1) {
  32209. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32210. }
  32211. else {
  32212. if (targetTexture) {
  32213. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32214. }
  32215. else {
  32216. engine.restoreDefaultFramebuffer();
  32217. }
  32218. }
  32219. var pp = postProcesses[index];
  32220. var effect = pp.apply();
  32221. if (effect) {
  32222. pp.onBeforeRenderObservable.notifyObservers(effect);
  32223. // VBOs
  32224. this._prepareBuffers();
  32225. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32226. // Draw order
  32227. engine.draw(true, 0, 6);
  32228. pp.onAfterRenderObservable.notifyObservers(effect);
  32229. }
  32230. }
  32231. // Restore depth buffer
  32232. engine.setDepthBuffer(true);
  32233. engine.setDepthWrite(true);
  32234. };
  32235. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32236. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32237. var camera = this._scene.activeCamera;
  32238. if (!camera) {
  32239. return;
  32240. }
  32241. postProcesses = postProcesses || camera._postProcesses;
  32242. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32243. return;
  32244. }
  32245. var engine = this._scene.getEngine();
  32246. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32247. if (index < len - 1) {
  32248. postProcesses[index + 1].activate(camera, targetTexture);
  32249. }
  32250. else {
  32251. if (targetTexture) {
  32252. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32253. }
  32254. else {
  32255. engine.restoreDefaultFramebuffer();
  32256. }
  32257. }
  32258. if (doNotPresent) {
  32259. break;
  32260. }
  32261. var pp = postProcesses[index];
  32262. var effect = pp.apply();
  32263. if (effect) {
  32264. pp.onBeforeRenderObservable.notifyObservers(effect);
  32265. // VBOs
  32266. this._prepareBuffers();
  32267. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32268. // Draw order
  32269. engine.draw(true, 0, 6);
  32270. pp.onAfterRenderObservable.notifyObservers(effect);
  32271. }
  32272. }
  32273. // Restore states
  32274. engine.setDepthBuffer(true);
  32275. engine.setDepthWrite(true);
  32276. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32277. };
  32278. PostProcessManager.prototype.dispose = function () {
  32279. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32280. if (buffer) {
  32281. buffer.dispose();
  32282. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32283. }
  32284. if (this._indexBuffer) {
  32285. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32286. this._indexBuffer = null;
  32287. }
  32288. };
  32289. return PostProcessManager;
  32290. }());
  32291. BABYLON.PostProcessManager = PostProcessManager;
  32292. })(BABYLON || (BABYLON = {}));
  32293. //# sourceMappingURL=babylon.postProcessManager.js.map
  32294. var BABYLON;
  32295. (function (BABYLON) {
  32296. /**
  32297. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32298. */
  32299. var PerformanceMonitor = /** @class */ (function () {
  32300. /**
  32301. * constructor
  32302. * @param frameSampleSize The number of samples required to saturate the sliding window
  32303. */
  32304. function PerformanceMonitor(frameSampleSize) {
  32305. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32306. this._enabled = true;
  32307. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32308. }
  32309. /**
  32310. * Samples current frame
  32311. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32312. */
  32313. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32314. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32315. if (!this._enabled)
  32316. return;
  32317. if (this._lastFrameTimeMs != null) {
  32318. var dt = timeMs - this._lastFrameTimeMs;
  32319. this._rollingFrameTime.add(dt);
  32320. }
  32321. this._lastFrameTimeMs = timeMs;
  32322. };
  32323. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32324. /**
  32325. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32326. * @return Average frame time in milliseconds
  32327. */
  32328. get: function () {
  32329. return this._rollingFrameTime.average;
  32330. },
  32331. enumerable: true,
  32332. configurable: true
  32333. });
  32334. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32335. /**
  32336. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32337. * @return Frame time variance in milliseconds squared
  32338. */
  32339. get: function () {
  32340. return this._rollingFrameTime.variance;
  32341. },
  32342. enumerable: true,
  32343. configurable: true
  32344. });
  32345. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32346. /**
  32347. * Returns the frame time of the most recent frame
  32348. * @return Frame time in milliseconds
  32349. */
  32350. get: function () {
  32351. return this._rollingFrameTime.history(0);
  32352. },
  32353. enumerable: true,
  32354. configurable: true
  32355. });
  32356. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32357. /**
  32358. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32359. * @return Framerate in frames per second
  32360. */
  32361. get: function () {
  32362. return 1000.0 / this._rollingFrameTime.average;
  32363. },
  32364. enumerable: true,
  32365. configurable: true
  32366. });
  32367. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32368. /**
  32369. * Returns the average framerate in frames per second using the most recent frame time
  32370. * @return Framerate in frames per second
  32371. */
  32372. get: function () {
  32373. var history = this._rollingFrameTime.history(0);
  32374. if (history === 0) {
  32375. return 0;
  32376. }
  32377. return 1000.0 / history;
  32378. },
  32379. enumerable: true,
  32380. configurable: true
  32381. });
  32382. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32383. /**
  32384. * Returns true if enough samples have been taken to completely fill the sliding window
  32385. * @return true if saturated
  32386. */
  32387. get: function () {
  32388. return this._rollingFrameTime.isSaturated();
  32389. },
  32390. enumerable: true,
  32391. configurable: true
  32392. });
  32393. /**
  32394. * Enables contributions to the sliding window sample set
  32395. */
  32396. PerformanceMonitor.prototype.enable = function () {
  32397. this._enabled = true;
  32398. };
  32399. /**
  32400. * Disables contributions to the sliding window sample set
  32401. * Samples will not be interpolated over the disabled period
  32402. */
  32403. PerformanceMonitor.prototype.disable = function () {
  32404. this._enabled = false;
  32405. //clear last sample to avoid interpolating over the disabled period when next enabled
  32406. this._lastFrameTimeMs = null;
  32407. this._lastChangeTimeMs = null;
  32408. };
  32409. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32410. /**
  32411. * Returns true if sampling is enabled
  32412. * @return true if enabled
  32413. */
  32414. get: function () {
  32415. return this._enabled;
  32416. },
  32417. enumerable: true,
  32418. configurable: true
  32419. });
  32420. /**
  32421. * Resets performance monitor
  32422. */
  32423. PerformanceMonitor.prototype.reset = function () {
  32424. //clear last sample to avoid interpolating over the disabled period when next enabled
  32425. this._lastFrameTimeMs = null;
  32426. this._lastChangeTimeMs = null;
  32427. //wipe record
  32428. this._rollingFrameTime.reset();
  32429. };
  32430. return PerformanceMonitor;
  32431. }());
  32432. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32433. /**
  32434. * RollingAverage
  32435. *
  32436. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32437. */
  32438. var RollingAverage = /** @class */ (function () {
  32439. /**
  32440. * constructor
  32441. * @param length The number of samples required to saturate the sliding window
  32442. */
  32443. function RollingAverage(length) {
  32444. this._samples = new Array(length);
  32445. this.reset();
  32446. }
  32447. /**
  32448. * Adds a sample to the sample set
  32449. * @param v The sample value
  32450. */
  32451. RollingAverage.prototype.add = function (v) {
  32452. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32453. var delta;
  32454. //we need to check if we've already wrapped round
  32455. if (this.isSaturated()) {
  32456. //remove bottom of stack from mean
  32457. var bottomValue = this._samples[this._pos];
  32458. delta = bottomValue - this.average;
  32459. this.average -= delta / (this._sampleCount - 1);
  32460. this._m2 -= delta * (bottomValue - this.average);
  32461. }
  32462. else {
  32463. this._sampleCount++;
  32464. }
  32465. //add new value to mean
  32466. delta = v - this.average;
  32467. this.average += delta / (this._sampleCount);
  32468. this._m2 += delta * (v - this.average);
  32469. //set the new variance
  32470. this.variance = this._m2 / (this._sampleCount - 1);
  32471. this._samples[this._pos] = v;
  32472. this._pos++;
  32473. this._pos %= this._samples.length; //positive wrap around
  32474. };
  32475. /**
  32476. * Returns previously added values or null if outside of history or outside the sliding window domain
  32477. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32478. * @return Value previously recorded with add() or null if outside of range
  32479. */
  32480. RollingAverage.prototype.history = function (i) {
  32481. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32482. return 0;
  32483. }
  32484. var i0 = this._wrapPosition(this._pos - 1.0);
  32485. return this._samples[this._wrapPosition(i0 - i)];
  32486. };
  32487. /**
  32488. * Returns true if enough samples have been taken to completely fill the sliding window
  32489. * @return true if sample-set saturated
  32490. */
  32491. RollingAverage.prototype.isSaturated = function () {
  32492. return this._sampleCount >= this._samples.length;
  32493. };
  32494. /**
  32495. * Resets the rolling average (equivalent to 0 samples taken so far)
  32496. */
  32497. RollingAverage.prototype.reset = function () {
  32498. this.average = 0;
  32499. this.variance = 0;
  32500. this._sampleCount = 0;
  32501. this._pos = 0;
  32502. this._m2 = 0;
  32503. };
  32504. /**
  32505. * Wraps a value around the sample range boundaries
  32506. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32507. * @return Wrapped position in sample range
  32508. */
  32509. RollingAverage.prototype._wrapPosition = function (i) {
  32510. var max = this._samples.length;
  32511. return ((i % max) + max) % max;
  32512. };
  32513. return RollingAverage;
  32514. }());
  32515. BABYLON.RollingAverage = RollingAverage;
  32516. })(BABYLON || (BABYLON = {}));
  32517. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32518. var BABYLON;
  32519. (function (BABYLON) {
  32520. /**
  32521. * This groups together the common properties used for image processing either in direct forward pass
  32522. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32523. * or not.
  32524. */
  32525. var ImageProcessingConfiguration = /** @class */ (function () {
  32526. function ImageProcessingConfiguration() {
  32527. /**
  32528. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32529. */
  32530. this.colorCurves = new BABYLON.ColorCurves();
  32531. this._colorCurvesEnabled = false;
  32532. this._colorGradingEnabled = false;
  32533. this._colorGradingWithGreenDepth = true;
  32534. this._colorGradingBGR = true;
  32535. this._exposure = 1.0;
  32536. this._toneMappingEnabled = false;
  32537. this._contrast = 1.0;
  32538. /**
  32539. * Vignette stretch size.
  32540. */
  32541. this.vignetteStretch = 0;
  32542. /**
  32543. * Vignette centre X Offset.
  32544. */
  32545. this.vignetteCentreX = 0;
  32546. /**
  32547. * Vignette centre Y Offset.
  32548. */
  32549. this.vignetteCentreY = 0;
  32550. /**
  32551. * Vignette weight or intensity of the vignette effect.
  32552. */
  32553. this.vignetteWeight = 1.5;
  32554. /**
  32555. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32556. * if vignetteEnabled is set to true.
  32557. */
  32558. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32559. /**
  32560. * Camera field of view used by the Vignette effect.
  32561. */
  32562. this.vignetteCameraFov = 0.5;
  32563. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32564. this._vignetteEnabled = false;
  32565. this._applyByPostProcess = false;
  32566. /**
  32567. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32568. * @type {BABYLON.Observable}
  32569. */
  32570. this.onUpdateParameters = new BABYLON.Observable();
  32571. }
  32572. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32573. /**
  32574. * Gets wether the color curves effect is enabled.
  32575. */
  32576. get: function () {
  32577. return this._colorCurvesEnabled;
  32578. },
  32579. /**
  32580. * Sets wether the color curves effect is enabled.
  32581. */
  32582. set: function (value) {
  32583. if (this._colorCurvesEnabled === value) {
  32584. return;
  32585. }
  32586. this._colorCurvesEnabled = value;
  32587. this._updateParameters();
  32588. },
  32589. enumerable: true,
  32590. configurable: true
  32591. });
  32592. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32593. /**
  32594. * Gets wether the color grading effect is enabled.
  32595. */
  32596. get: function () {
  32597. return this._colorGradingEnabled;
  32598. },
  32599. /**
  32600. * Sets wether the color grading effect is enabled.
  32601. */
  32602. set: function (value) {
  32603. if (this._colorGradingEnabled === value) {
  32604. return;
  32605. }
  32606. this._colorGradingEnabled = value;
  32607. this._updateParameters();
  32608. },
  32609. enumerable: true,
  32610. configurable: true
  32611. });
  32612. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32613. /**
  32614. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32615. */
  32616. get: function () {
  32617. return this._colorGradingWithGreenDepth;
  32618. },
  32619. /**
  32620. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32621. */
  32622. set: function (value) {
  32623. if (this._colorGradingWithGreenDepth === value) {
  32624. return;
  32625. }
  32626. this._colorGradingWithGreenDepth = value;
  32627. this._updateParameters();
  32628. },
  32629. enumerable: true,
  32630. configurable: true
  32631. });
  32632. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32633. /**
  32634. * Gets wether the color grading texture contains BGR values.
  32635. */
  32636. get: function () {
  32637. return this._colorGradingBGR;
  32638. },
  32639. /**
  32640. * Sets wether the color grading texture contains BGR values.
  32641. */
  32642. set: function (value) {
  32643. if (this._colorGradingBGR === value) {
  32644. return;
  32645. }
  32646. this._colorGradingBGR = value;
  32647. this._updateParameters();
  32648. },
  32649. enumerable: true,
  32650. configurable: true
  32651. });
  32652. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32653. /**
  32654. * Gets the Exposure used in the effect.
  32655. */
  32656. get: function () {
  32657. return this._exposure;
  32658. },
  32659. /**
  32660. * Sets the Exposure used in the effect.
  32661. */
  32662. set: function (value) {
  32663. if (this._exposure === value) {
  32664. return;
  32665. }
  32666. this._exposure = value;
  32667. this._updateParameters();
  32668. },
  32669. enumerable: true,
  32670. configurable: true
  32671. });
  32672. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32673. /**
  32674. * Gets wether the tone mapping effect is enabled.
  32675. */
  32676. get: function () {
  32677. return this._toneMappingEnabled;
  32678. },
  32679. /**
  32680. * Sets wether the tone mapping effect is enabled.
  32681. */
  32682. set: function (value) {
  32683. if (this._toneMappingEnabled === value) {
  32684. return;
  32685. }
  32686. this._toneMappingEnabled = value;
  32687. this._updateParameters();
  32688. },
  32689. enumerable: true,
  32690. configurable: true
  32691. });
  32692. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32693. /**
  32694. * Gets the contrast used in the effect.
  32695. */
  32696. get: function () {
  32697. return this._contrast;
  32698. },
  32699. /**
  32700. * Sets the contrast used in the effect.
  32701. */
  32702. set: function (value) {
  32703. if (this._contrast === value) {
  32704. return;
  32705. }
  32706. this._contrast = value;
  32707. this._updateParameters();
  32708. },
  32709. enumerable: true,
  32710. configurable: true
  32711. });
  32712. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32713. /**
  32714. * Gets the vignette blend mode allowing different kind of effect.
  32715. */
  32716. get: function () {
  32717. return this._vignetteBlendMode;
  32718. },
  32719. /**
  32720. * Sets the vignette blend mode allowing different kind of effect.
  32721. */
  32722. set: function (value) {
  32723. if (this._vignetteBlendMode === value) {
  32724. return;
  32725. }
  32726. this._vignetteBlendMode = value;
  32727. this._updateParameters();
  32728. },
  32729. enumerable: true,
  32730. configurable: true
  32731. });
  32732. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32733. /**
  32734. * Gets wether the vignette effect is enabled.
  32735. */
  32736. get: function () {
  32737. return this._vignetteEnabled;
  32738. },
  32739. /**
  32740. * Sets wether the vignette effect is enabled.
  32741. */
  32742. set: function (value) {
  32743. if (this._vignetteEnabled === value) {
  32744. return;
  32745. }
  32746. this._vignetteEnabled = value;
  32747. this._updateParameters();
  32748. },
  32749. enumerable: true,
  32750. configurable: true
  32751. });
  32752. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32753. /**
  32754. * Gets wether the image processing is applied through a post process or not.
  32755. */
  32756. get: function () {
  32757. return this._applyByPostProcess;
  32758. },
  32759. /**
  32760. * Sets wether the image processing is applied through a post process or not.
  32761. */
  32762. set: function (value) {
  32763. if (this._applyByPostProcess === value) {
  32764. return;
  32765. }
  32766. this._applyByPostProcess = value;
  32767. this._updateParameters();
  32768. },
  32769. enumerable: true,
  32770. configurable: true
  32771. });
  32772. /**
  32773. * Method called each time the image processing information changes requires to recompile the effect.
  32774. */
  32775. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32776. this.onUpdateParameters.notifyObservers(this);
  32777. };
  32778. ImageProcessingConfiguration.prototype.getClassName = function () {
  32779. return "ImageProcessingConfiguration";
  32780. };
  32781. /**
  32782. * Prepare the list of uniforms associated with the Image Processing effects.
  32783. * @param uniformsList The list of uniforms used in the effect
  32784. * @param defines the list of defines currently in use
  32785. */
  32786. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32787. if (defines.EXPOSURE) {
  32788. uniforms.push("exposureLinear");
  32789. }
  32790. if (defines.CONTRAST) {
  32791. uniforms.push("contrast");
  32792. }
  32793. if (defines.COLORGRADING) {
  32794. uniforms.push("colorTransformSettings");
  32795. }
  32796. if (defines.VIGNETTE) {
  32797. uniforms.push("vInverseScreenSize");
  32798. uniforms.push("vignetteSettings1");
  32799. uniforms.push("vignetteSettings2");
  32800. }
  32801. if (defines.COLORCURVES) {
  32802. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32803. }
  32804. };
  32805. /**
  32806. * Prepare the list of samplers associated with the Image Processing effects.
  32807. * @param uniformsList The list of uniforms used in the effect
  32808. * @param defines the list of defines currently in use
  32809. */
  32810. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32811. if (defines.COLORGRADING) {
  32812. samplersList.push("txColorTransform");
  32813. }
  32814. };
  32815. /**
  32816. * Prepare the list of defines associated to the shader.
  32817. * @param defines the list of defines to complete
  32818. */
  32819. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32820. if (forPostProcess === void 0) { forPostProcess = false; }
  32821. if (forPostProcess !== this.applyByPostProcess) {
  32822. defines.VIGNETTE = false;
  32823. defines.TONEMAPPING = false;
  32824. defines.CONTRAST = false;
  32825. defines.EXPOSURE = false;
  32826. defines.COLORCURVES = false;
  32827. defines.COLORGRADING = false;
  32828. defines.COLORGRADING3D = false;
  32829. defines.IMAGEPROCESSING = false;
  32830. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32831. return;
  32832. }
  32833. defines.VIGNETTE = this.vignetteEnabled;
  32834. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32835. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32836. defines.TONEMAPPING = this.toneMappingEnabled;
  32837. defines.CONTRAST = (this.contrast !== 1.0);
  32838. defines.EXPOSURE = (this.exposure !== 1.0);
  32839. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32840. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32841. if (defines.COLORGRADING) {
  32842. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32843. }
  32844. else {
  32845. defines.COLORGRADING3D = false;
  32846. }
  32847. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32848. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32849. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32850. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32851. };
  32852. /**
  32853. * Returns true if all the image processing information are ready.
  32854. */
  32855. ImageProcessingConfiguration.prototype.isReady = function () {
  32856. // Color Grading texure can not be none blocking.
  32857. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32858. };
  32859. /**
  32860. * Binds the image processing to the shader.
  32861. * @param effect The effect to bind to
  32862. */
  32863. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32864. if (aspectRatio === void 0) { aspectRatio = 1; }
  32865. // Color Curves
  32866. if (this._colorCurvesEnabled && this.colorCurves) {
  32867. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32868. }
  32869. // Vignette
  32870. if (this._vignetteEnabled) {
  32871. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32872. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32873. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32874. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32875. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32876. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32877. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32878. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32879. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32880. var vignettePower = -2.0 * this.vignetteWeight;
  32881. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32882. }
  32883. // Exposure
  32884. effect.setFloat("exposureLinear", this.exposure);
  32885. // Contrast
  32886. effect.setFloat("contrast", this.contrast);
  32887. // Color transform settings
  32888. if (this.colorGradingTexture) {
  32889. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32890. var textureSize = this.colorGradingTexture.getSize().height;
  32891. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32892. 0.5 / textureSize, // textureOffset
  32893. textureSize, // textureSize
  32894. this.colorGradingTexture.level // weight
  32895. );
  32896. }
  32897. };
  32898. /**
  32899. * Clones the current image processing instance.
  32900. * @return The cloned image processing
  32901. */
  32902. ImageProcessingConfiguration.prototype.clone = function () {
  32903. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32904. };
  32905. /**
  32906. * Serializes the current image processing instance to a json representation.
  32907. * @return a JSON representation
  32908. */
  32909. ImageProcessingConfiguration.prototype.serialize = function () {
  32910. return BABYLON.SerializationHelper.Serialize(this);
  32911. };
  32912. /**
  32913. * Parses the image processing from a json representation.
  32914. * @param source the JSON source to parse
  32915. * @return The parsed image processing
  32916. */
  32917. ImageProcessingConfiguration.Parse = function (source) {
  32918. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32919. };
  32920. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32921. /**
  32922. * Used to apply the vignette as a mix with the pixel color.
  32923. */
  32924. get: function () {
  32925. return this._VIGNETTEMODE_MULTIPLY;
  32926. },
  32927. enumerable: true,
  32928. configurable: true
  32929. });
  32930. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32931. /**
  32932. * Used to apply the vignette as a replacement of the pixel color.
  32933. */
  32934. get: function () {
  32935. return this._VIGNETTEMODE_OPAQUE;
  32936. },
  32937. enumerable: true,
  32938. configurable: true
  32939. });
  32940. // Static constants associated to the image processing.
  32941. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32942. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32943. __decorate([
  32944. BABYLON.serializeAsColorCurves()
  32945. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32946. __decorate([
  32947. BABYLON.serialize()
  32948. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  32949. __decorate([
  32950. BABYLON.serializeAsTexture()
  32951. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  32952. __decorate([
  32953. BABYLON.serialize()
  32954. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  32955. __decorate([
  32956. BABYLON.serialize()
  32957. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  32958. __decorate([
  32959. BABYLON.serialize()
  32960. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  32961. __decorate([
  32962. BABYLON.serialize()
  32963. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  32964. __decorate([
  32965. BABYLON.serialize()
  32966. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  32967. __decorate([
  32968. BABYLON.serialize()
  32969. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  32970. __decorate([
  32971. BABYLON.serialize()
  32972. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  32973. __decorate([
  32974. BABYLON.serialize()
  32975. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  32976. __decorate([
  32977. BABYLON.serialize()
  32978. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  32979. __decorate([
  32980. BABYLON.serialize()
  32981. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  32982. __decorate([
  32983. BABYLON.serializeAsColor4()
  32984. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  32985. __decorate([
  32986. BABYLON.serialize()
  32987. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  32988. __decorate([
  32989. BABYLON.serialize()
  32990. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  32991. __decorate([
  32992. BABYLON.serialize()
  32993. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  32994. __decorate([
  32995. BABYLON.serialize()
  32996. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  32997. return ImageProcessingConfiguration;
  32998. }());
  32999. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33000. })(BABYLON || (BABYLON = {}));
  33001. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33002. var BABYLON;
  33003. (function (BABYLON) {
  33004. /**
  33005. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33006. * It can help converting any input color in a desired output one. This can then be used to create effects
  33007. * from sepia, black and white to sixties or futuristic rendering...
  33008. *
  33009. * The only supported format is currently 3dl.
  33010. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33011. */
  33012. var ColorGradingTexture = /** @class */ (function (_super) {
  33013. __extends(ColorGradingTexture, _super);
  33014. /**
  33015. * Instantiates a ColorGradingTexture from the following parameters.
  33016. *
  33017. * @param url The location of the color gradind data (currently only supporting 3dl)
  33018. * @param scene The scene the texture will be used in
  33019. */
  33020. function ColorGradingTexture(url, scene) {
  33021. var _this = _super.call(this, scene) || this;
  33022. if (!url) {
  33023. return _this;
  33024. }
  33025. _this._engine = scene.getEngine();
  33026. _this._textureMatrix = BABYLON.Matrix.Identity();
  33027. _this.name = url;
  33028. _this.url = url;
  33029. _this.hasAlpha = false;
  33030. _this.isCube = false;
  33031. _this.is3D = _this._engine.webGLVersion > 1;
  33032. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33033. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33034. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33035. _this.anisotropicFilteringLevel = 1;
  33036. _this._texture = _this._getFromCache(url, true);
  33037. if (!_this._texture) {
  33038. if (!scene.useDelayedTextureLoading) {
  33039. _this.loadTexture();
  33040. }
  33041. else {
  33042. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33043. }
  33044. }
  33045. return _this;
  33046. }
  33047. /**
  33048. * Returns the texture matrix used in most of the material.
  33049. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33050. */
  33051. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33052. return this._textureMatrix;
  33053. };
  33054. /**
  33055. * Occurs when the file being loaded is a .3dl LUT file.
  33056. */
  33057. ColorGradingTexture.prototype.load3dlTexture = function () {
  33058. var engine = this._engine;
  33059. var texture;
  33060. if (engine.webGLVersion === 1) {
  33061. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33062. }
  33063. else {
  33064. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33065. }
  33066. this._texture = texture;
  33067. var callback = function (text) {
  33068. var data = null;
  33069. var tempData = null;
  33070. var line;
  33071. var lines = text.split('\n');
  33072. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33073. var maxColor = 0;
  33074. for (var i = 0; i < lines.length; i++) {
  33075. line = lines[i];
  33076. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33077. continue;
  33078. if (line.indexOf('#') === 0)
  33079. continue;
  33080. var words = line.split(" ");
  33081. if (size === 0) {
  33082. // Number of space + one
  33083. size = words.length;
  33084. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33085. tempData = new Float32Array(size * size * size * 4);
  33086. continue;
  33087. }
  33088. if (size != 0) {
  33089. var r = Math.max(parseInt(words[0]), 0);
  33090. var g = Math.max(parseInt(words[1]), 0);
  33091. var b = Math.max(parseInt(words[2]), 0);
  33092. maxColor = Math.max(r, maxColor);
  33093. maxColor = Math.max(g, maxColor);
  33094. maxColor = Math.max(b, maxColor);
  33095. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33096. if (tempData) {
  33097. tempData[pixelStorageIndex + 0] = r;
  33098. tempData[pixelStorageIndex + 1] = g;
  33099. tempData[pixelStorageIndex + 2] = b;
  33100. }
  33101. pixelIndexSlice++;
  33102. if (pixelIndexSlice % size == 0) {
  33103. pixelIndexH++;
  33104. pixelIndexSlice = 0;
  33105. if (pixelIndexH % size == 0) {
  33106. pixelIndexW++;
  33107. pixelIndexH = 0;
  33108. }
  33109. }
  33110. }
  33111. }
  33112. if (tempData && data) {
  33113. for (var i = 0; i < tempData.length; i++) {
  33114. if (i > 0 && (i + 1) % 4 === 0) {
  33115. data[i] = 255;
  33116. }
  33117. else {
  33118. var value = tempData[i];
  33119. data[i] = (value / maxColor * 255);
  33120. }
  33121. }
  33122. }
  33123. if (texture.is3D) {
  33124. texture.updateSize(size, size, size);
  33125. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33126. }
  33127. else {
  33128. texture.updateSize(size * size, size);
  33129. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33130. }
  33131. };
  33132. BABYLON.Tools.LoadFile(this.url, callback);
  33133. return this._texture;
  33134. };
  33135. /**
  33136. * Starts the loading process of the texture.
  33137. */
  33138. ColorGradingTexture.prototype.loadTexture = function () {
  33139. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33140. this.load3dlTexture();
  33141. }
  33142. };
  33143. /**
  33144. * Clones the color gradind texture.
  33145. */
  33146. ColorGradingTexture.prototype.clone = function () {
  33147. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33148. // Base texture
  33149. newTexture.level = this.level;
  33150. return newTexture;
  33151. };
  33152. /**
  33153. * Called during delayed load for textures.
  33154. */
  33155. ColorGradingTexture.prototype.delayLoad = function () {
  33156. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33157. return;
  33158. }
  33159. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33160. this._texture = this._getFromCache(this.url, true);
  33161. if (!this._texture) {
  33162. this.loadTexture();
  33163. }
  33164. };
  33165. /**
  33166. * Parses a color grading texture serialized by Babylon.
  33167. * @param parsedTexture The texture information being parsedTexture
  33168. * @param scene The scene to load the texture in
  33169. * @param rootUrl The root url of the data assets to load
  33170. * @return A color gradind texture
  33171. */
  33172. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33173. var texture = null;
  33174. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33175. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  33176. texture.name = parsedTexture.name;
  33177. texture.level = parsedTexture.level;
  33178. }
  33179. return texture;
  33180. };
  33181. /**
  33182. * Serializes the LUT texture to json format.
  33183. */
  33184. ColorGradingTexture.prototype.serialize = function () {
  33185. if (!this.name) {
  33186. return null;
  33187. }
  33188. var serializationObject = {};
  33189. serializationObject.name = this.name;
  33190. serializationObject.level = this.level;
  33191. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33192. return serializationObject;
  33193. };
  33194. /**
  33195. * Empty line regex stored for GC.
  33196. */
  33197. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33198. return ColorGradingTexture;
  33199. }(BABYLON.BaseTexture));
  33200. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33201. })(BABYLON || (BABYLON = {}));
  33202. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33203. var BABYLON;
  33204. (function (BABYLON) {
  33205. /**
  33206. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33207. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33208. * 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;
  33209. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33210. */
  33211. var ColorCurves = /** @class */ (function () {
  33212. function ColorCurves() {
  33213. this._dirty = true;
  33214. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33215. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33216. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33217. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33218. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33219. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33220. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33221. this._globalHue = 30;
  33222. this._globalDensity = 0;
  33223. this._globalSaturation = 0;
  33224. this._globalExposure = 0;
  33225. this._highlightsHue = 30;
  33226. this._highlightsDensity = 0;
  33227. this._highlightsSaturation = 0;
  33228. this._highlightsExposure = 0;
  33229. this._midtonesHue = 30;
  33230. this._midtonesDensity = 0;
  33231. this._midtonesSaturation = 0;
  33232. this._midtonesExposure = 0;
  33233. this._shadowsHue = 30;
  33234. this._shadowsDensity = 0;
  33235. this._shadowsSaturation = 0;
  33236. this._shadowsExposure = 0;
  33237. }
  33238. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33239. /**
  33240. * Gets the global Hue value.
  33241. * 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).
  33242. */
  33243. get: function () {
  33244. return this._globalHue;
  33245. },
  33246. /**
  33247. * Sets the global Hue value.
  33248. * 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).
  33249. */
  33250. set: function (value) {
  33251. this._globalHue = value;
  33252. this._dirty = true;
  33253. },
  33254. enumerable: true,
  33255. configurable: true
  33256. });
  33257. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33258. /**
  33259. * Gets the global Density value.
  33260. * 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.
  33261. * Values less than zero provide a filter of opposite hue.
  33262. */
  33263. get: function () {
  33264. return this._globalDensity;
  33265. },
  33266. /**
  33267. * Sets the global Density value.
  33268. * 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.
  33269. * Values less than zero provide a filter of opposite hue.
  33270. */
  33271. set: function (value) {
  33272. this._globalDensity = value;
  33273. this._dirty = true;
  33274. },
  33275. enumerable: true,
  33276. configurable: true
  33277. });
  33278. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33279. /**
  33280. * Gets the global Saturation value.
  33281. * 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.
  33282. */
  33283. get: function () {
  33284. return this._globalSaturation;
  33285. },
  33286. /**
  33287. * Sets the global Saturation value.
  33288. * 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.
  33289. */
  33290. set: function (value) {
  33291. this._globalSaturation = value;
  33292. this._dirty = true;
  33293. },
  33294. enumerable: true,
  33295. configurable: true
  33296. });
  33297. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33298. /**
  33299. * Gets the highlights Hue value.
  33300. * 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).
  33301. */
  33302. get: function () {
  33303. return this._highlightsHue;
  33304. },
  33305. /**
  33306. * Sets the highlights Hue value.
  33307. * 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).
  33308. */
  33309. set: function (value) {
  33310. this._highlightsHue = value;
  33311. this._dirty = true;
  33312. },
  33313. enumerable: true,
  33314. configurable: true
  33315. });
  33316. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33317. /**
  33318. * Gets the highlights Density value.
  33319. * 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.
  33320. * Values less than zero provide a filter of opposite hue.
  33321. */
  33322. get: function () {
  33323. return this._highlightsDensity;
  33324. },
  33325. /**
  33326. * Sets the highlights Density value.
  33327. * 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.
  33328. * Values less than zero provide a filter of opposite hue.
  33329. */
  33330. set: function (value) {
  33331. this._highlightsDensity = value;
  33332. this._dirty = true;
  33333. },
  33334. enumerable: true,
  33335. configurable: true
  33336. });
  33337. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33338. /**
  33339. * Gets the highlights Saturation value.
  33340. * 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.
  33341. */
  33342. get: function () {
  33343. return this._highlightsSaturation;
  33344. },
  33345. /**
  33346. * Sets the highlights Saturation value.
  33347. * 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.
  33348. */
  33349. set: function (value) {
  33350. this._highlightsSaturation = value;
  33351. this._dirty = true;
  33352. },
  33353. enumerable: true,
  33354. configurable: true
  33355. });
  33356. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33357. /**
  33358. * Gets the highlights Exposure value.
  33359. * 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.
  33360. */
  33361. get: function () {
  33362. return this._highlightsExposure;
  33363. },
  33364. /**
  33365. * Sets the highlights Exposure value.
  33366. * 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.
  33367. */
  33368. set: function (value) {
  33369. this._highlightsExposure = value;
  33370. this._dirty = true;
  33371. },
  33372. enumerable: true,
  33373. configurable: true
  33374. });
  33375. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33376. /**
  33377. * Gets the midtones Hue value.
  33378. * 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).
  33379. */
  33380. get: function () {
  33381. return this._midtonesHue;
  33382. },
  33383. /**
  33384. * Sets the midtones Hue value.
  33385. * 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).
  33386. */
  33387. set: function (value) {
  33388. this._midtonesHue = value;
  33389. this._dirty = true;
  33390. },
  33391. enumerable: true,
  33392. configurable: true
  33393. });
  33394. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33395. /**
  33396. * Gets the midtones Density value.
  33397. * 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.
  33398. * Values less than zero provide a filter of opposite hue.
  33399. */
  33400. get: function () {
  33401. return this._midtonesDensity;
  33402. },
  33403. /**
  33404. * Sets the midtones Density value.
  33405. * 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.
  33406. * Values less than zero provide a filter of opposite hue.
  33407. */
  33408. set: function (value) {
  33409. this._midtonesDensity = value;
  33410. this._dirty = true;
  33411. },
  33412. enumerable: true,
  33413. configurable: true
  33414. });
  33415. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33416. /**
  33417. * Gets the midtones Saturation value.
  33418. * 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.
  33419. */
  33420. get: function () {
  33421. return this._midtonesSaturation;
  33422. },
  33423. /**
  33424. * Sets the midtones Saturation value.
  33425. * 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.
  33426. */
  33427. set: function (value) {
  33428. this._midtonesSaturation = value;
  33429. this._dirty = true;
  33430. },
  33431. enumerable: true,
  33432. configurable: true
  33433. });
  33434. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33435. /**
  33436. * Gets the midtones Exposure value.
  33437. * 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.
  33438. */
  33439. get: function () {
  33440. return this._midtonesExposure;
  33441. },
  33442. /**
  33443. * Sets the midtones Exposure value.
  33444. * 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.
  33445. */
  33446. set: function (value) {
  33447. this._midtonesExposure = value;
  33448. this._dirty = true;
  33449. },
  33450. enumerable: true,
  33451. configurable: true
  33452. });
  33453. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33454. /**
  33455. * Gets the shadows Hue value.
  33456. * 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).
  33457. */
  33458. get: function () {
  33459. return this._shadowsHue;
  33460. },
  33461. /**
  33462. * Sets the shadows Hue value.
  33463. * 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).
  33464. */
  33465. set: function (value) {
  33466. this._shadowsHue = value;
  33467. this._dirty = true;
  33468. },
  33469. enumerable: true,
  33470. configurable: true
  33471. });
  33472. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33473. /**
  33474. * Gets the shadows Density value.
  33475. * 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.
  33476. * Values less than zero provide a filter of opposite hue.
  33477. */
  33478. get: function () {
  33479. return this._shadowsDensity;
  33480. },
  33481. /**
  33482. * Sets the shadows Density value.
  33483. * 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.
  33484. * Values less than zero provide a filter of opposite hue.
  33485. */
  33486. set: function (value) {
  33487. this._shadowsDensity = value;
  33488. this._dirty = true;
  33489. },
  33490. enumerable: true,
  33491. configurable: true
  33492. });
  33493. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33494. /**
  33495. * Gets the shadows Saturation value.
  33496. * 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.
  33497. */
  33498. get: function () {
  33499. return this._shadowsSaturation;
  33500. },
  33501. /**
  33502. * Sets the shadows Saturation value.
  33503. * 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.
  33504. */
  33505. set: function (value) {
  33506. this._shadowsSaturation = value;
  33507. this._dirty = true;
  33508. },
  33509. enumerable: true,
  33510. configurable: true
  33511. });
  33512. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33513. /**
  33514. * Gets the shadows Exposure value.
  33515. * 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.
  33516. */
  33517. get: function () {
  33518. return this._shadowsExposure;
  33519. },
  33520. /**
  33521. * Sets the shadows Exposure value.
  33522. * 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.
  33523. */
  33524. set: function (value) {
  33525. this._shadowsExposure = value;
  33526. this._dirty = true;
  33527. },
  33528. enumerable: true,
  33529. configurable: true
  33530. });
  33531. ColorCurves.prototype.getClassName = function () {
  33532. return "ColorCurves";
  33533. };
  33534. /**
  33535. * Binds the color curves to the shader.
  33536. * @param colorCurves The color curve to bind
  33537. * @param effect The effect to bind to
  33538. */
  33539. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33540. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33541. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33542. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33543. if (colorCurves._dirty) {
  33544. colorCurves._dirty = false;
  33545. // Fill in global info.
  33546. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33547. // Compute highlights info.
  33548. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33549. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33550. // Compute midtones info.
  33551. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33552. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33553. // Compute shadows info.
  33554. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33555. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33556. // Compute deltas (neutral is midtones).
  33557. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33558. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33559. }
  33560. if (effect) {
  33561. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33562. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33563. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33564. }
  33565. };
  33566. /**
  33567. * Prepare the list of uniforms associated with the ColorCurves effects.
  33568. * @param uniformsList The list of uniforms used in the effect
  33569. */
  33570. ColorCurves.PrepareUniforms = function (uniformsList) {
  33571. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33572. };
  33573. /**
  33574. * Returns color grading data based on a hue, density, saturation and exposure value.
  33575. * @param filterHue The hue of the color filter.
  33576. * @param filterDensity The density of the color filter.
  33577. * @param saturation The saturation.
  33578. * @param exposure The exposure.
  33579. * @param result The result data container.
  33580. */
  33581. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33582. if (hue == null) {
  33583. return;
  33584. }
  33585. hue = ColorCurves.clamp(hue, 0, 360);
  33586. density = ColorCurves.clamp(density, -100, 100);
  33587. saturation = ColorCurves.clamp(saturation, -100, 100);
  33588. exposure = ColorCurves.clamp(exposure, -100, 100);
  33589. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33590. // so that the maximum filter density is only 50% control. This provides fine control
  33591. // for small values and reasonable range.
  33592. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33593. density *= 0.5;
  33594. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33595. if (density < 0) {
  33596. density *= -1;
  33597. hue = (hue + 180) % 360;
  33598. }
  33599. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33600. result.scaleToRef(2, result);
  33601. result.a = 1 + 0.01 * saturation;
  33602. };
  33603. /**
  33604. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33605. * @param value The input slider value in range [-100,100].
  33606. * @returns Adjusted value.
  33607. */
  33608. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33609. value /= 100;
  33610. var x = Math.abs(value);
  33611. x = Math.pow(x, 2);
  33612. if (value < 0) {
  33613. x *= -1;
  33614. }
  33615. x *= 100;
  33616. return x;
  33617. };
  33618. /**
  33619. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33620. * @param hue The hue (H) input.
  33621. * @param saturation The saturation (S) input.
  33622. * @param brightness The brightness (B) input.
  33623. * @result An RGBA color represented as Vector4.
  33624. */
  33625. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33626. var h = ColorCurves.clamp(hue, 0, 360);
  33627. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33628. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33629. if (s === 0) {
  33630. result.r = v;
  33631. result.g = v;
  33632. result.b = v;
  33633. }
  33634. else {
  33635. // sector 0 to 5
  33636. h /= 60;
  33637. var i = Math.floor(h);
  33638. // fractional part of h
  33639. var f = h - i;
  33640. var p = v * (1 - s);
  33641. var q = v * (1 - s * f);
  33642. var t = v * (1 - s * (1 - f));
  33643. switch (i) {
  33644. case 0:
  33645. result.r = v;
  33646. result.g = t;
  33647. result.b = p;
  33648. break;
  33649. case 1:
  33650. result.r = q;
  33651. result.g = v;
  33652. result.b = p;
  33653. break;
  33654. case 2:
  33655. result.r = p;
  33656. result.g = v;
  33657. result.b = t;
  33658. break;
  33659. case 3:
  33660. result.r = p;
  33661. result.g = q;
  33662. result.b = v;
  33663. break;
  33664. case 4:
  33665. result.r = t;
  33666. result.g = p;
  33667. result.b = v;
  33668. break;
  33669. default:// case 5:
  33670. result.r = v;
  33671. result.g = p;
  33672. result.b = q;
  33673. break;
  33674. }
  33675. }
  33676. result.a = 1;
  33677. };
  33678. /**
  33679. * Returns a value clamped between min and max
  33680. * @param value The value to clamp
  33681. * @param min The minimum of value
  33682. * @param max The maximum of value
  33683. * @returns The clamped value.
  33684. */
  33685. ColorCurves.clamp = function (value, min, max) {
  33686. return Math.min(Math.max(value, min), max);
  33687. };
  33688. /**
  33689. * Clones the current color curve instance.
  33690. * @return The cloned curves
  33691. */
  33692. ColorCurves.prototype.clone = function () {
  33693. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33694. };
  33695. /**
  33696. * Serializes the current color curve instance to a json representation.
  33697. * @return a JSON representation
  33698. */
  33699. ColorCurves.prototype.serialize = function () {
  33700. return BABYLON.SerializationHelper.Serialize(this);
  33701. };
  33702. /**
  33703. * Parses the color curve from a json representation.
  33704. * @param source the JSON source to parse
  33705. * @return The parsed curves
  33706. */
  33707. ColorCurves.Parse = function (source) {
  33708. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33709. };
  33710. __decorate([
  33711. BABYLON.serialize()
  33712. ], ColorCurves.prototype, "_globalHue", void 0);
  33713. __decorate([
  33714. BABYLON.serialize()
  33715. ], ColorCurves.prototype, "_globalDensity", void 0);
  33716. __decorate([
  33717. BABYLON.serialize()
  33718. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33719. __decorate([
  33720. BABYLON.serialize()
  33721. ], ColorCurves.prototype, "_globalExposure", void 0);
  33722. __decorate([
  33723. BABYLON.serialize()
  33724. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33725. __decorate([
  33726. BABYLON.serialize()
  33727. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33728. __decorate([
  33729. BABYLON.serialize()
  33730. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33731. __decorate([
  33732. BABYLON.serialize()
  33733. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33734. __decorate([
  33735. BABYLON.serialize()
  33736. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33737. __decorate([
  33738. BABYLON.serialize()
  33739. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33740. __decorate([
  33741. BABYLON.serialize()
  33742. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33743. __decorate([
  33744. BABYLON.serialize()
  33745. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33746. return ColorCurves;
  33747. }());
  33748. BABYLON.ColorCurves = ColorCurves;
  33749. })(BABYLON || (BABYLON = {}));
  33750. //# sourceMappingURL=babylon.colorCurves.js.map
  33751. var BABYLON;
  33752. (function (BABYLON) {
  33753. var StandardMaterialDefines = /** @class */ (function (_super) {
  33754. __extends(StandardMaterialDefines, _super);
  33755. function StandardMaterialDefines() {
  33756. var _this = _super.call(this) || this;
  33757. _this.MAINUV1 = false;
  33758. _this.MAINUV2 = false;
  33759. _this.DIFFUSE = false;
  33760. _this.DIFFUSEDIRECTUV = 0;
  33761. _this.AMBIENT = false;
  33762. _this.AMBIENTDIRECTUV = 0;
  33763. _this.OPACITY = false;
  33764. _this.OPACITYDIRECTUV = 0;
  33765. _this.OPACITYRGB = false;
  33766. _this.REFLECTION = false;
  33767. _this.EMISSIVE = false;
  33768. _this.EMISSIVEDIRECTUV = 0;
  33769. _this.SPECULAR = false;
  33770. _this.SPECULARDIRECTUV = 0;
  33771. _this.BUMP = false;
  33772. _this.BUMPDIRECTUV = 0;
  33773. _this.PARALLAX = false;
  33774. _this.PARALLAXOCCLUSION = false;
  33775. _this.SPECULAROVERALPHA = false;
  33776. _this.CLIPPLANE = false;
  33777. _this.ALPHATEST = false;
  33778. _this.DEPTHPREPASS = false;
  33779. _this.ALPHAFROMDIFFUSE = false;
  33780. _this.POINTSIZE = false;
  33781. _this.FOG = false;
  33782. _this.SPECULARTERM = false;
  33783. _this.DIFFUSEFRESNEL = false;
  33784. _this.OPACITYFRESNEL = false;
  33785. _this.REFLECTIONFRESNEL = false;
  33786. _this.REFRACTIONFRESNEL = false;
  33787. _this.EMISSIVEFRESNEL = false;
  33788. _this.FRESNEL = false;
  33789. _this.NORMAL = false;
  33790. _this.UV1 = false;
  33791. _this.UV2 = false;
  33792. _this.VERTEXCOLOR = false;
  33793. _this.VERTEXALPHA = false;
  33794. _this.NUM_BONE_INFLUENCERS = 0;
  33795. _this.BonesPerMesh = 0;
  33796. _this.INSTANCES = false;
  33797. _this.GLOSSINESS = false;
  33798. _this.ROUGHNESS = false;
  33799. _this.EMISSIVEASILLUMINATION = false;
  33800. _this.LINKEMISSIVEWITHDIFFUSE = false;
  33801. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  33802. _this.LIGHTMAP = false;
  33803. _this.LIGHTMAPDIRECTUV = 0;
  33804. _this.USELIGHTMAPASSHADOWMAP = false;
  33805. _this.REFLECTIONMAP_3D = false;
  33806. _this.REFLECTIONMAP_SPHERICAL = false;
  33807. _this.REFLECTIONMAP_PLANAR = false;
  33808. _this.REFLECTIONMAP_CUBIC = false;
  33809. _this.REFLECTIONMAP_PROJECTION = false;
  33810. _this.REFLECTIONMAP_SKYBOX = false;
  33811. _this.REFLECTIONMAP_EXPLICIT = false;
  33812. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33813. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33814. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33815. _this.INVERTCUBICMAP = false;
  33816. _this.LOGARITHMICDEPTH = false;
  33817. _this.REFRACTION = false;
  33818. _this.REFRACTIONMAP_3D = false;
  33819. _this.REFLECTIONOVERALPHA = false;
  33820. _this.TWOSIDEDLIGHTING = false;
  33821. _this.SHADOWFLOAT = false;
  33822. _this.MORPHTARGETS = false;
  33823. _this.MORPHTARGETS_NORMAL = false;
  33824. _this.MORPHTARGETS_TANGENT = false;
  33825. _this.NUM_MORPH_INFLUENCERS = 0;
  33826. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  33827. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  33828. _this.IMAGEPROCESSING = false;
  33829. _this.VIGNETTE = false;
  33830. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33831. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33832. _this.TONEMAPPING = false;
  33833. _this.CONTRAST = false;
  33834. _this.COLORCURVES = false;
  33835. _this.COLORGRADING = false;
  33836. _this.COLORGRADING3D = false;
  33837. _this.SAMPLER3DGREENDEPTH = false;
  33838. _this.SAMPLER3DBGRMAP = false;
  33839. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33840. _this.EXPOSURE = false;
  33841. _this.rebuild();
  33842. return _this;
  33843. }
  33844. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33845. var modes = [
  33846. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33847. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33848. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33849. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33850. ];
  33851. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33852. var mode = modes_1[_i];
  33853. this[mode] = (mode === modeToEnable);
  33854. }
  33855. };
  33856. return StandardMaterialDefines;
  33857. }(BABYLON.MaterialDefines));
  33858. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33859. var StandardMaterial = /** @class */ (function (_super) {
  33860. __extends(StandardMaterial, _super);
  33861. function StandardMaterial(name, scene) {
  33862. var _this = _super.call(this, name, scene) || this;
  33863. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33864. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33865. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33866. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33867. _this.specularPower = 64;
  33868. _this._useAlphaFromDiffuseTexture = false;
  33869. _this._useEmissiveAsIllumination = false;
  33870. _this._linkEmissiveWithDiffuse = false;
  33871. _this._useSpecularOverAlpha = false;
  33872. _this._useReflectionOverAlpha = false;
  33873. _this._disableLighting = false;
  33874. _this._useParallax = false;
  33875. _this._useParallaxOcclusion = false;
  33876. _this.parallaxScaleBias = 0.05;
  33877. _this._roughness = 0;
  33878. _this.indexOfRefraction = 0.98;
  33879. _this.invertRefractionY = true;
  33880. _this._useLightmapAsShadowmap = false;
  33881. _this._useReflectionFresnelFromSpecular = false;
  33882. _this._useGlossinessFromSpecularMapAlpha = false;
  33883. _this._maxSimultaneousLights = 4;
  33884. /**
  33885. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33886. */
  33887. _this._invertNormalMapX = false;
  33888. /**
  33889. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33890. */
  33891. _this._invertNormalMapY = false;
  33892. /**
  33893. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33894. */
  33895. _this._twoSidedLighting = false;
  33896. _this._renderTargets = new BABYLON.SmartArray(16);
  33897. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33898. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33899. // Setup the default processing configuration to the scene.
  33900. _this._attachImageProcessingConfiguration(null);
  33901. _this.getRenderTargetTextures = function () {
  33902. _this._renderTargets.reset();
  33903. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33904. _this._renderTargets.push(_this._reflectionTexture);
  33905. }
  33906. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33907. _this._renderTargets.push(_this._refractionTexture);
  33908. }
  33909. return _this._renderTargets;
  33910. };
  33911. return _this;
  33912. }
  33913. ;
  33914. ;
  33915. ;
  33916. ;
  33917. ;
  33918. ;
  33919. ;
  33920. ;
  33921. ;
  33922. ;
  33923. ;
  33924. ;
  33925. ;
  33926. ;
  33927. ;
  33928. ;
  33929. ;
  33930. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  33931. /**
  33932. * Gets the image processing configuration used either in this material.
  33933. */
  33934. get: function () {
  33935. return this._imageProcessingConfiguration;
  33936. },
  33937. /**
  33938. * Sets the Default image processing configuration used either in the this material.
  33939. *
  33940. * If sets to null, the scene one is in use.
  33941. */
  33942. set: function (value) {
  33943. this._attachImageProcessingConfiguration(value);
  33944. // Ensure the effect will be rebuilt.
  33945. this._markAllSubMeshesAsTexturesDirty();
  33946. },
  33947. enumerable: true,
  33948. configurable: true
  33949. });
  33950. /**
  33951. * Attaches a new image processing configuration to the Standard Material.
  33952. * @param configuration
  33953. */
  33954. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33955. var _this = this;
  33956. if (configuration === this._imageProcessingConfiguration) {
  33957. return;
  33958. }
  33959. // Detaches observer.
  33960. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33961. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33962. }
  33963. // Pick the scene configuration if needed.
  33964. if (!configuration) {
  33965. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33966. }
  33967. else {
  33968. this._imageProcessingConfiguration = configuration;
  33969. }
  33970. // Attaches observer.
  33971. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33972. _this._markAllSubMeshesAsImageProcessingDirty();
  33973. });
  33974. };
  33975. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  33976. /**
  33977. * Gets wether the color curves effect is enabled.
  33978. */
  33979. get: function () {
  33980. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33981. },
  33982. /**
  33983. * Sets wether the color curves effect is enabled.
  33984. */
  33985. set: function (value) {
  33986. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33987. },
  33988. enumerable: true,
  33989. configurable: true
  33990. });
  33991. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  33992. /**
  33993. * Gets wether the color grading effect is enabled.
  33994. */
  33995. get: function () {
  33996. return this.imageProcessingConfiguration.colorGradingEnabled;
  33997. },
  33998. /**
  33999. * Gets wether the color grading effect is enabled.
  34000. */
  34001. set: function (value) {
  34002. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34003. },
  34004. enumerable: true,
  34005. configurable: true
  34006. });
  34007. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34008. /**
  34009. * Gets wether tonemapping is enabled or not.
  34010. */
  34011. get: function () {
  34012. return this._imageProcessingConfiguration.toneMappingEnabled;
  34013. },
  34014. /**
  34015. * Sets wether tonemapping is enabled or not
  34016. */
  34017. set: function (value) {
  34018. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34019. },
  34020. enumerable: true,
  34021. configurable: true
  34022. });
  34023. ;
  34024. ;
  34025. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34026. /**
  34027. * The camera exposure used on this material.
  34028. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34029. * This corresponds to a photographic exposure.
  34030. */
  34031. get: function () {
  34032. return this._imageProcessingConfiguration.exposure;
  34033. },
  34034. /**
  34035. * The camera exposure used on this material.
  34036. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34037. * This corresponds to a photographic exposure.
  34038. */
  34039. set: function (value) {
  34040. this._imageProcessingConfiguration.exposure = value;
  34041. },
  34042. enumerable: true,
  34043. configurable: true
  34044. });
  34045. ;
  34046. ;
  34047. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  34048. /**
  34049. * Gets The camera contrast used on this material.
  34050. */
  34051. get: function () {
  34052. return this._imageProcessingConfiguration.contrast;
  34053. },
  34054. /**
  34055. * Sets The camera contrast used on this material.
  34056. */
  34057. set: function (value) {
  34058. this._imageProcessingConfiguration.contrast = value;
  34059. },
  34060. enumerable: true,
  34061. configurable: true
  34062. });
  34063. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  34064. /**
  34065. * Gets the Color Grading 2D Lookup Texture.
  34066. */
  34067. get: function () {
  34068. return this._imageProcessingConfiguration.colorGradingTexture;
  34069. },
  34070. /**
  34071. * Sets the Color Grading 2D Lookup Texture.
  34072. */
  34073. set: function (value) {
  34074. this._imageProcessingConfiguration.colorGradingTexture = value;
  34075. },
  34076. enumerable: true,
  34077. configurable: true
  34078. });
  34079. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  34080. /**
  34081. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34082. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34083. * 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;
  34084. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34085. */
  34086. get: function () {
  34087. return this._imageProcessingConfiguration.colorCurves;
  34088. },
  34089. /**
  34090. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34091. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34092. * 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;
  34093. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34094. */
  34095. set: function (value) {
  34096. this._imageProcessingConfiguration.colorCurves = value;
  34097. },
  34098. enumerable: true,
  34099. configurable: true
  34100. });
  34101. StandardMaterial.prototype.getClassName = function () {
  34102. return "StandardMaterial";
  34103. };
  34104. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34105. get: function () {
  34106. return this._useLogarithmicDepth;
  34107. },
  34108. set: function (value) {
  34109. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34110. this._markAllSubMeshesAsMiscDirty();
  34111. },
  34112. enumerable: true,
  34113. configurable: true
  34114. });
  34115. StandardMaterial.prototype.needAlphaBlending = function () {
  34116. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34117. };
  34118. StandardMaterial.prototype.needAlphaTesting = function () {
  34119. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34120. };
  34121. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34122. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34123. };
  34124. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34125. return this._diffuseTexture;
  34126. };
  34127. /**
  34128. * Child classes can use it to update shaders
  34129. */
  34130. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34131. if (useInstances === void 0) { useInstances = false; }
  34132. if (subMesh.effect && this.isFrozen) {
  34133. if (this._wasPreviouslyReady && subMesh.effect) {
  34134. return true;
  34135. }
  34136. }
  34137. if (!subMesh._materialDefines) {
  34138. subMesh._materialDefines = new StandardMaterialDefines();
  34139. }
  34140. var scene = this.getScene();
  34141. var defines = subMesh._materialDefines;
  34142. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34143. if (defines._renderId === scene.getRenderId()) {
  34144. return true;
  34145. }
  34146. }
  34147. var engine = scene.getEngine();
  34148. // Lights
  34149. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34150. // Textures
  34151. if (defines._areTexturesDirty) {
  34152. defines._needUVs = false;
  34153. defines.MAINUV1 = false;
  34154. defines.MAINUV2 = false;
  34155. if (scene.texturesEnabled) {
  34156. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34157. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34158. return false;
  34159. }
  34160. else {
  34161. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  34162. }
  34163. }
  34164. else {
  34165. defines.DIFFUSE = false;
  34166. }
  34167. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34168. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34169. return false;
  34170. }
  34171. else {
  34172. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  34173. }
  34174. }
  34175. else {
  34176. defines.AMBIENT = false;
  34177. }
  34178. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34179. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34180. return false;
  34181. }
  34182. else {
  34183. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  34184. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34185. }
  34186. }
  34187. else {
  34188. defines.OPACITY = false;
  34189. }
  34190. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34191. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  34192. return false;
  34193. }
  34194. else {
  34195. defines._needNormals = true;
  34196. defines.REFLECTION = true;
  34197. defines.ROUGHNESS = (this._roughness > 0);
  34198. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  34199. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  34200. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  34201. switch (this._reflectionTexture.coordinatesMode) {
  34202. case BABYLON.Texture.CUBIC_MODE:
  34203. case BABYLON.Texture.INVCUBIC_MODE:
  34204. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  34205. break;
  34206. case BABYLON.Texture.EXPLICIT_MODE:
  34207. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  34208. break;
  34209. case BABYLON.Texture.PLANAR_MODE:
  34210. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  34211. break;
  34212. case BABYLON.Texture.PROJECTION_MODE:
  34213. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  34214. break;
  34215. case BABYLON.Texture.SKYBOX_MODE:
  34216. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  34217. break;
  34218. case BABYLON.Texture.SPHERICAL_MODE:
  34219. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  34220. break;
  34221. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34222. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  34223. break;
  34224. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34225. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  34226. break;
  34227. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34228. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  34229. break;
  34230. }
  34231. }
  34232. }
  34233. else {
  34234. defines.REFLECTION = false;
  34235. }
  34236. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34237. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34238. return false;
  34239. }
  34240. else {
  34241. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  34242. }
  34243. }
  34244. else {
  34245. defines.EMISSIVE = false;
  34246. }
  34247. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34248. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34249. return false;
  34250. }
  34251. else {
  34252. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  34253. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34254. }
  34255. }
  34256. else {
  34257. defines.LIGHTMAP = false;
  34258. }
  34259. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34260. if (!this._specularTexture.isReadyOrNotBlocking()) {
  34261. return false;
  34262. }
  34263. else {
  34264. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  34265. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  34266. }
  34267. }
  34268. else {
  34269. defines.SPECULAR = false;
  34270. }
  34271. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  34272. // Bump texure can not be not blocking.
  34273. if (!this._bumpTexture.isReady()) {
  34274. return false;
  34275. }
  34276. else {
  34277. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  34278. defines.PARALLAX = this._useParallax;
  34279. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  34280. }
  34281. }
  34282. else {
  34283. defines.BUMP = false;
  34284. }
  34285. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34286. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  34287. return false;
  34288. }
  34289. else {
  34290. defines._needUVs = true;
  34291. defines.REFRACTION = true;
  34292. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  34293. }
  34294. }
  34295. else {
  34296. defines.REFRACTION = false;
  34297. }
  34298. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  34299. }
  34300. else {
  34301. defines.DIFFUSE = false;
  34302. defines.AMBIENT = false;
  34303. defines.OPACITY = false;
  34304. defines.REFLECTION = false;
  34305. defines.EMISSIVE = false;
  34306. defines.LIGHTMAP = false;
  34307. defines.BUMP = false;
  34308. defines.REFRACTION = false;
  34309. }
  34310. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  34311. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  34312. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  34313. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  34314. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  34315. }
  34316. if (defines._areImageProcessingDirty) {
  34317. if (!this._imageProcessingConfiguration.isReady()) {
  34318. return false;
  34319. }
  34320. this._imageProcessingConfiguration.prepareDefines(defines);
  34321. }
  34322. if (defines._areFresnelDirty) {
  34323. if (StandardMaterial.FresnelEnabled) {
  34324. // Fresnel
  34325. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  34326. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  34327. this._reflectionFresnelParameters) {
  34328. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  34329. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  34330. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  34331. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  34332. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  34333. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  34334. defines._needNormals = true;
  34335. defines.FRESNEL = true;
  34336. }
  34337. }
  34338. else {
  34339. defines.FRESNEL = false;
  34340. }
  34341. }
  34342. // Misc.
  34343. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34344. // Attribs
  34345. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  34346. // Values that need to be evaluated on every frame
  34347. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  34348. // Get correct effect
  34349. if (defines.isDirty) {
  34350. defines.markAsProcessed();
  34351. scene.resetCachedMaterial();
  34352. // Fallbacks
  34353. var fallbacks = new BABYLON.EffectFallbacks();
  34354. if (defines.REFLECTION) {
  34355. fallbacks.addFallback(0, "REFLECTION");
  34356. }
  34357. if (defines.SPECULAR) {
  34358. fallbacks.addFallback(0, "SPECULAR");
  34359. }
  34360. if (defines.BUMP) {
  34361. fallbacks.addFallback(0, "BUMP");
  34362. }
  34363. if (defines.PARALLAX) {
  34364. fallbacks.addFallback(1, "PARALLAX");
  34365. }
  34366. if (defines.PARALLAXOCCLUSION) {
  34367. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34368. }
  34369. if (defines.SPECULAROVERALPHA) {
  34370. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34371. }
  34372. if (defines.FOG) {
  34373. fallbacks.addFallback(1, "FOG");
  34374. }
  34375. if (defines.POINTSIZE) {
  34376. fallbacks.addFallback(0, "POINTSIZE");
  34377. }
  34378. if (defines.LOGARITHMICDEPTH) {
  34379. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34380. }
  34381. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34382. if (defines.SPECULARTERM) {
  34383. fallbacks.addFallback(0, "SPECULARTERM");
  34384. }
  34385. if (defines.DIFFUSEFRESNEL) {
  34386. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  34387. }
  34388. if (defines.OPACITYFRESNEL) {
  34389. fallbacks.addFallback(2, "OPACITYFRESNEL");
  34390. }
  34391. if (defines.REFLECTIONFRESNEL) {
  34392. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  34393. }
  34394. if (defines.EMISSIVEFRESNEL) {
  34395. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  34396. }
  34397. if (defines.FRESNEL) {
  34398. fallbacks.addFallback(4, "FRESNEL");
  34399. }
  34400. //Attributes
  34401. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34402. if (defines.NORMAL) {
  34403. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34404. }
  34405. if (defines.UV1) {
  34406. attribs.push(BABYLON.VertexBuffer.UVKind);
  34407. }
  34408. if (defines.UV2) {
  34409. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34410. }
  34411. if (defines.VERTEXCOLOR) {
  34412. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34413. }
  34414. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34415. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34416. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34417. var shaderName = "default";
  34418. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  34419. "vFogInfos", "vFogColor", "pointSize",
  34420. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34421. "mBones",
  34422. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34423. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  34424. "logarithmicDepthConstant", "vTangentSpaceParams"
  34425. ];
  34426. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  34427. var uniformBuffers = ["Material", "Scene"];
  34428. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  34429. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  34430. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  34431. uniformsNames: uniforms,
  34432. uniformBuffersNames: uniformBuffers,
  34433. samplers: samplers,
  34434. defines: defines,
  34435. maxSimultaneousLights: this._maxSimultaneousLights
  34436. });
  34437. if (this.customShaderNameResolve) {
  34438. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  34439. }
  34440. var join = defines.toString();
  34441. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  34442. attributes: attribs,
  34443. uniformsNames: uniforms,
  34444. uniformBuffersNames: uniformBuffers,
  34445. samplers: samplers,
  34446. defines: join,
  34447. fallbacks: fallbacks,
  34448. onCompiled: this.onCompiled,
  34449. onError: this.onError,
  34450. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  34451. }, engine), defines);
  34452. this.buildUniformLayout();
  34453. }
  34454. if (!subMesh.effect || !subMesh.effect.isReady()) {
  34455. return false;
  34456. }
  34457. defines._renderId = scene.getRenderId();
  34458. this._wasPreviouslyReady = true;
  34459. return true;
  34460. };
  34461. StandardMaterial.prototype.buildUniformLayout = function () {
  34462. // Order is important !
  34463. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  34464. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  34465. this._uniformBuffer.addUniform("opacityParts", 4);
  34466. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  34467. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  34468. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  34469. this._uniformBuffer.addUniform("refractionRightColor", 4);
  34470. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  34471. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  34472. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  34473. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  34474. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34475. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34476. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34477. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34478. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  34479. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34480. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  34481. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34482. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34483. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34484. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34485. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34486. this._uniformBuffer.addUniform("specularMatrix", 16);
  34487. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34488. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34489. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34490. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34491. this._uniformBuffer.addUniform("vSpecularColor", 4);
  34492. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34493. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  34494. this._uniformBuffer.addUniform("pointSize", 1);
  34495. this._uniformBuffer.create();
  34496. };
  34497. StandardMaterial.prototype.unbind = function () {
  34498. if (this._activeEffect) {
  34499. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34500. this._activeEffect.setTexture("reflection2DSampler", null);
  34501. }
  34502. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34503. this._activeEffect.setTexture("refraction2DSampler", null);
  34504. }
  34505. }
  34506. _super.prototype.unbind.call(this);
  34507. };
  34508. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34509. var scene = this.getScene();
  34510. var defines = subMesh._materialDefines;
  34511. if (!defines) {
  34512. return;
  34513. }
  34514. var effect = subMesh.effect;
  34515. if (!effect) {
  34516. return;
  34517. }
  34518. this._activeEffect = effect;
  34519. // Matrices
  34520. this.bindOnlyWorldMatrix(world);
  34521. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34522. // Bones
  34523. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  34524. if (mustRebind) {
  34525. this._uniformBuffer.bindToEffect(effect, "Material");
  34526. this.bindViewProjection(effect);
  34527. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34528. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  34529. // Fresnel
  34530. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  34531. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  34532. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  34533. }
  34534. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  34535. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  34536. }
  34537. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  34538. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  34539. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  34540. }
  34541. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  34542. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  34543. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  34544. }
  34545. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  34546. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  34547. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  34548. }
  34549. }
  34550. // Textures
  34551. if (scene.texturesEnabled) {
  34552. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34553. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  34554. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  34555. }
  34556. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34557. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  34558. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34559. }
  34560. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34561. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34562. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34563. }
  34564. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34565. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  34566. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  34567. }
  34568. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34569. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34570. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34571. }
  34572. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34573. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34574. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34575. }
  34576. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34577. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  34578. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  34579. }
  34580. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34581. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  34582. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34583. if (scene._mirroredCameraPosition) {
  34584. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34585. }
  34586. else {
  34587. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34588. }
  34589. }
  34590. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34591. var depth = 1.0;
  34592. if (!this._refractionTexture.isCube) {
  34593. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  34594. if (this._refractionTexture.depth) {
  34595. depth = this._refractionTexture.depth;
  34596. }
  34597. }
  34598. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  34599. }
  34600. }
  34601. // Point size
  34602. if (this.pointsCloud) {
  34603. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34604. }
  34605. if (defines.SPECULARTERM) {
  34606. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  34607. }
  34608. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  34609. // Diffuse
  34610. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  34611. }
  34612. // Textures
  34613. if (scene.texturesEnabled) {
  34614. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34615. effect.setTexture("diffuseSampler", this._diffuseTexture);
  34616. }
  34617. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34618. effect.setTexture("ambientSampler", this._ambientTexture);
  34619. }
  34620. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34621. effect.setTexture("opacitySampler", this._opacityTexture);
  34622. }
  34623. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34624. if (this._reflectionTexture.isCube) {
  34625. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  34626. }
  34627. else {
  34628. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  34629. }
  34630. }
  34631. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34632. effect.setTexture("emissiveSampler", this._emissiveTexture);
  34633. }
  34634. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34635. effect.setTexture("lightmapSampler", this._lightmapTexture);
  34636. }
  34637. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34638. effect.setTexture("specularSampler", this._specularTexture);
  34639. }
  34640. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34641. effect.setTexture("bumpSampler", this._bumpTexture);
  34642. }
  34643. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34644. var depth = 1.0;
  34645. if (this._refractionTexture.isCube) {
  34646. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  34647. }
  34648. else {
  34649. effect.setTexture("refraction2DSampler", this._refractionTexture);
  34650. }
  34651. }
  34652. }
  34653. // Clip plane
  34654. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34655. // Colors
  34656. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34657. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34658. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34659. }
  34660. if (mustRebind || !this.isFrozen) {
  34661. // Lights
  34662. if (scene.lightsEnabled && !this._disableLighting) {
  34663. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34664. }
  34665. // View
  34666. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34667. this.bindView(effect);
  34668. }
  34669. // Fog
  34670. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34671. // Morph targets
  34672. if (defines.NUM_MORPH_INFLUENCERS) {
  34673. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34674. }
  34675. // Log. depth
  34676. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34677. // image processing
  34678. this._imageProcessingConfiguration.bind(this._activeEffect);
  34679. }
  34680. this._uniformBuffer.update();
  34681. this._afterBind(mesh, this._activeEffect);
  34682. };
  34683. StandardMaterial.prototype.getAnimatables = function () {
  34684. var results = [];
  34685. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34686. results.push(this._diffuseTexture);
  34687. }
  34688. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34689. results.push(this._ambientTexture);
  34690. }
  34691. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34692. results.push(this._opacityTexture);
  34693. }
  34694. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34695. results.push(this._reflectionTexture);
  34696. }
  34697. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34698. results.push(this._emissiveTexture);
  34699. }
  34700. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34701. results.push(this._specularTexture);
  34702. }
  34703. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34704. results.push(this._bumpTexture);
  34705. }
  34706. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34707. results.push(this._lightmapTexture);
  34708. }
  34709. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34710. results.push(this._refractionTexture);
  34711. }
  34712. return results;
  34713. };
  34714. StandardMaterial.prototype.getActiveTextures = function () {
  34715. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34716. if (this._diffuseTexture) {
  34717. activeTextures.push(this._diffuseTexture);
  34718. }
  34719. if (this._ambientTexture) {
  34720. activeTextures.push(this._ambientTexture);
  34721. }
  34722. if (this._opacityTexture) {
  34723. activeTextures.push(this._opacityTexture);
  34724. }
  34725. if (this._reflectionTexture) {
  34726. activeTextures.push(this._reflectionTexture);
  34727. }
  34728. if (this._emissiveTexture) {
  34729. activeTextures.push(this._emissiveTexture);
  34730. }
  34731. if (this._specularTexture) {
  34732. activeTextures.push(this._specularTexture);
  34733. }
  34734. if (this._bumpTexture) {
  34735. activeTextures.push(this._bumpTexture);
  34736. }
  34737. if (this._lightmapTexture) {
  34738. activeTextures.push(this._lightmapTexture);
  34739. }
  34740. if (this._refractionTexture) {
  34741. activeTextures.push(this._refractionTexture);
  34742. }
  34743. return activeTextures;
  34744. };
  34745. StandardMaterial.prototype.hasTexture = function (texture) {
  34746. if (_super.prototype.hasTexture.call(this, texture)) {
  34747. return true;
  34748. }
  34749. if (this._diffuseTexture === texture) {
  34750. return true;
  34751. }
  34752. if (this._ambientTexture === texture) {
  34753. return true;
  34754. }
  34755. if (this._opacityTexture === texture) {
  34756. return true;
  34757. }
  34758. if (this._reflectionTexture === texture) {
  34759. return true;
  34760. }
  34761. if (this._emissiveTexture === texture) {
  34762. return true;
  34763. }
  34764. if (this._specularTexture === texture) {
  34765. return true;
  34766. }
  34767. if (this._bumpTexture === texture) {
  34768. return true;
  34769. }
  34770. if (this._lightmapTexture === texture) {
  34771. return true;
  34772. }
  34773. if (this._refractionTexture === texture) {
  34774. return true;
  34775. }
  34776. return false;
  34777. };
  34778. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34779. if (forceDisposeTextures) {
  34780. if (this._diffuseTexture) {
  34781. this._diffuseTexture.dispose();
  34782. }
  34783. if (this._ambientTexture) {
  34784. this._ambientTexture.dispose();
  34785. }
  34786. if (this._opacityTexture) {
  34787. this._opacityTexture.dispose();
  34788. }
  34789. if (this._reflectionTexture) {
  34790. this._reflectionTexture.dispose();
  34791. }
  34792. if (this._emissiveTexture) {
  34793. this._emissiveTexture.dispose();
  34794. }
  34795. if (this._specularTexture) {
  34796. this._specularTexture.dispose();
  34797. }
  34798. if (this._bumpTexture) {
  34799. this._bumpTexture.dispose();
  34800. }
  34801. if (this._lightmapTexture) {
  34802. this._lightmapTexture.dispose();
  34803. }
  34804. if (this._refractionTexture) {
  34805. this._refractionTexture.dispose();
  34806. }
  34807. }
  34808. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34809. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34810. }
  34811. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34812. };
  34813. StandardMaterial.prototype.clone = function (name) {
  34814. var _this = this;
  34815. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  34816. result.name = name;
  34817. result.id = name;
  34818. return result;
  34819. };
  34820. StandardMaterial.prototype.serialize = function () {
  34821. return BABYLON.SerializationHelper.Serialize(this);
  34822. };
  34823. // Statics
  34824. StandardMaterial.Parse = function (source, scene, rootUrl) {
  34825. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  34826. };
  34827. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  34828. get: function () {
  34829. return StandardMaterial._DiffuseTextureEnabled;
  34830. },
  34831. set: function (value) {
  34832. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34833. return;
  34834. }
  34835. StandardMaterial._DiffuseTextureEnabled = value;
  34836. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34837. },
  34838. enumerable: true,
  34839. configurable: true
  34840. });
  34841. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34842. get: function () {
  34843. return StandardMaterial._AmbientTextureEnabled;
  34844. },
  34845. set: function (value) {
  34846. if (StandardMaterial._AmbientTextureEnabled === value) {
  34847. return;
  34848. }
  34849. StandardMaterial._AmbientTextureEnabled = value;
  34850. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34851. },
  34852. enumerable: true,
  34853. configurable: true
  34854. });
  34855. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34856. get: function () {
  34857. return StandardMaterial._OpacityTextureEnabled;
  34858. },
  34859. set: function (value) {
  34860. if (StandardMaterial._OpacityTextureEnabled === value) {
  34861. return;
  34862. }
  34863. StandardMaterial._OpacityTextureEnabled = value;
  34864. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34865. },
  34866. enumerable: true,
  34867. configurable: true
  34868. });
  34869. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34870. get: function () {
  34871. return StandardMaterial._ReflectionTextureEnabled;
  34872. },
  34873. set: function (value) {
  34874. if (StandardMaterial._ReflectionTextureEnabled === value) {
  34875. return;
  34876. }
  34877. StandardMaterial._ReflectionTextureEnabled = value;
  34878. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34879. },
  34880. enumerable: true,
  34881. configurable: true
  34882. });
  34883. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  34884. get: function () {
  34885. return StandardMaterial._EmissiveTextureEnabled;
  34886. },
  34887. set: function (value) {
  34888. if (StandardMaterial._EmissiveTextureEnabled === value) {
  34889. return;
  34890. }
  34891. StandardMaterial._EmissiveTextureEnabled = value;
  34892. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34893. },
  34894. enumerable: true,
  34895. configurable: true
  34896. });
  34897. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  34898. get: function () {
  34899. return StandardMaterial._SpecularTextureEnabled;
  34900. },
  34901. set: function (value) {
  34902. if (StandardMaterial._SpecularTextureEnabled === value) {
  34903. return;
  34904. }
  34905. StandardMaterial._SpecularTextureEnabled = value;
  34906. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34907. },
  34908. enumerable: true,
  34909. configurable: true
  34910. });
  34911. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  34912. get: function () {
  34913. return StandardMaterial._BumpTextureEnabled;
  34914. },
  34915. set: function (value) {
  34916. if (StandardMaterial._BumpTextureEnabled === value) {
  34917. return;
  34918. }
  34919. StandardMaterial._BumpTextureEnabled = value;
  34920. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34921. },
  34922. enumerable: true,
  34923. configurable: true
  34924. });
  34925. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  34926. get: function () {
  34927. return StandardMaterial._LightmapTextureEnabled;
  34928. },
  34929. set: function (value) {
  34930. if (StandardMaterial._LightmapTextureEnabled === value) {
  34931. return;
  34932. }
  34933. StandardMaterial._LightmapTextureEnabled = value;
  34934. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34935. },
  34936. enumerable: true,
  34937. configurable: true
  34938. });
  34939. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  34940. get: function () {
  34941. return StandardMaterial._RefractionTextureEnabled;
  34942. },
  34943. set: function (value) {
  34944. if (StandardMaterial._RefractionTextureEnabled === value) {
  34945. return;
  34946. }
  34947. StandardMaterial._RefractionTextureEnabled = value;
  34948. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34949. },
  34950. enumerable: true,
  34951. configurable: true
  34952. });
  34953. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  34954. get: function () {
  34955. return StandardMaterial._ColorGradingTextureEnabled;
  34956. },
  34957. set: function (value) {
  34958. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  34959. return;
  34960. }
  34961. StandardMaterial._ColorGradingTextureEnabled = value;
  34962. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34963. },
  34964. enumerable: true,
  34965. configurable: true
  34966. });
  34967. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  34968. get: function () {
  34969. return StandardMaterial._FresnelEnabled;
  34970. },
  34971. set: function (value) {
  34972. if (StandardMaterial._FresnelEnabled === value) {
  34973. return;
  34974. }
  34975. StandardMaterial._FresnelEnabled = value;
  34976. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  34977. },
  34978. enumerable: true,
  34979. configurable: true
  34980. });
  34981. // Flags used to enable or disable a type of texture for all Standard Materials
  34982. StandardMaterial._DiffuseTextureEnabled = true;
  34983. StandardMaterial._AmbientTextureEnabled = true;
  34984. StandardMaterial._OpacityTextureEnabled = true;
  34985. StandardMaterial._ReflectionTextureEnabled = true;
  34986. StandardMaterial._EmissiveTextureEnabled = true;
  34987. StandardMaterial._SpecularTextureEnabled = true;
  34988. StandardMaterial._BumpTextureEnabled = true;
  34989. StandardMaterial._LightmapTextureEnabled = true;
  34990. StandardMaterial._RefractionTextureEnabled = true;
  34991. StandardMaterial._ColorGradingTextureEnabled = true;
  34992. StandardMaterial._FresnelEnabled = true;
  34993. __decorate([
  34994. BABYLON.serializeAsTexture("diffuseTexture")
  34995. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  34996. __decorate([
  34997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34998. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  34999. __decorate([
  35000. BABYLON.serializeAsTexture("ambientTexture")
  35001. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35002. __decorate([
  35003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35004. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35005. __decorate([
  35006. BABYLON.serializeAsTexture("opacityTexture")
  35007. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35008. __decorate([
  35009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35010. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35011. __decorate([
  35012. BABYLON.serializeAsTexture("reflectionTexture")
  35013. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35014. __decorate([
  35015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35016. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35017. __decorate([
  35018. BABYLON.serializeAsTexture("emissiveTexture")
  35019. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35020. __decorate([
  35021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35022. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35023. __decorate([
  35024. BABYLON.serializeAsTexture("specularTexture")
  35025. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35026. __decorate([
  35027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35028. ], StandardMaterial.prototype, "specularTexture", void 0);
  35029. __decorate([
  35030. BABYLON.serializeAsTexture("bumpTexture")
  35031. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35032. __decorate([
  35033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35034. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35035. __decorate([
  35036. BABYLON.serializeAsTexture("lightmapTexture")
  35037. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35038. __decorate([
  35039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35040. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35041. __decorate([
  35042. BABYLON.serializeAsTexture("refractionTexture")
  35043. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35044. __decorate([
  35045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35046. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35047. __decorate([
  35048. BABYLON.serializeAsColor3("ambient")
  35049. ], StandardMaterial.prototype, "ambientColor", void 0);
  35050. __decorate([
  35051. BABYLON.serializeAsColor3("diffuse")
  35052. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35053. __decorate([
  35054. BABYLON.serializeAsColor3("specular")
  35055. ], StandardMaterial.prototype, "specularColor", void 0);
  35056. __decorate([
  35057. BABYLON.serializeAsColor3("emissive")
  35058. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35059. __decorate([
  35060. BABYLON.serialize()
  35061. ], StandardMaterial.prototype, "specularPower", void 0);
  35062. __decorate([
  35063. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35064. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35065. __decorate([
  35066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35067. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35068. __decorate([
  35069. BABYLON.serialize("useEmissiveAsIllumination")
  35070. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35071. __decorate([
  35072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35073. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35074. __decorate([
  35075. BABYLON.serialize("linkEmissiveWithDiffuse")
  35076. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35077. __decorate([
  35078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35079. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35080. __decorate([
  35081. BABYLON.serialize("useSpecularOverAlpha")
  35082. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35083. __decorate([
  35084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35085. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35086. __decorate([
  35087. BABYLON.serialize("useReflectionOverAlpha")
  35088. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35089. __decorate([
  35090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35091. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35092. __decorate([
  35093. BABYLON.serialize("disableLighting")
  35094. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35095. __decorate([
  35096. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35097. ], StandardMaterial.prototype, "disableLighting", void 0);
  35098. __decorate([
  35099. BABYLON.serialize("useParallax")
  35100. ], StandardMaterial.prototype, "_useParallax", void 0);
  35101. __decorate([
  35102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35103. ], StandardMaterial.prototype, "useParallax", void 0);
  35104. __decorate([
  35105. BABYLON.serialize("useParallaxOcclusion")
  35106. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35107. __decorate([
  35108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35109. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35110. __decorate([
  35111. BABYLON.serialize()
  35112. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35113. __decorate([
  35114. BABYLON.serialize("roughness")
  35115. ], StandardMaterial.prototype, "_roughness", void 0);
  35116. __decorate([
  35117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35118. ], StandardMaterial.prototype, "roughness", void 0);
  35119. __decorate([
  35120. BABYLON.serialize()
  35121. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35122. __decorate([
  35123. BABYLON.serialize()
  35124. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35125. __decorate([
  35126. BABYLON.serialize("useLightmapAsShadowmap")
  35127. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35128. __decorate([
  35129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35130. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35131. __decorate([
  35132. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35133. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35134. __decorate([
  35135. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35136. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35137. __decorate([
  35138. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35139. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35140. __decorate([
  35141. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35142. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35143. __decorate([
  35144. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35145. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35146. __decorate([
  35147. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35148. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35149. __decorate([
  35150. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35151. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35152. __decorate([
  35153. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35154. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35155. __decorate([
  35156. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35157. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35158. __decorate([
  35159. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35160. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35161. __decorate([
  35162. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35163. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35164. __decorate([
  35165. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35166. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  35167. __decorate([
  35168. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  35169. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  35170. __decorate([
  35171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35172. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  35173. __decorate([
  35174. BABYLON.serialize("maxSimultaneousLights")
  35175. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  35176. __decorate([
  35177. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35178. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  35179. __decorate([
  35180. BABYLON.serialize("invertNormalMapX")
  35181. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  35182. __decorate([
  35183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35184. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  35185. __decorate([
  35186. BABYLON.serialize("invertNormalMapY")
  35187. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  35188. __decorate([
  35189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35190. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  35191. __decorate([
  35192. BABYLON.serialize("twoSidedLighting")
  35193. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  35194. __decorate([
  35195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35196. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  35197. __decorate([
  35198. BABYLON.serialize()
  35199. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  35200. return StandardMaterial;
  35201. }(BABYLON.PushMaterial));
  35202. BABYLON.StandardMaterial = StandardMaterial;
  35203. })(BABYLON || (BABYLON = {}));
  35204. //# sourceMappingURL=babylon.standardMaterial.js.map
  35205. var BABYLON;
  35206. (function (BABYLON) {
  35207. var PBRMaterialDefines = /** @class */ (function (_super) {
  35208. __extends(PBRMaterialDefines, _super);
  35209. function PBRMaterialDefines() {
  35210. var _this = _super.call(this) || this;
  35211. _this.PBR = true;
  35212. _this.MAINUV1 = false;
  35213. _this.MAINUV2 = false;
  35214. _this.UV1 = false;
  35215. _this.UV2 = false;
  35216. _this.ALBEDO = false;
  35217. _this.ALBEDODIRECTUV = 0;
  35218. _this.VERTEXCOLOR = false;
  35219. _this.AMBIENT = false;
  35220. _this.AMBIENTDIRECTUV = 0;
  35221. _this.AMBIENTINGRAYSCALE = false;
  35222. _this.OPACITY = false;
  35223. _this.VERTEXALPHA = false;
  35224. _this.OPACITYDIRECTUV = 0;
  35225. _this.OPACITYRGB = false;
  35226. _this.ALPHATEST = false;
  35227. _this.DEPTHPREPASS = false;
  35228. _this.ALPHABLEND = false;
  35229. _this.ALPHAFROMALBEDO = false;
  35230. _this.ALPHATESTVALUE = 0.5;
  35231. _this.SPECULAROVERALPHA = false;
  35232. _this.RADIANCEOVERALPHA = false;
  35233. _this.ALPHAFRESNEL = false;
  35234. _this.PREMULTIPLYALPHA = false;
  35235. _this.EMISSIVE = false;
  35236. _this.EMISSIVEDIRECTUV = 0;
  35237. _this.REFLECTIVITY = false;
  35238. _this.REFLECTIVITYDIRECTUV = 0;
  35239. _this.SPECULARTERM = false;
  35240. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  35241. _this.MICROSURFACEAUTOMATIC = false;
  35242. _this.LODBASEDMICROSFURACE = false;
  35243. _this.MICROSURFACEMAP = false;
  35244. _this.MICROSURFACEMAPDIRECTUV = 0;
  35245. _this.METALLICWORKFLOW = false;
  35246. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  35247. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  35248. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  35249. _this.AOSTOREINMETALMAPRED = false;
  35250. _this.ENVIRONMENTBRDF = false;
  35251. _this.NORMAL = false;
  35252. _this.TANGENT = false;
  35253. _this.BUMP = false;
  35254. _this.BUMPDIRECTUV = 0;
  35255. _this.PARALLAX = false;
  35256. _this.PARALLAXOCCLUSION = false;
  35257. _this.NORMALXYSCALE = true;
  35258. _this.LIGHTMAP = false;
  35259. _this.LIGHTMAPDIRECTUV = 0;
  35260. _this.USELIGHTMAPASSHADOWMAP = false;
  35261. _this.REFLECTION = false;
  35262. _this.REFLECTIONMAP_3D = false;
  35263. _this.REFLECTIONMAP_SPHERICAL = false;
  35264. _this.REFLECTIONMAP_PLANAR = false;
  35265. _this.REFLECTIONMAP_CUBIC = false;
  35266. _this.REFLECTIONMAP_PROJECTION = false;
  35267. _this.REFLECTIONMAP_SKYBOX = false;
  35268. _this.REFLECTIONMAP_EXPLICIT = false;
  35269. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35270. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35271. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35272. _this.INVERTCUBICMAP = false;
  35273. _this.USESPHERICALFROMREFLECTIONMAP = false;
  35274. _this.USESPHERICALINVERTEX = false;
  35275. _this.REFLECTIONMAP_OPPOSITEZ = false;
  35276. _this.LODINREFLECTIONALPHA = false;
  35277. _this.GAMMAREFLECTION = false;
  35278. _this.REFRACTION = false;
  35279. _this.REFRACTIONMAP_3D = false;
  35280. _this.REFRACTIONMAP_OPPOSITEZ = false;
  35281. _this.LODINREFRACTIONALPHA = false;
  35282. _this.GAMMAREFRACTION = false;
  35283. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  35284. _this.INSTANCES = false;
  35285. _this.NUM_BONE_INFLUENCERS = 0;
  35286. _this.BonesPerMesh = 0;
  35287. _this.NONUNIFORMSCALING = false;
  35288. _this.MORPHTARGETS = false;
  35289. _this.MORPHTARGETS_NORMAL = false;
  35290. _this.MORPHTARGETS_TANGENT = false;
  35291. _this.NUM_MORPH_INFLUENCERS = 0;
  35292. _this.IMAGEPROCESSING = false;
  35293. _this.VIGNETTE = false;
  35294. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35295. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35296. _this.TONEMAPPING = false;
  35297. _this.CONTRAST = false;
  35298. _this.COLORCURVES = false;
  35299. _this.COLORGRADING = false;
  35300. _this.COLORGRADING3D = false;
  35301. _this.SAMPLER3DGREENDEPTH = false;
  35302. _this.SAMPLER3DBGRMAP = false;
  35303. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35304. _this.EXPOSURE = false;
  35305. _this.USEPHYSICALLIGHTFALLOFF = false;
  35306. _this.TWOSIDEDLIGHTING = false;
  35307. _this.SHADOWFLOAT = false;
  35308. _this.CLIPPLANE = false;
  35309. _this.POINTSIZE = false;
  35310. _this.FOG = false;
  35311. _this.LOGARITHMICDEPTH = false;
  35312. _this.FORCENORMALFORWARD = false;
  35313. _this.rebuild();
  35314. return _this;
  35315. }
  35316. PBRMaterialDefines.prototype.reset = function () {
  35317. _super.prototype.reset.call(this);
  35318. this.ALPHATESTVALUE = 0.5;
  35319. this.PBR = true;
  35320. };
  35321. return PBRMaterialDefines;
  35322. }(BABYLON.MaterialDefines));
  35323. /**
  35324. * The Physically based material base class of BJS.
  35325. *
  35326. * This offers the main features of a standard PBR material.
  35327. * For more information, please refer to the documentation :
  35328. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35329. */
  35330. var PBRBaseMaterial = /** @class */ (function (_super) {
  35331. __extends(PBRBaseMaterial, _super);
  35332. /**
  35333. * Instantiates a new PBRMaterial instance.
  35334. *
  35335. * @param name The material name
  35336. * @param scene The scene the material will be use in.
  35337. */
  35338. function PBRBaseMaterial(name, scene) {
  35339. var _this = _super.call(this, name, scene) || this;
  35340. /**
  35341. * Intensity of the direct lights e.g. the four lights available in your scene.
  35342. * This impacts both the direct diffuse and specular highlights.
  35343. */
  35344. _this._directIntensity = 1.0;
  35345. /**
  35346. * Intensity of the emissive part of the material.
  35347. * This helps controlling the emissive effect without modifying the emissive color.
  35348. */
  35349. _this._emissiveIntensity = 1.0;
  35350. /**
  35351. * Intensity of the environment e.g. how much the environment will light the object
  35352. * either through harmonics for rough material or through the refelction for shiny ones.
  35353. */
  35354. _this._environmentIntensity = 1.0;
  35355. /**
  35356. * This is a special control allowing the reduction of the specular highlights coming from the
  35357. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35358. */
  35359. _this._specularIntensity = 1.0;
  35360. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  35361. /**
  35362. * Debug Control allowing disabling the bump map on this material.
  35363. */
  35364. _this._disableBumpMap = false;
  35365. /**
  35366. * AKA Occlusion Texture Intensity in other nomenclature.
  35367. */
  35368. _this._ambientTextureStrength = 1.0;
  35369. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  35370. /**
  35371. * AKA Diffuse Color in other nomenclature.
  35372. */
  35373. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  35374. /**
  35375. * AKA Specular Color in other nomenclature.
  35376. */
  35377. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35378. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  35379. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  35380. /**
  35381. * AKA Glossiness in other nomenclature.
  35382. */
  35383. _this._microSurface = 0.9;
  35384. /**
  35385. * source material index of refraction (IOR)' / 'destination material IOR.
  35386. */
  35387. _this._indexOfRefraction = 0.66;
  35388. /**
  35389. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35390. */
  35391. _this._invertRefractionY = false;
  35392. /**
  35393. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35394. * Materials half opaque for instance using refraction could benefit from this control.
  35395. */
  35396. _this._linkRefractionWithTransparency = false;
  35397. _this._useLightmapAsShadowmap = false;
  35398. /**
  35399. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  35400. */
  35401. _this._useAlphaFromAlbedoTexture = false;
  35402. /**
  35403. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35404. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35405. */
  35406. _this._useSpecularOverAlpha = true;
  35407. /**
  35408. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35409. */
  35410. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  35411. /**
  35412. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35413. */
  35414. _this._useRoughnessFromMetallicTextureAlpha = true;
  35415. /**
  35416. * Specifies if the metallic texture contains the roughness information in its green channel.
  35417. */
  35418. _this._useRoughnessFromMetallicTextureGreen = false;
  35419. /**
  35420. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35421. */
  35422. _this._useMetallnessFromMetallicTextureBlue = false;
  35423. /**
  35424. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35425. */
  35426. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  35427. /**
  35428. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35429. */
  35430. _this._useAmbientInGrayScale = false;
  35431. /**
  35432. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35433. * The material will try to infer what glossiness each pixel should be.
  35434. */
  35435. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  35436. /**
  35437. * BJS is using an harcoded light falloff based on a manually sets up range.
  35438. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35439. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35440. */
  35441. _this._usePhysicalLightFalloff = true;
  35442. /**
  35443. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35444. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35445. */
  35446. _this._useRadianceOverAlpha = true;
  35447. /**
  35448. * Allows using the bump map in parallax mode.
  35449. */
  35450. _this._useParallax = false;
  35451. /**
  35452. * Allows using the bump map in parallax occlusion mode.
  35453. */
  35454. _this._useParallaxOcclusion = false;
  35455. /**
  35456. * Controls the scale bias of the parallax mode.
  35457. */
  35458. _this._parallaxScaleBias = 0.05;
  35459. /**
  35460. * If sets to true, disables all the lights affecting the material.
  35461. */
  35462. _this._disableLighting = false;
  35463. /**
  35464. * Number of Simultaneous lights allowed on the material.
  35465. */
  35466. _this._maxSimultaneousLights = 4;
  35467. /**
  35468. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  35469. */
  35470. _this._invertNormalMapX = false;
  35471. /**
  35472. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  35473. */
  35474. _this._invertNormalMapY = false;
  35475. /**
  35476. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35477. */
  35478. _this._twoSidedLighting = false;
  35479. /**
  35480. * Defines the alpha limits in alpha test mode.
  35481. */
  35482. _this._alphaCutOff = 0.4;
  35483. /**
  35484. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35485. */
  35486. _this._forceAlphaTest = false;
  35487. /**
  35488. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35489. * And/Or occlude the blended part.
  35490. */
  35491. _this._useAlphaFresnel = false;
  35492. /**
  35493. * The transparency mode of the material.
  35494. */
  35495. _this._transparencyMode = null;
  35496. /**
  35497. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  35498. * from cos thetav and roughness:
  35499. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  35500. */
  35501. _this._environmentBRDFTexture = null;
  35502. /**
  35503. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  35504. */
  35505. _this._forceIrradianceInFragment = false;
  35506. /**
  35507. * Force normal to face away from face.
  35508. * (Temporary internal fix to remove before 3.1)
  35509. */
  35510. _this._forceNormalForward = false;
  35511. _this._renderTargets = new BABYLON.SmartArray(16);
  35512. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35513. // Setup the default processing configuration to the scene.
  35514. _this._attachImageProcessingConfiguration(null);
  35515. _this.getRenderTargetTextures = function () {
  35516. _this._renderTargets.reset();
  35517. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35518. _this._renderTargets.push(_this._reflectionTexture);
  35519. }
  35520. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35521. _this._renderTargets.push(_this._refractionTexture);
  35522. }
  35523. return _this._renderTargets;
  35524. };
  35525. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35526. return _this;
  35527. }
  35528. /**
  35529. * Attaches a new image processing configuration to the PBR Material.
  35530. * @param configuration
  35531. */
  35532. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35533. var _this = this;
  35534. if (configuration === this._imageProcessingConfiguration) {
  35535. return;
  35536. }
  35537. // Detaches observer.
  35538. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35539. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35540. }
  35541. // Pick the scene configuration if needed.
  35542. if (!configuration) {
  35543. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35544. }
  35545. else {
  35546. this._imageProcessingConfiguration = configuration;
  35547. }
  35548. // Attaches observer.
  35549. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35550. _this._markAllSubMeshesAsImageProcessingDirty();
  35551. });
  35552. };
  35553. PBRBaseMaterial.prototype.getClassName = function () {
  35554. return "PBRBaseMaterial";
  35555. };
  35556. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  35557. get: function () {
  35558. return this._useLogarithmicDepth;
  35559. },
  35560. set: function (value) {
  35561. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35562. },
  35563. enumerable: true,
  35564. configurable: true
  35565. });
  35566. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  35567. /**
  35568. * Gets the current transparency mode.
  35569. */
  35570. get: function () {
  35571. return this._transparencyMode;
  35572. },
  35573. /**
  35574. * Sets the transparency mode of the material.
  35575. */
  35576. set: function (value) {
  35577. if (this._transparencyMode === value) {
  35578. return;
  35579. }
  35580. this._transparencyMode = value;
  35581. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  35582. this._markAllSubMeshesAsTexturesDirty();
  35583. },
  35584. enumerable: true,
  35585. configurable: true
  35586. });
  35587. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  35588. /**
  35589. * Returns true if alpha blending should be disabled.
  35590. */
  35591. get: function () {
  35592. return (this._linkRefractionWithTransparency ||
  35593. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  35594. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  35595. },
  35596. enumerable: true,
  35597. configurable: true
  35598. });
  35599. /**
  35600. * Specifies whether or not this material should be rendered in alpha blend mode.
  35601. */
  35602. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  35603. if (this._disableAlphaBlending) {
  35604. return false;
  35605. }
  35606. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  35607. };
  35608. /**
  35609. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  35610. */
  35611. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  35612. if (this._disableAlphaBlending) {
  35613. return false;
  35614. }
  35615. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  35616. };
  35617. /**
  35618. * Specifies whether or not this material should be rendered in alpha test mode.
  35619. */
  35620. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  35621. if (this._forceAlphaTest) {
  35622. return true;
  35623. }
  35624. if (this._linkRefractionWithTransparency) {
  35625. return false;
  35626. }
  35627. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35628. };
  35629. /**
  35630. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  35631. */
  35632. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35633. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35634. };
  35635. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35636. return this._albedoTexture;
  35637. };
  35638. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35639. var _this = this;
  35640. if (subMesh.effect && this.isFrozen) {
  35641. if (this._wasPreviouslyReady) {
  35642. return true;
  35643. }
  35644. }
  35645. if (!subMesh._materialDefines) {
  35646. subMesh._materialDefines = new PBRMaterialDefines();
  35647. }
  35648. var scene = this.getScene();
  35649. var defines = subMesh._materialDefines;
  35650. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35651. if (defines._renderId === scene.getRenderId()) {
  35652. return true;
  35653. }
  35654. }
  35655. var engine = scene.getEngine();
  35656. // Lights
  35657. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35658. defines._needNormals = true;
  35659. // Textures
  35660. if (defines._areTexturesDirty) {
  35661. defines._needUVs = false;
  35662. if (scene.texturesEnabled) {
  35663. if (scene.getEngine().getCaps().textureLOD) {
  35664. defines.LODBASEDMICROSFURACE = true;
  35665. }
  35666. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35667. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35668. return false;
  35669. }
  35670. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35671. }
  35672. else {
  35673. defines.ALBEDO = false;
  35674. }
  35675. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35676. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35677. return false;
  35678. }
  35679. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35680. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35681. }
  35682. else {
  35683. defines.AMBIENT = false;
  35684. }
  35685. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35686. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35687. return false;
  35688. }
  35689. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35690. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35691. }
  35692. else {
  35693. defines.OPACITY = false;
  35694. }
  35695. var reflectionTexture = this._getReflectionTexture();
  35696. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35697. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35698. return false;
  35699. }
  35700. defines.REFLECTION = true;
  35701. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35702. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  35703. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35704. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35705. defines.INVERTCUBICMAP = true;
  35706. }
  35707. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35708. switch (reflectionTexture.coordinatesMode) {
  35709. case BABYLON.Texture.CUBIC_MODE:
  35710. case BABYLON.Texture.INVCUBIC_MODE:
  35711. defines.REFLECTIONMAP_CUBIC = true;
  35712. break;
  35713. case BABYLON.Texture.EXPLICIT_MODE:
  35714. defines.REFLECTIONMAP_EXPLICIT = true;
  35715. break;
  35716. case BABYLON.Texture.PLANAR_MODE:
  35717. defines.REFLECTIONMAP_PLANAR = true;
  35718. break;
  35719. case BABYLON.Texture.PROJECTION_MODE:
  35720. defines.REFLECTIONMAP_PROJECTION = true;
  35721. break;
  35722. case BABYLON.Texture.SKYBOX_MODE:
  35723. defines.REFLECTIONMAP_SKYBOX = true;
  35724. break;
  35725. case BABYLON.Texture.SPHERICAL_MODE:
  35726. defines.REFLECTIONMAP_SPHERICAL = true;
  35727. break;
  35728. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35729. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35730. break;
  35731. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35732. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35733. break;
  35734. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35735. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35736. break;
  35737. }
  35738. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35739. if (reflectionTexture.sphericalPolynomial) {
  35740. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35741. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35742. defines.USESPHERICALINVERTEX = false;
  35743. }
  35744. else {
  35745. defines.USESPHERICALINVERTEX = true;
  35746. }
  35747. }
  35748. }
  35749. }
  35750. else {
  35751. defines.REFLECTION = false;
  35752. defines.REFLECTIONMAP_3D = false;
  35753. defines.REFLECTIONMAP_SPHERICAL = false;
  35754. defines.REFLECTIONMAP_PLANAR = false;
  35755. defines.REFLECTIONMAP_CUBIC = false;
  35756. defines.REFLECTIONMAP_PROJECTION = false;
  35757. defines.REFLECTIONMAP_SKYBOX = false;
  35758. defines.REFLECTIONMAP_EXPLICIT = false;
  35759. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35760. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35761. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35762. defines.INVERTCUBICMAP = false;
  35763. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35764. defines.USESPHERICALINVERTEX = false;
  35765. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35766. defines.LODINREFLECTIONALPHA = false;
  35767. defines.GAMMAREFLECTION = false;
  35768. }
  35769. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35770. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35771. return false;
  35772. }
  35773. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35774. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35775. }
  35776. else {
  35777. defines.LIGHTMAP = false;
  35778. }
  35779. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35780. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35781. return false;
  35782. }
  35783. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35784. }
  35785. else {
  35786. defines.EMISSIVE = false;
  35787. }
  35788. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35789. if (this._metallicTexture) {
  35790. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35791. return false;
  35792. }
  35793. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35794. defines.METALLICWORKFLOW = true;
  35795. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35796. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35797. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35798. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35799. }
  35800. else if (this._reflectivityTexture) {
  35801. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35802. return false;
  35803. }
  35804. defines.METALLICWORKFLOW = false;
  35805. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35806. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35807. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35808. }
  35809. else {
  35810. defines.METALLICWORKFLOW = false;
  35811. defines.REFLECTIVITY = false;
  35812. }
  35813. if (this._microSurfaceTexture) {
  35814. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35815. return false;
  35816. }
  35817. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35818. }
  35819. else {
  35820. defines.MICROSURFACEMAP = false;
  35821. }
  35822. }
  35823. else {
  35824. defines.REFLECTIVITY = false;
  35825. defines.MICROSURFACEMAP = false;
  35826. }
  35827. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35828. // Bump texure can not be none blocking.
  35829. if (!this._bumpTexture.isReady()) {
  35830. return false;
  35831. }
  35832. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35833. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35834. defines.PARALLAX = true;
  35835. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  35836. }
  35837. else {
  35838. defines.PARALLAX = false;
  35839. }
  35840. }
  35841. else {
  35842. defines.BUMP = false;
  35843. }
  35844. var refractionTexture = this._getRefractionTexture();
  35845. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35846. if (!refractionTexture.isReadyOrNotBlocking()) {
  35847. return false;
  35848. }
  35849. defines.REFRACTION = true;
  35850. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35851. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35852. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35853. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35854. if (this._linkRefractionWithTransparency) {
  35855. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35856. }
  35857. }
  35858. else {
  35859. defines.REFRACTION = false;
  35860. }
  35861. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35862. // This is blocking.
  35863. if (!this._environmentBRDFTexture.isReady()) {
  35864. return false;
  35865. }
  35866. defines.ENVIRONMENTBRDF = true;
  35867. }
  35868. else {
  35869. defines.ENVIRONMENTBRDF = false;
  35870. }
  35871. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35872. defines.ALPHAFROMALBEDO = true;
  35873. }
  35874. else {
  35875. defines.ALPHAFROMALBEDO = false;
  35876. }
  35877. }
  35878. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35879. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  35880. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  35881. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35882. defines.METALLICWORKFLOW = true;
  35883. }
  35884. else {
  35885. defines.METALLICWORKFLOW = false;
  35886. }
  35887. if (!this.backFaceCulling && this._twoSidedLighting) {
  35888. defines.TWOSIDEDLIGHTING = true;
  35889. }
  35890. else {
  35891. defines.TWOSIDEDLIGHTING = false;
  35892. }
  35893. defines.ALPHATESTVALUE = this._alphaCutOff;
  35894. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35895. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  35896. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35897. }
  35898. if (defines._areImageProcessingDirty) {
  35899. if (!this._imageProcessingConfiguration.isReady()) {
  35900. return false;
  35901. }
  35902. this._imageProcessingConfiguration.prepareDefines(defines);
  35903. }
  35904. defines.FORCENORMALFORWARD = this._forceNormalForward;
  35905. // Misc.
  35906. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35907. // Values that need to be evaluated on every frame
  35908. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  35909. // Attribs
  35910. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE)) {
  35911. if (mesh) {
  35912. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35913. mesh.createNormals(true);
  35914. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35915. }
  35916. }
  35917. }
  35918. // Get correct effect
  35919. if (defines.isDirty) {
  35920. defines.markAsProcessed();
  35921. scene.resetCachedMaterial();
  35922. // Fallbacks
  35923. var fallbacks = new BABYLON.EffectFallbacks();
  35924. var fallbackRank = 0;
  35925. if (defines.USESPHERICALINVERTEX) {
  35926. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  35927. }
  35928. if (defines.FOG) {
  35929. fallbacks.addFallback(fallbackRank, "FOG");
  35930. }
  35931. if (defines.POINTSIZE) {
  35932. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  35933. }
  35934. if (defines.LOGARITHMICDEPTH) {
  35935. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  35936. }
  35937. if (defines.PARALLAX) {
  35938. fallbacks.addFallback(fallbackRank, "PARALLAX");
  35939. }
  35940. if (defines.PARALLAXOCCLUSION) {
  35941. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  35942. }
  35943. if (defines.ENVIRONMENTBRDF) {
  35944. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  35945. }
  35946. if (defines.TANGENT) {
  35947. fallbacks.addFallback(fallbackRank++, "TANGENT");
  35948. }
  35949. if (defines.BUMP) {
  35950. fallbacks.addFallback(fallbackRank++, "BUMP");
  35951. }
  35952. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  35953. if (defines.SPECULARTERM) {
  35954. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  35955. }
  35956. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  35957. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  35958. }
  35959. if (defines.LIGHTMAP) {
  35960. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  35961. }
  35962. if (defines.NORMAL) {
  35963. fallbacks.addFallback(fallbackRank++, "NORMAL");
  35964. }
  35965. if (defines.AMBIENT) {
  35966. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  35967. }
  35968. if (defines.EMISSIVE) {
  35969. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  35970. }
  35971. if (defines.VERTEXCOLOR) {
  35972. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  35973. }
  35974. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35975. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  35976. }
  35977. if (defines.MORPHTARGETS) {
  35978. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  35979. }
  35980. //Attributes
  35981. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35982. if (defines.NORMAL) {
  35983. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35984. }
  35985. if (defines.TANGENT) {
  35986. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35987. }
  35988. if (defines.UV1) {
  35989. attribs.push(BABYLON.VertexBuffer.UVKind);
  35990. }
  35991. if (defines.UV2) {
  35992. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35993. }
  35994. if (defines.VERTEXCOLOR) {
  35995. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35996. }
  35997. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35998. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35999. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36000. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  36001. "vFogInfos", "vFogColor", "pointSize",
  36002. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36003. "mBones",
  36004. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36005. "vLightingIntensity",
  36006. "logarithmicDepthConstant",
  36007. "vSphericalX", "vSphericalY", "vSphericalZ",
  36008. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  36009. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  36010. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  36011. "vTangentSpaceParams"
  36012. ];
  36013. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  36014. "bumpSampler", "lightmapSampler", "opacitySampler",
  36015. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  36016. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  36017. "microSurfaceSampler", "environmentBrdfSampler"];
  36018. var uniformBuffers = ["Material", "Scene"];
  36019. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36020. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36021. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36022. uniformsNames: uniforms,
  36023. uniformBuffersNames: uniformBuffers,
  36024. samplers: samplers,
  36025. defines: defines,
  36026. maxSimultaneousLights: this._maxSimultaneousLights
  36027. });
  36028. var onCompiled = function (effect) {
  36029. if (_this.onCompiled) {
  36030. _this.onCompiled(effect);
  36031. }
  36032. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  36033. };
  36034. var join = defines.toString();
  36035. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  36036. attributes: attribs,
  36037. uniformsNames: uniforms,
  36038. uniformBuffersNames: uniformBuffers,
  36039. samplers: samplers,
  36040. defines: join,
  36041. fallbacks: fallbacks,
  36042. onCompiled: onCompiled,
  36043. onError: this.onError,
  36044. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36045. }, engine), defines);
  36046. this.buildUniformLayout();
  36047. }
  36048. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36049. return false;
  36050. }
  36051. defines._renderId = scene.getRenderId();
  36052. this._wasPreviouslyReady = true;
  36053. return true;
  36054. };
  36055. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  36056. // Order is important !
  36057. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  36058. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  36059. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36060. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36061. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36062. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  36063. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  36064. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36065. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36066. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36067. this._uniformBuffer.addUniform("albedoMatrix", 16);
  36068. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36069. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36070. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36071. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36072. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  36073. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  36074. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36075. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36076. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36077. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36078. this._uniformBuffer.addUniform("vReflectionColor", 3);
  36079. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  36080. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  36081. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  36082. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  36083. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  36084. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36085. this._uniformBuffer.addUniform("pointSize", 1);
  36086. this._uniformBuffer.create();
  36087. };
  36088. PBRBaseMaterial.prototype.unbind = function () {
  36089. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36090. this._uniformBuffer.setTexture("reflectionSampler", null);
  36091. }
  36092. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36093. this._uniformBuffer.setTexture("refractionSampler", null);
  36094. }
  36095. _super.prototype.unbind.call(this);
  36096. };
  36097. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36098. this._activeEffect.setMatrix("world", world);
  36099. };
  36100. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36101. var scene = this.getScene();
  36102. var defines = subMesh._materialDefines;
  36103. if (!defines) {
  36104. return;
  36105. }
  36106. var effect = subMesh.effect;
  36107. if (!effect) {
  36108. return;
  36109. }
  36110. this._activeEffect = effect;
  36111. // Matrices
  36112. this.bindOnlyWorldMatrix(world);
  36113. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36114. // Bones
  36115. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  36116. var reflectionTexture = null;
  36117. if (mustRebind) {
  36118. this._uniformBuffer.bindToEffect(effect, "Material");
  36119. this.bindViewProjection(effect);
  36120. reflectionTexture = this._getReflectionTexture();
  36121. var refractionTexture = this._getRefractionTexture();
  36122. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36123. // Texture uniforms
  36124. if (scene.texturesEnabled) {
  36125. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36126. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  36127. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  36128. }
  36129. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36130. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  36131. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36132. }
  36133. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36134. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36135. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36136. }
  36137. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36138. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  36139. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  36140. var polynomials = reflectionTexture.sphericalPolynomial;
  36141. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  36142. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  36143. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  36144. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  36145. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  36146. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  36147. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  36148. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  36149. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  36150. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  36151. }
  36152. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  36153. }
  36154. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36155. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36156. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36157. }
  36158. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36159. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36160. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36161. }
  36162. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36163. if (this._metallicTexture) {
  36164. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  36165. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  36166. }
  36167. else if (this._reflectivityTexture) {
  36168. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  36169. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  36170. }
  36171. if (this._microSurfaceTexture) {
  36172. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  36173. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  36174. }
  36175. }
  36176. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36177. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  36178. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36179. if (scene._mirroredCameraPosition) {
  36180. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36181. }
  36182. else {
  36183. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36184. }
  36185. }
  36186. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36187. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  36188. var depth = 1.0;
  36189. if (!refractionTexture.isCube) {
  36190. if (refractionTexture.depth) {
  36191. depth = refractionTexture.depth;
  36192. }
  36193. }
  36194. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  36195. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  36196. }
  36197. }
  36198. // Point size
  36199. if (this.pointsCloud) {
  36200. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36201. }
  36202. // Colors
  36203. if (defines.METALLICWORKFLOW) {
  36204. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  36205. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  36206. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  36207. }
  36208. else {
  36209. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  36210. }
  36211. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  36212. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  36213. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  36214. // Misc
  36215. this._lightingInfos.x = this._directIntensity;
  36216. this._lightingInfos.y = this._emissiveIntensity;
  36217. this._lightingInfos.z = this._environmentIntensity;
  36218. this._lightingInfos.w = this._specularIntensity;
  36219. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  36220. }
  36221. // Textures
  36222. if (scene.texturesEnabled) {
  36223. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36224. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  36225. }
  36226. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36227. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  36228. }
  36229. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36230. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  36231. }
  36232. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36233. if (defines.LODBASEDMICROSFURACE) {
  36234. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  36235. }
  36236. else {
  36237. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  36238. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  36239. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  36240. }
  36241. }
  36242. if (defines.ENVIRONMENTBRDF) {
  36243. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  36244. }
  36245. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36246. if (defines.LODBASEDMICROSFURACE) {
  36247. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  36248. }
  36249. else {
  36250. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  36251. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  36252. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  36253. }
  36254. }
  36255. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36256. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  36257. }
  36258. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36259. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  36260. }
  36261. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36262. if (this._metallicTexture) {
  36263. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  36264. }
  36265. else if (this._reflectivityTexture) {
  36266. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  36267. }
  36268. if (this._microSurfaceTexture) {
  36269. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  36270. }
  36271. }
  36272. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36273. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  36274. }
  36275. }
  36276. // Clip plane
  36277. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  36278. // Colors
  36279. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  36280. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  36281. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  36282. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  36283. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36284. }
  36285. if (mustRebind || !this.isFrozen) {
  36286. // Lights
  36287. if (scene.lightsEnabled && !this._disableLighting) {
  36288. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  36289. }
  36290. // View
  36291. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  36292. this.bindView(effect);
  36293. }
  36294. // Fog
  36295. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  36296. // Morph targets
  36297. if (defines.NUM_MORPH_INFLUENCERS) {
  36298. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  36299. }
  36300. // image processing
  36301. this._imageProcessingConfiguration.bind(this._activeEffect);
  36302. // Log. depth
  36303. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  36304. }
  36305. this._uniformBuffer.update();
  36306. this._afterBind(mesh);
  36307. };
  36308. PBRBaseMaterial.prototype.getAnimatables = function () {
  36309. var results = [];
  36310. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  36311. results.push(this._albedoTexture);
  36312. }
  36313. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36314. results.push(this._ambientTexture);
  36315. }
  36316. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36317. results.push(this._opacityTexture);
  36318. }
  36319. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36320. results.push(this._reflectionTexture);
  36321. }
  36322. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36323. results.push(this._emissiveTexture);
  36324. }
  36325. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  36326. results.push(this._metallicTexture);
  36327. }
  36328. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  36329. results.push(this._reflectivityTexture);
  36330. }
  36331. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36332. results.push(this._bumpTexture);
  36333. }
  36334. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36335. results.push(this._lightmapTexture);
  36336. }
  36337. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36338. results.push(this._refractionTexture);
  36339. }
  36340. return results;
  36341. };
  36342. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  36343. if (this._reflectionTexture) {
  36344. return this._reflectionTexture;
  36345. }
  36346. return this.getScene().environmentTexture;
  36347. };
  36348. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  36349. if (this._refractionTexture) {
  36350. return this._refractionTexture;
  36351. }
  36352. if (this._linkRefractionWithTransparency) {
  36353. return this.getScene().environmentTexture;
  36354. }
  36355. return null;
  36356. };
  36357. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36358. if (forceDisposeTextures) {
  36359. if (this._albedoTexture) {
  36360. this._albedoTexture.dispose();
  36361. }
  36362. if (this._ambientTexture) {
  36363. this._ambientTexture.dispose();
  36364. }
  36365. if (this._opacityTexture) {
  36366. this._opacityTexture.dispose();
  36367. }
  36368. if (this._reflectionTexture) {
  36369. this._reflectionTexture.dispose();
  36370. }
  36371. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  36372. this._environmentBRDFTexture.dispose();
  36373. }
  36374. if (this._emissiveTexture) {
  36375. this._emissiveTexture.dispose();
  36376. }
  36377. if (this._metallicTexture) {
  36378. this._metallicTexture.dispose();
  36379. }
  36380. if (this._reflectivityTexture) {
  36381. this._reflectivityTexture.dispose();
  36382. }
  36383. if (this._bumpTexture) {
  36384. this._bumpTexture.dispose();
  36385. }
  36386. if (this._lightmapTexture) {
  36387. this._lightmapTexture.dispose();
  36388. }
  36389. if (this._refractionTexture) {
  36390. this._refractionTexture.dispose();
  36391. }
  36392. }
  36393. this._renderTargets.dispose();
  36394. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36395. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36396. }
  36397. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36398. };
  36399. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  36400. __decorate([
  36401. BABYLON.serializeAsImageProcessingConfiguration()
  36402. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  36403. __decorate([
  36404. BABYLON.serialize()
  36405. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  36406. __decorate([
  36407. BABYLON.serialize()
  36408. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  36409. return PBRBaseMaterial;
  36410. }(BABYLON.PushMaterial));
  36411. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  36412. })(BABYLON || (BABYLON = {}));
  36413. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  36414. var BABYLON;
  36415. (function (BABYLON) {
  36416. var Internals;
  36417. (function (Internals) {
  36418. /**
  36419. * The Physically based simple base material of BJS.
  36420. *
  36421. * This enables better naming and convention enforcements on top of the pbrMaterial.
  36422. * It is used as the base class for both the specGloss and metalRough conventions.
  36423. */
  36424. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  36425. __extends(PBRBaseSimpleMaterial, _super);
  36426. /**
  36427. * Instantiates a new PBRMaterial instance.
  36428. *
  36429. * @param name The material name
  36430. * @param scene The scene the material will be use in.
  36431. */
  36432. function PBRBaseSimpleMaterial(name, scene) {
  36433. var _this = _super.call(this, name, scene) || this;
  36434. /**
  36435. * Number of Simultaneous lights allowed on the material.
  36436. */
  36437. _this.maxSimultaneousLights = 4;
  36438. /**
  36439. * If sets to true, disables all the lights affecting the material.
  36440. */
  36441. _this.disableLighting = false;
  36442. /**
  36443. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36444. */
  36445. _this.invertNormalMapX = false;
  36446. /**
  36447. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36448. */
  36449. _this.invertNormalMapY = false;
  36450. /**
  36451. * Emissivie color used to self-illuminate the model.
  36452. */
  36453. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36454. /**
  36455. * Occlusion Channel Strenght.
  36456. */
  36457. _this.occlusionStrength = 1.0;
  36458. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36459. _this._useAlphaFromAlbedoTexture = true;
  36460. _this._useAmbientInGrayScale = true;
  36461. return _this;
  36462. }
  36463. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  36464. /**
  36465. * Gets the current double sided mode.
  36466. */
  36467. get: function () {
  36468. return this._twoSidedLighting;
  36469. },
  36470. /**
  36471. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36472. */
  36473. set: function (value) {
  36474. if (this._twoSidedLighting === value) {
  36475. return;
  36476. }
  36477. this._twoSidedLighting = value;
  36478. this.backFaceCulling = !value;
  36479. this._markAllSubMeshesAsTexturesDirty();
  36480. },
  36481. enumerable: true,
  36482. configurable: true
  36483. });
  36484. /**
  36485. * Return the active textures of the material.
  36486. */
  36487. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  36488. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36489. if (this.environmentTexture) {
  36490. activeTextures.push(this.environmentTexture);
  36491. }
  36492. if (this.normalTexture) {
  36493. activeTextures.push(this.normalTexture);
  36494. }
  36495. if (this.emissiveTexture) {
  36496. activeTextures.push(this.emissiveTexture);
  36497. }
  36498. if (this.occlusionTexture) {
  36499. activeTextures.push(this.occlusionTexture);
  36500. }
  36501. return activeTextures;
  36502. };
  36503. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  36504. return "PBRBaseSimpleMaterial";
  36505. };
  36506. __decorate([
  36507. BABYLON.serialize(),
  36508. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36509. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  36510. __decorate([
  36511. BABYLON.serialize(),
  36512. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36513. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  36514. __decorate([
  36515. BABYLON.serializeAsTexture(),
  36516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  36517. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  36518. __decorate([
  36519. BABYLON.serialize(),
  36520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36521. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  36522. __decorate([
  36523. BABYLON.serialize(),
  36524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36525. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  36526. __decorate([
  36527. BABYLON.serializeAsTexture(),
  36528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  36529. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  36530. __decorate([
  36531. BABYLON.serializeAsColor3("emissive"),
  36532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36533. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  36534. __decorate([
  36535. BABYLON.serializeAsTexture(),
  36536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36537. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  36538. __decorate([
  36539. BABYLON.serialize(),
  36540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  36541. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  36542. __decorate([
  36543. BABYLON.serializeAsTexture(),
  36544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  36545. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  36546. __decorate([
  36547. BABYLON.serialize(),
  36548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  36549. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  36550. __decorate([
  36551. BABYLON.serialize()
  36552. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  36553. return PBRBaseSimpleMaterial;
  36554. }(BABYLON.PBRBaseMaterial));
  36555. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  36556. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36557. })(BABYLON || (BABYLON = {}));
  36558. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  36559. var BABYLON;
  36560. (function (BABYLON) {
  36561. /**
  36562. * The Physically based material of BJS.
  36563. *
  36564. * This offers the main features of a standard PBR material.
  36565. * For more information, please refer to the documentation :
  36566. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36567. */
  36568. var PBRMaterial = /** @class */ (function (_super) {
  36569. __extends(PBRMaterial, _super);
  36570. /**
  36571. * Instantiates a new PBRMaterial instance.
  36572. *
  36573. * @param name The material name
  36574. * @param scene The scene the material will be use in.
  36575. */
  36576. function PBRMaterial(name, scene) {
  36577. var _this = _super.call(this, name, scene) || this;
  36578. /**
  36579. * Intensity of the direct lights e.g. the four lights available in your scene.
  36580. * This impacts both the direct diffuse and specular highlights.
  36581. */
  36582. _this.directIntensity = 1.0;
  36583. /**
  36584. * Intensity of the emissive part of the material.
  36585. * This helps controlling the emissive effect without modifying the emissive color.
  36586. */
  36587. _this.emissiveIntensity = 1.0;
  36588. /**
  36589. * Intensity of the environment e.g. how much the environment will light the object
  36590. * either through harmonics for rough material or through the refelction for shiny ones.
  36591. */
  36592. _this.environmentIntensity = 1.0;
  36593. /**
  36594. * This is a special control allowing the reduction of the specular highlights coming from the
  36595. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36596. */
  36597. _this.specularIntensity = 1.0;
  36598. /**
  36599. * Debug Control allowing disabling the bump map on this material.
  36600. */
  36601. _this.disableBumpMap = false;
  36602. /**
  36603. * AKA Occlusion Texture Intensity in other nomenclature.
  36604. */
  36605. _this.ambientTextureStrength = 1.0;
  36606. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36607. /**
  36608. * AKA Diffuse Color in other nomenclature.
  36609. */
  36610. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36611. /**
  36612. * AKA Specular Color in other nomenclature.
  36613. */
  36614. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36615. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36616. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36617. /**
  36618. * AKA Glossiness in other nomenclature.
  36619. */
  36620. _this.microSurface = 1.0;
  36621. /**
  36622. * source material index of refraction (IOR)' / 'destination material IOR.
  36623. */
  36624. _this.indexOfRefraction = 0.66;
  36625. /**
  36626. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36627. */
  36628. _this.invertRefractionY = false;
  36629. /**
  36630. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36631. * Materials half opaque for instance using refraction could benefit from this control.
  36632. */
  36633. _this.linkRefractionWithTransparency = false;
  36634. _this.useLightmapAsShadowmap = false;
  36635. /**
  36636. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36637. */
  36638. _this.useAlphaFromAlbedoTexture = false;
  36639. /**
  36640. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36641. */
  36642. _this.forceAlphaTest = false;
  36643. /**
  36644. * Defines the alpha limits in alpha test mode.
  36645. */
  36646. _this.alphaCutOff = 0.4;
  36647. /**
  36648. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36649. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36650. */
  36651. _this.useSpecularOverAlpha = true;
  36652. /**
  36653. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36654. */
  36655. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36656. /**
  36657. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36658. */
  36659. _this.useRoughnessFromMetallicTextureAlpha = true;
  36660. /**
  36661. * Specifies if the metallic texture contains the roughness information in its green channel.
  36662. */
  36663. _this.useRoughnessFromMetallicTextureGreen = false;
  36664. /**
  36665. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36666. */
  36667. _this.useMetallnessFromMetallicTextureBlue = false;
  36668. /**
  36669. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36670. */
  36671. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36672. /**
  36673. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36674. */
  36675. _this.useAmbientInGrayScale = false;
  36676. /**
  36677. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36678. * The material will try to infer what glossiness each pixel should be.
  36679. */
  36680. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36681. /**
  36682. * BJS is using an harcoded light falloff based on a manually sets up range.
  36683. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36684. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36685. */
  36686. _this.usePhysicalLightFalloff = true;
  36687. /**
  36688. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36689. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36690. */
  36691. _this.useRadianceOverAlpha = true;
  36692. /**
  36693. * Allows using the bump map in parallax mode.
  36694. */
  36695. _this.useParallax = false;
  36696. /**
  36697. * Allows using the bump map in parallax occlusion mode.
  36698. */
  36699. _this.useParallaxOcclusion = false;
  36700. /**
  36701. * Controls the scale bias of the parallax mode.
  36702. */
  36703. _this.parallaxScaleBias = 0.05;
  36704. /**
  36705. * If sets to true, disables all the lights affecting the material.
  36706. */
  36707. _this.disableLighting = false;
  36708. /**
  36709. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36710. */
  36711. _this.forceIrradianceInFragment = false;
  36712. /**
  36713. * Number of Simultaneous lights allowed on the material.
  36714. */
  36715. _this.maxSimultaneousLights = 4;
  36716. /**
  36717. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36718. */
  36719. _this.invertNormalMapX = false;
  36720. /**
  36721. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36722. */
  36723. _this.invertNormalMapY = false;
  36724. /**
  36725. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36726. */
  36727. _this.twoSidedLighting = false;
  36728. /**
  36729. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36730. * And/Or occlude the blended part.
  36731. */
  36732. _this.useAlphaFresnel = false;
  36733. /**
  36734. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36735. * And/Or occlude the blended part.
  36736. */
  36737. _this.environmentBRDFTexture = null;
  36738. /**
  36739. * Force normal to face away from face.
  36740. * (Temporary internal fix to remove before 3.1)
  36741. */
  36742. _this.forceNormalForward = false;
  36743. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36744. return _this;
  36745. }
  36746. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36747. /**
  36748. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36749. */
  36750. get: function () {
  36751. return this._PBRMATERIAL_OPAQUE;
  36752. },
  36753. enumerable: true,
  36754. configurable: true
  36755. });
  36756. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36757. /**
  36758. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36759. */
  36760. get: function () {
  36761. return this._PBRMATERIAL_ALPHATEST;
  36762. },
  36763. enumerable: true,
  36764. configurable: true
  36765. });
  36766. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36767. /**
  36768. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36769. */
  36770. get: function () {
  36771. return this._PBRMATERIAL_ALPHABLEND;
  36772. },
  36773. enumerable: true,
  36774. configurable: true
  36775. });
  36776. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36777. /**
  36778. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36779. * They are also discarded below the alpha cutoff threshold to improve performances.
  36780. */
  36781. get: function () {
  36782. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36783. },
  36784. enumerable: true,
  36785. configurable: true
  36786. });
  36787. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36788. /**
  36789. * Gets the image processing configuration used either in this material.
  36790. */
  36791. get: function () {
  36792. return this._imageProcessingConfiguration;
  36793. },
  36794. /**
  36795. * Sets the Default image processing configuration used either in the this material.
  36796. *
  36797. * If sets to null, the scene one is in use.
  36798. */
  36799. set: function (value) {
  36800. this._attachImageProcessingConfiguration(value);
  36801. // Ensure the effect will be rebuilt.
  36802. this._markAllSubMeshesAsTexturesDirty();
  36803. },
  36804. enumerable: true,
  36805. configurable: true
  36806. });
  36807. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36808. /**
  36809. * Gets wether the color curves effect is enabled.
  36810. */
  36811. get: function () {
  36812. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36813. },
  36814. /**
  36815. * Sets wether the color curves effect is enabled.
  36816. */
  36817. set: function (value) {
  36818. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36819. },
  36820. enumerable: true,
  36821. configurable: true
  36822. });
  36823. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36824. /**
  36825. * Gets wether the color grading effect is enabled.
  36826. */
  36827. get: function () {
  36828. return this.imageProcessingConfiguration.colorGradingEnabled;
  36829. },
  36830. /**
  36831. * Gets wether the color grading effect is enabled.
  36832. */
  36833. set: function (value) {
  36834. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36835. },
  36836. enumerable: true,
  36837. configurable: true
  36838. });
  36839. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36840. /**
  36841. * Gets wether tonemapping is enabled or not.
  36842. */
  36843. get: function () {
  36844. return this._imageProcessingConfiguration.toneMappingEnabled;
  36845. },
  36846. /**
  36847. * Sets wether tonemapping is enabled or not
  36848. */
  36849. set: function (value) {
  36850. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36851. },
  36852. enumerable: true,
  36853. configurable: true
  36854. });
  36855. ;
  36856. ;
  36857. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36858. /**
  36859. * The camera exposure used on this material.
  36860. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36861. * This corresponds to a photographic exposure.
  36862. */
  36863. get: function () {
  36864. return this._imageProcessingConfiguration.exposure;
  36865. },
  36866. /**
  36867. * The camera exposure used on this material.
  36868. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36869. * This corresponds to a photographic exposure.
  36870. */
  36871. set: function (value) {
  36872. this._imageProcessingConfiguration.exposure = value;
  36873. },
  36874. enumerable: true,
  36875. configurable: true
  36876. });
  36877. ;
  36878. ;
  36879. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36880. /**
  36881. * Gets The camera contrast used on this material.
  36882. */
  36883. get: function () {
  36884. return this._imageProcessingConfiguration.contrast;
  36885. },
  36886. /**
  36887. * Sets The camera contrast used on this material.
  36888. */
  36889. set: function (value) {
  36890. this._imageProcessingConfiguration.contrast = value;
  36891. },
  36892. enumerable: true,
  36893. configurable: true
  36894. });
  36895. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36896. /**
  36897. * Gets the Color Grading 2D Lookup Texture.
  36898. */
  36899. get: function () {
  36900. return this._imageProcessingConfiguration.colorGradingTexture;
  36901. },
  36902. /**
  36903. * Sets the Color Grading 2D Lookup Texture.
  36904. */
  36905. set: function (value) {
  36906. this._imageProcessingConfiguration.colorGradingTexture = value;
  36907. },
  36908. enumerable: true,
  36909. configurable: true
  36910. });
  36911. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36912. /**
  36913. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36914. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36915. * 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;
  36916. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36917. */
  36918. get: function () {
  36919. return this._imageProcessingConfiguration.colorCurves;
  36920. },
  36921. /**
  36922. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36923. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36924. * 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;
  36925. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36926. */
  36927. set: function (value) {
  36928. this._imageProcessingConfiguration.colorCurves = value;
  36929. },
  36930. enumerable: true,
  36931. configurable: true
  36932. });
  36933. PBRMaterial.prototype.getClassName = function () {
  36934. return "PBRMaterial";
  36935. };
  36936. PBRMaterial.prototype.getActiveTextures = function () {
  36937. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36938. if (this._albedoTexture) {
  36939. activeTextures.push(this._albedoTexture);
  36940. }
  36941. if (this._ambientTexture) {
  36942. activeTextures.push(this._ambientTexture);
  36943. }
  36944. if (this._opacityTexture) {
  36945. activeTextures.push(this._opacityTexture);
  36946. }
  36947. if (this._reflectionTexture) {
  36948. activeTextures.push(this._reflectionTexture);
  36949. }
  36950. if (this._emissiveTexture) {
  36951. activeTextures.push(this._emissiveTexture);
  36952. }
  36953. if (this._reflectivityTexture) {
  36954. activeTextures.push(this._reflectivityTexture);
  36955. }
  36956. if (this._metallicTexture) {
  36957. activeTextures.push(this._metallicTexture);
  36958. }
  36959. if (this._microSurfaceTexture) {
  36960. activeTextures.push(this._microSurfaceTexture);
  36961. }
  36962. if (this._bumpTexture) {
  36963. activeTextures.push(this._bumpTexture);
  36964. }
  36965. if (this._lightmapTexture) {
  36966. activeTextures.push(this._lightmapTexture);
  36967. }
  36968. if (this._refractionTexture) {
  36969. activeTextures.push(this._refractionTexture);
  36970. }
  36971. return activeTextures;
  36972. };
  36973. PBRMaterial.prototype.hasTexture = function (texture) {
  36974. if (_super.prototype.hasTexture.call(this, texture)) {
  36975. return true;
  36976. }
  36977. if (this._albedoTexture === texture) {
  36978. return true;
  36979. }
  36980. if (this._ambientTexture === texture) {
  36981. return true;
  36982. }
  36983. if (this._opacityTexture === texture) {
  36984. return true;
  36985. }
  36986. if (this._reflectionTexture === texture) {
  36987. return true;
  36988. }
  36989. if (this._reflectivityTexture === texture) {
  36990. return true;
  36991. }
  36992. if (this._metallicTexture === texture) {
  36993. return true;
  36994. }
  36995. if (this._microSurfaceTexture === texture) {
  36996. return true;
  36997. }
  36998. if (this._bumpTexture === texture) {
  36999. return true;
  37000. }
  37001. if (this._lightmapTexture === texture) {
  37002. return true;
  37003. }
  37004. if (this._refractionTexture === texture) {
  37005. return true;
  37006. }
  37007. return false;
  37008. };
  37009. PBRMaterial.prototype.clone = function (name) {
  37010. var _this = this;
  37011. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  37012. clone.id = name;
  37013. clone.name = name;
  37014. return clone;
  37015. };
  37016. PBRMaterial.prototype.serialize = function () {
  37017. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37018. serializationObject.customType = "BABYLON.PBRMaterial";
  37019. return serializationObject;
  37020. };
  37021. // Statics
  37022. PBRMaterial.Parse = function (source, scene, rootUrl) {
  37023. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  37024. };
  37025. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  37026. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  37027. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  37028. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  37029. __decorate([
  37030. BABYLON.serialize(),
  37031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37032. ], PBRMaterial.prototype, "directIntensity", void 0);
  37033. __decorate([
  37034. BABYLON.serialize(),
  37035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37036. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  37037. __decorate([
  37038. BABYLON.serialize(),
  37039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37040. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  37041. __decorate([
  37042. BABYLON.serialize(),
  37043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37044. ], PBRMaterial.prototype, "specularIntensity", void 0);
  37045. __decorate([
  37046. BABYLON.serialize(),
  37047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37048. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  37049. __decorate([
  37050. BABYLON.serializeAsTexture(),
  37051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37052. ], PBRMaterial.prototype, "albedoTexture", void 0);
  37053. __decorate([
  37054. BABYLON.serializeAsTexture(),
  37055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37056. ], PBRMaterial.prototype, "ambientTexture", void 0);
  37057. __decorate([
  37058. BABYLON.serialize(),
  37059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37060. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  37061. __decorate([
  37062. BABYLON.serializeAsTexture(),
  37063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37064. ], PBRMaterial.prototype, "opacityTexture", void 0);
  37065. __decorate([
  37066. BABYLON.serializeAsTexture(),
  37067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37068. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  37069. __decorate([
  37070. BABYLON.serializeAsTexture(),
  37071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37072. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  37073. __decorate([
  37074. BABYLON.serializeAsTexture(),
  37075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37076. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  37077. __decorate([
  37078. BABYLON.serializeAsTexture(),
  37079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37080. ], PBRMaterial.prototype, "metallicTexture", void 0);
  37081. __decorate([
  37082. BABYLON.serialize(),
  37083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37084. ], PBRMaterial.prototype, "metallic", void 0);
  37085. __decorate([
  37086. BABYLON.serialize(),
  37087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37088. ], PBRMaterial.prototype, "roughness", void 0);
  37089. __decorate([
  37090. BABYLON.serializeAsTexture(),
  37091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37092. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  37093. __decorate([
  37094. BABYLON.serializeAsTexture(),
  37095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37096. ], PBRMaterial.prototype, "bumpTexture", void 0);
  37097. __decorate([
  37098. BABYLON.serializeAsTexture(),
  37099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37100. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  37101. __decorate([
  37102. BABYLON.serializeAsTexture(),
  37103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37104. ], PBRMaterial.prototype, "refractionTexture", void 0);
  37105. __decorate([
  37106. BABYLON.serializeAsColor3("ambient"),
  37107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37108. ], PBRMaterial.prototype, "ambientColor", void 0);
  37109. __decorate([
  37110. BABYLON.serializeAsColor3("albedo"),
  37111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37112. ], PBRMaterial.prototype, "albedoColor", void 0);
  37113. __decorate([
  37114. BABYLON.serializeAsColor3("reflectivity"),
  37115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37116. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  37117. __decorate([
  37118. BABYLON.serializeAsColor3("reflection"),
  37119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37120. ], PBRMaterial.prototype, "reflectionColor", void 0);
  37121. __decorate([
  37122. BABYLON.serializeAsColor3("emissive"),
  37123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37124. ], PBRMaterial.prototype, "emissiveColor", void 0);
  37125. __decorate([
  37126. BABYLON.serialize(),
  37127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37128. ], PBRMaterial.prototype, "microSurface", void 0);
  37129. __decorate([
  37130. BABYLON.serialize(),
  37131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37132. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  37133. __decorate([
  37134. BABYLON.serialize(),
  37135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37136. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  37137. __decorate([
  37138. BABYLON.serialize(),
  37139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37140. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  37141. __decorate([
  37142. BABYLON.serialize(),
  37143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37144. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37145. __decorate([
  37146. BABYLON.serialize(),
  37147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37148. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  37149. __decorate([
  37150. BABYLON.serialize(),
  37151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37152. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  37153. __decorate([
  37154. BABYLON.serialize(),
  37155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37156. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  37157. __decorate([
  37158. BABYLON.serialize(),
  37159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37160. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  37161. __decorate([
  37162. BABYLON.serialize(),
  37163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37164. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  37165. __decorate([
  37166. BABYLON.serialize(),
  37167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37168. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  37169. __decorate([
  37170. BABYLON.serialize(),
  37171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37172. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  37173. __decorate([
  37174. BABYLON.serialize(),
  37175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37176. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  37177. __decorate([
  37178. BABYLON.serialize(),
  37179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37180. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  37181. __decorate([
  37182. BABYLON.serialize(),
  37183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37184. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  37185. __decorate([
  37186. BABYLON.serialize(),
  37187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37188. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  37189. __decorate([
  37190. BABYLON.serialize(),
  37191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37192. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  37193. __decorate([
  37194. BABYLON.serialize(),
  37195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37196. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  37197. __decorate([
  37198. BABYLON.serialize(),
  37199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37200. ], PBRMaterial.prototype, "useParallax", void 0);
  37201. __decorate([
  37202. BABYLON.serialize(),
  37203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37204. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  37205. __decorate([
  37206. BABYLON.serialize(),
  37207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37208. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  37209. __decorate([
  37210. BABYLON.serialize(),
  37211. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37212. ], PBRMaterial.prototype, "disableLighting", void 0);
  37213. __decorate([
  37214. BABYLON.serialize(),
  37215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37216. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  37217. __decorate([
  37218. BABYLON.serialize(),
  37219. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37220. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  37221. __decorate([
  37222. BABYLON.serialize(),
  37223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37224. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  37225. __decorate([
  37226. BABYLON.serialize(),
  37227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37228. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  37229. __decorate([
  37230. BABYLON.serialize(),
  37231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37232. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  37233. __decorate([
  37234. BABYLON.serialize(),
  37235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37236. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  37237. __decorate([
  37238. BABYLON.serializeAsTexture(),
  37239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37240. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  37241. __decorate([
  37242. BABYLON.serialize(),
  37243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37244. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  37245. return PBRMaterial;
  37246. }(BABYLON.PBRBaseMaterial));
  37247. BABYLON.PBRMaterial = PBRMaterial;
  37248. })(BABYLON || (BABYLON = {}));
  37249. //# sourceMappingURL=babylon.pbrMaterial.js.map
  37250. var BABYLON;
  37251. (function (BABYLON) {
  37252. /**
  37253. * The PBR material of BJS following the metal roughness convention.
  37254. *
  37255. * This fits to the PBR convention in the GLTF definition:
  37256. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  37257. */
  37258. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  37259. __extends(PBRMetallicRoughnessMaterial, _super);
  37260. /**
  37261. * Instantiates a new PBRMetalRoughnessMaterial instance.
  37262. *
  37263. * @param name The material name
  37264. * @param scene The scene the material will be use in.
  37265. */
  37266. function PBRMetallicRoughnessMaterial(name, scene) {
  37267. var _this = _super.call(this, name, scene) || this;
  37268. _this._useRoughnessFromMetallicTextureAlpha = false;
  37269. _this._useRoughnessFromMetallicTextureGreen = true;
  37270. _this._useMetallnessFromMetallicTextureBlue = true;
  37271. return _this;
  37272. }
  37273. /**
  37274. * Return the currrent class name of the material.
  37275. */
  37276. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  37277. return "PBRMetallicRoughnessMaterial";
  37278. };
  37279. /**
  37280. * Return the active textures of the material.
  37281. */
  37282. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  37283. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37284. if (this.baseTexture) {
  37285. activeTextures.push(this.baseTexture);
  37286. }
  37287. if (this.metallicRoughnessTexture) {
  37288. activeTextures.push(this.metallicRoughnessTexture);
  37289. }
  37290. return activeTextures;
  37291. };
  37292. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  37293. if (_super.prototype.hasTexture.call(this, texture)) {
  37294. return true;
  37295. }
  37296. if (this.baseTexture === texture) {
  37297. return true;
  37298. }
  37299. if (this.metallicRoughnessTexture === texture) {
  37300. return true;
  37301. }
  37302. return false;
  37303. };
  37304. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  37305. var _this = this;
  37306. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  37307. clone.id = name;
  37308. clone.name = name;
  37309. return clone;
  37310. };
  37311. /**
  37312. * Serialize the material to a parsable JSON object.
  37313. */
  37314. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  37315. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37316. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  37317. return serializationObject;
  37318. };
  37319. /**
  37320. * Parses a JSON object correponding to the serialize function.
  37321. */
  37322. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  37323. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  37324. };
  37325. __decorate([
  37326. BABYLON.serializeAsColor3(),
  37327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37328. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  37329. __decorate([
  37330. BABYLON.serializeAsTexture(),
  37331. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37332. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  37333. __decorate([
  37334. BABYLON.serialize(),
  37335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37336. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  37337. __decorate([
  37338. BABYLON.serialize(),
  37339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37340. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  37341. __decorate([
  37342. BABYLON.serializeAsTexture(),
  37343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  37344. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  37345. return PBRMetallicRoughnessMaterial;
  37346. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37347. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  37348. })(BABYLON || (BABYLON = {}));
  37349. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  37350. var BABYLON;
  37351. (function (BABYLON) {
  37352. /**
  37353. * The PBR material of BJS following the specular glossiness convention.
  37354. *
  37355. * This fits to the PBR convention in the GLTF definition:
  37356. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  37357. */
  37358. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  37359. __extends(PBRSpecularGlossinessMaterial, _super);
  37360. /**
  37361. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  37362. *
  37363. * @param name The material name
  37364. * @param scene The scene the material will be use in.
  37365. */
  37366. function PBRSpecularGlossinessMaterial(name, scene) {
  37367. var _this = _super.call(this, name, scene) || this;
  37368. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  37369. return _this;
  37370. }
  37371. /**
  37372. * Return the currrent class name of the material.
  37373. */
  37374. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  37375. return "PBRSpecularGlossinessMaterial";
  37376. };
  37377. /**
  37378. * Return the active textures of the material.
  37379. */
  37380. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  37381. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37382. if (this.diffuseTexture) {
  37383. activeTextures.push(this.diffuseTexture);
  37384. }
  37385. if (this.specularGlossinessTexture) {
  37386. activeTextures.push(this.specularGlossinessTexture);
  37387. }
  37388. return activeTextures;
  37389. };
  37390. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  37391. if (_super.prototype.hasTexture.call(this, texture)) {
  37392. return true;
  37393. }
  37394. if (this.diffuseTexture === texture) {
  37395. return true;
  37396. }
  37397. if (this.specularGlossinessTexture === texture) {
  37398. return true;
  37399. }
  37400. return false;
  37401. };
  37402. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  37403. var _this = this;
  37404. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  37405. clone.id = name;
  37406. clone.name = name;
  37407. return clone;
  37408. };
  37409. /**
  37410. * Serialize the material to a parsable JSON object.
  37411. */
  37412. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  37413. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37414. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  37415. return serializationObject;
  37416. };
  37417. /**
  37418. * Parses a JSON object correponding to the serialize function.
  37419. */
  37420. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  37421. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  37422. };
  37423. __decorate([
  37424. BABYLON.serializeAsColor3("diffuse"),
  37425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37426. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  37427. __decorate([
  37428. BABYLON.serializeAsTexture(),
  37429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37430. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  37431. __decorate([
  37432. BABYLON.serializeAsColor3("specular"),
  37433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  37434. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  37435. __decorate([
  37436. BABYLON.serialize(),
  37437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  37438. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  37439. __decorate([
  37440. BABYLON.serializeAsTexture(),
  37441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  37442. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  37443. return PBRSpecularGlossinessMaterial;
  37444. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37445. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  37446. })(BABYLON || (BABYLON = {}));
  37447. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  37448. var BABYLON;
  37449. (function (BABYLON) {
  37450. BABYLON.CameraInputTypes = {};
  37451. var CameraInputsManager = /** @class */ (function () {
  37452. function CameraInputsManager(camera) {
  37453. this.attached = {};
  37454. this.camera = camera;
  37455. this.checkInputs = function () { };
  37456. }
  37457. CameraInputsManager.prototype.add = function (input) {
  37458. var type = input.getSimpleName();
  37459. if (this.attached[type]) {
  37460. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  37461. return;
  37462. }
  37463. this.attached[type] = input;
  37464. input.camera = this.camera;
  37465. //for checkInputs, we are dynamically creating a function
  37466. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  37467. if (input.checkInputs) {
  37468. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37469. }
  37470. if (this.attachedElement) {
  37471. input.attachControl(this.attachedElement);
  37472. }
  37473. };
  37474. CameraInputsManager.prototype.remove = function (inputToRemove) {
  37475. for (var cam in this.attached) {
  37476. var input = this.attached[cam];
  37477. if (input === inputToRemove) {
  37478. input.detachControl(this.attachedElement);
  37479. input.camera = null;
  37480. delete this.attached[cam];
  37481. this.rebuildInputCheck();
  37482. }
  37483. }
  37484. };
  37485. CameraInputsManager.prototype.removeByType = function (inputType) {
  37486. for (var cam in this.attached) {
  37487. var input = this.attached[cam];
  37488. if (input.getClassName() === inputType) {
  37489. input.detachControl(this.attachedElement);
  37490. input.camera = null;
  37491. delete this.attached[cam];
  37492. this.rebuildInputCheck();
  37493. }
  37494. }
  37495. };
  37496. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  37497. var current = this.checkInputs;
  37498. return function () {
  37499. current();
  37500. fn();
  37501. };
  37502. };
  37503. CameraInputsManager.prototype.attachInput = function (input) {
  37504. if (this.attachedElement) {
  37505. input.attachControl(this.attachedElement, this.noPreventDefault);
  37506. }
  37507. };
  37508. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  37509. if (noPreventDefault === void 0) { noPreventDefault = false; }
  37510. if (this.attachedElement) {
  37511. return;
  37512. }
  37513. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37514. this.attachedElement = element;
  37515. this.noPreventDefault = noPreventDefault;
  37516. for (var cam in this.attached) {
  37517. this.attached[cam].attachControl(element, noPreventDefault);
  37518. }
  37519. };
  37520. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  37521. if (disconnect === void 0) { disconnect = false; }
  37522. if (this.attachedElement !== element) {
  37523. return;
  37524. }
  37525. for (var cam in this.attached) {
  37526. this.attached[cam].detachControl(element);
  37527. if (disconnect) {
  37528. this.attached[cam].camera = null;
  37529. }
  37530. }
  37531. this.attachedElement = null;
  37532. };
  37533. CameraInputsManager.prototype.rebuildInputCheck = function () {
  37534. this.checkInputs = function () { };
  37535. for (var cam in this.attached) {
  37536. var input = this.attached[cam];
  37537. if (input.checkInputs) {
  37538. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37539. }
  37540. }
  37541. };
  37542. CameraInputsManager.prototype.clear = function () {
  37543. if (this.attachedElement) {
  37544. this.detachElement(this.attachedElement, true);
  37545. }
  37546. this.attached = {};
  37547. this.attachedElement = null;
  37548. this.checkInputs = function () { };
  37549. };
  37550. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  37551. var inputs = {};
  37552. for (var cam in this.attached) {
  37553. var input = this.attached[cam];
  37554. var res = BABYLON.SerializationHelper.Serialize(input);
  37555. inputs[input.getClassName()] = res;
  37556. }
  37557. serializedCamera.inputsmgr = inputs;
  37558. };
  37559. CameraInputsManager.prototype.parse = function (parsedCamera) {
  37560. var parsedInputs = parsedCamera.inputsmgr;
  37561. if (parsedInputs) {
  37562. this.clear();
  37563. for (var n in parsedInputs) {
  37564. var construct = BABYLON.CameraInputTypes[n];
  37565. if (construct) {
  37566. var parsedinput = parsedInputs[n];
  37567. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  37568. this.add(input);
  37569. }
  37570. }
  37571. }
  37572. else {
  37573. //2016-03-08 this part is for managing backward compatibility
  37574. for (var n in this.attached) {
  37575. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  37576. if (construct) {
  37577. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  37578. this.remove(this.attached[n]);
  37579. this.add(input);
  37580. }
  37581. }
  37582. }
  37583. };
  37584. return CameraInputsManager;
  37585. }());
  37586. BABYLON.CameraInputsManager = CameraInputsManager;
  37587. })(BABYLON || (BABYLON = {}));
  37588. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  37589. var BABYLON;
  37590. (function (BABYLON) {
  37591. var FreeCameraMouseInput = /** @class */ (function () {
  37592. function FreeCameraMouseInput(touchEnabled) {
  37593. if (touchEnabled === void 0) { touchEnabled = true; }
  37594. this.touchEnabled = touchEnabled;
  37595. this.buttons = [0, 1, 2];
  37596. this.angularSensibility = 2000.0;
  37597. this.previousPosition = null;
  37598. }
  37599. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  37600. var _this = this;
  37601. var engine = this.camera.getEngine();
  37602. if (!this._pointerInput) {
  37603. this._pointerInput = function (p, s) {
  37604. var evt = p.event;
  37605. if (engine.isInVRExclusivePointerMode) {
  37606. return;
  37607. }
  37608. if (!_this.touchEnabled && evt.pointerType === "touch") {
  37609. return;
  37610. }
  37611. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37612. return;
  37613. }
  37614. var srcElement = (evt.srcElement || evt.target);
  37615. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37616. try {
  37617. srcElement.setPointerCapture(evt.pointerId);
  37618. }
  37619. catch (e) {
  37620. //Nothing to do with the error. Execution will continue.
  37621. }
  37622. _this.previousPosition = {
  37623. x: evt.clientX,
  37624. y: evt.clientY
  37625. };
  37626. if (!noPreventDefault) {
  37627. evt.preventDefault();
  37628. element.focus();
  37629. }
  37630. }
  37631. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37632. try {
  37633. srcElement.releasePointerCapture(evt.pointerId);
  37634. }
  37635. catch (e) {
  37636. //Nothing to do with the error.
  37637. }
  37638. _this.previousPosition = null;
  37639. if (!noPreventDefault) {
  37640. evt.preventDefault();
  37641. }
  37642. }
  37643. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37644. if (!_this.previousPosition || engine.isPointerLock) {
  37645. return;
  37646. }
  37647. var offsetX = evt.clientX - _this.previousPosition.x;
  37648. var offsetY = evt.clientY - _this.previousPosition.y;
  37649. if (_this.camera.getScene().useRightHandedSystem) {
  37650. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37651. }
  37652. else {
  37653. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37654. }
  37655. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37656. _this.previousPosition = {
  37657. x: evt.clientX,
  37658. y: evt.clientY
  37659. };
  37660. if (!noPreventDefault) {
  37661. evt.preventDefault();
  37662. }
  37663. }
  37664. };
  37665. }
  37666. this._onMouseMove = function (evt) {
  37667. if (!engine.isPointerLock) {
  37668. return;
  37669. }
  37670. if (engine.isInVRExclusivePointerMode) {
  37671. return;
  37672. }
  37673. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37674. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37675. if (_this.camera.getScene().useRightHandedSystem) {
  37676. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37677. }
  37678. else {
  37679. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37680. }
  37681. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37682. _this.previousPosition = null;
  37683. if (!noPreventDefault) {
  37684. evt.preventDefault();
  37685. }
  37686. };
  37687. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37688. element.addEventListener("mousemove", this._onMouseMove, false);
  37689. };
  37690. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37691. if (this._observer && element) {
  37692. this.camera.getScene().onPointerObservable.remove(this._observer);
  37693. if (this._onMouseMove) {
  37694. element.removeEventListener("mousemove", this._onMouseMove);
  37695. }
  37696. this._observer = null;
  37697. this._onMouseMove = null;
  37698. this.previousPosition = null;
  37699. }
  37700. };
  37701. FreeCameraMouseInput.prototype.getClassName = function () {
  37702. return "FreeCameraMouseInput";
  37703. };
  37704. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37705. return "mouse";
  37706. };
  37707. __decorate([
  37708. BABYLON.serialize()
  37709. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37710. __decorate([
  37711. BABYLON.serialize()
  37712. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37713. return FreeCameraMouseInput;
  37714. }());
  37715. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37716. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37717. })(BABYLON || (BABYLON = {}));
  37718. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37719. var BABYLON;
  37720. (function (BABYLON) {
  37721. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37722. function FreeCameraKeyboardMoveInput() {
  37723. this._keys = new Array();
  37724. this.keysUp = [38];
  37725. this.keysDown = [40];
  37726. this.keysLeft = [37];
  37727. this.keysRight = [39];
  37728. }
  37729. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37730. var _this = this;
  37731. if (this._onCanvasBlurObserver) {
  37732. return;
  37733. }
  37734. this._scene = this.camera.getScene();
  37735. this._engine = this._scene.getEngine();
  37736. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37737. _this._keys = [];
  37738. });
  37739. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37740. var evt = info.event;
  37741. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37742. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37743. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37744. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37745. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37746. var index = _this._keys.indexOf(evt.keyCode);
  37747. if (index === -1) {
  37748. _this._keys.push(evt.keyCode);
  37749. }
  37750. if (!noPreventDefault) {
  37751. evt.preventDefault();
  37752. }
  37753. }
  37754. }
  37755. else {
  37756. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37757. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37758. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37759. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37760. var index = _this._keys.indexOf(evt.keyCode);
  37761. if (index >= 0) {
  37762. _this._keys.splice(index, 1);
  37763. }
  37764. if (!noPreventDefault) {
  37765. evt.preventDefault();
  37766. }
  37767. }
  37768. }
  37769. });
  37770. };
  37771. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37772. if (this._scene) {
  37773. if (this._onKeyboardObserver) {
  37774. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37775. }
  37776. if (this._onCanvasBlurObserver) {
  37777. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37778. }
  37779. this._onKeyboardObserver = null;
  37780. this._onCanvasBlurObserver = null;
  37781. }
  37782. this._keys = [];
  37783. };
  37784. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37785. if (this._onKeyboardObserver) {
  37786. var camera = this.camera;
  37787. // Keyboard
  37788. for (var index = 0; index < this._keys.length; index++) {
  37789. var keyCode = this._keys[index];
  37790. var speed = camera._computeLocalCameraSpeed();
  37791. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37792. camera._localDirection.copyFromFloats(-speed, 0, 0);
  37793. }
  37794. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37795. camera._localDirection.copyFromFloats(0, 0, speed);
  37796. }
  37797. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37798. camera._localDirection.copyFromFloats(speed, 0, 0);
  37799. }
  37800. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37801. camera._localDirection.copyFromFloats(0, 0, -speed);
  37802. }
  37803. if (camera.getScene().useRightHandedSystem) {
  37804. camera._localDirection.z *= -1;
  37805. }
  37806. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  37807. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  37808. camera.cameraDirection.addInPlace(camera._transformedDirection);
  37809. }
  37810. }
  37811. };
  37812. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  37813. return "FreeCameraKeyboardMoveInput";
  37814. };
  37815. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  37816. this._keys = [];
  37817. };
  37818. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37819. return "keyboard";
  37820. };
  37821. __decorate([
  37822. BABYLON.serialize()
  37823. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37824. __decorate([
  37825. BABYLON.serialize()
  37826. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37827. __decorate([
  37828. BABYLON.serialize()
  37829. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37830. __decorate([
  37831. BABYLON.serialize()
  37832. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37833. return FreeCameraKeyboardMoveInput;
  37834. }());
  37835. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  37836. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  37837. })(BABYLON || (BABYLON = {}));
  37838. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  37839. var BABYLON;
  37840. (function (BABYLON) {
  37841. var FreeCameraInputsManager = /** @class */ (function (_super) {
  37842. __extends(FreeCameraInputsManager, _super);
  37843. function FreeCameraInputsManager(camera) {
  37844. return _super.call(this, camera) || this;
  37845. }
  37846. FreeCameraInputsManager.prototype.addKeyboard = function () {
  37847. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  37848. return this;
  37849. };
  37850. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  37851. if (touchEnabled === void 0) { touchEnabled = true; }
  37852. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  37853. return this;
  37854. };
  37855. FreeCameraInputsManager.prototype.addGamepad = function () {
  37856. this.add(new BABYLON.FreeCameraGamepadInput());
  37857. return this;
  37858. };
  37859. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  37860. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  37861. return this;
  37862. };
  37863. FreeCameraInputsManager.prototype.addTouch = function () {
  37864. this.add(new BABYLON.FreeCameraTouchInput());
  37865. return this;
  37866. };
  37867. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  37868. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  37869. return this;
  37870. };
  37871. return FreeCameraInputsManager;
  37872. }(BABYLON.CameraInputsManager));
  37873. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  37874. })(BABYLON || (BABYLON = {}));
  37875. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  37876. var BABYLON;
  37877. (function (BABYLON) {
  37878. var TargetCamera = /** @class */ (function (_super) {
  37879. __extends(TargetCamera, _super);
  37880. function TargetCamera(name, position, scene) {
  37881. var _this = _super.call(this, name, position, scene) || this;
  37882. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37883. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  37884. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  37885. _this.speed = 2.0;
  37886. _this.noRotationConstraint = false;
  37887. _this.lockedTarget = null;
  37888. _this._currentTarget = BABYLON.Vector3.Zero();
  37889. _this._viewMatrix = BABYLON.Matrix.Zero();
  37890. _this._camMatrix = BABYLON.Matrix.Zero();
  37891. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  37892. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  37893. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  37894. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  37895. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  37896. _this._lookAtTemp = BABYLON.Matrix.Zero();
  37897. _this._tempMatrix = BABYLON.Matrix.Zero();
  37898. return _this;
  37899. }
  37900. TargetCamera.prototype.getFrontPosition = function (distance) {
  37901. var direction = this.getTarget().subtract(this.position);
  37902. direction.normalize();
  37903. direction.scaleInPlace(distance);
  37904. return this.globalPosition.add(direction);
  37905. };
  37906. TargetCamera.prototype._getLockedTargetPosition = function () {
  37907. if (!this.lockedTarget) {
  37908. return null;
  37909. }
  37910. if (this.lockedTarget.absolutePosition) {
  37911. this.lockedTarget.computeWorldMatrix();
  37912. }
  37913. return this.lockedTarget.absolutePosition || this.lockedTarget;
  37914. };
  37915. TargetCamera.prototype.storeState = function () {
  37916. this._storedPosition = this.position.clone();
  37917. this._storedRotation = this.rotation.clone();
  37918. if (this.rotationQuaternion) {
  37919. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  37920. }
  37921. return _super.prototype.storeState.call(this);
  37922. };
  37923. /**
  37924. * Restored camera state. You must call storeState() first
  37925. */
  37926. TargetCamera.prototype._restoreStateValues = function () {
  37927. if (!_super.prototype._restoreStateValues.call(this)) {
  37928. return false;
  37929. }
  37930. this.position = this._storedPosition.clone();
  37931. this.rotation = this._storedRotation.clone();
  37932. if (this.rotationQuaternion) {
  37933. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  37934. }
  37935. this.cameraDirection.copyFromFloats(0, 0, 0);
  37936. this.cameraRotation.copyFromFloats(0, 0);
  37937. return true;
  37938. };
  37939. // Cache
  37940. TargetCamera.prototype._initCache = function () {
  37941. _super.prototype._initCache.call(this);
  37942. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37943. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37944. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37945. };
  37946. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  37947. if (!ignoreParentClass) {
  37948. _super.prototype._updateCache.call(this);
  37949. }
  37950. var lockedTargetPosition = this._getLockedTargetPosition();
  37951. if (!lockedTargetPosition) {
  37952. this._cache.lockedTarget = null;
  37953. }
  37954. else {
  37955. if (!this._cache.lockedTarget) {
  37956. this._cache.lockedTarget = lockedTargetPosition.clone();
  37957. }
  37958. else {
  37959. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  37960. }
  37961. }
  37962. this._cache.rotation.copyFrom(this.rotation);
  37963. if (this.rotationQuaternion)
  37964. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37965. };
  37966. // Synchronized
  37967. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  37968. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  37969. return false;
  37970. }
  37971. var lockedTargetPosition = this._getLockedTargetPosition();
  37972. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  37973. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  37974. };
  37975. // Methods
  37976. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  37977. var engine = this.getEngine();
  37978. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  37979. };
  37980. // Target
  37981. TargetCamera.prototype.setTarget = function (target) {
  37982. this.upVector.normalize();
  37983. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  37984. this._camMatrix.invert();
  37985. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  37986. var vDir = target.subtract(this.position);
  37987. if (vDir.x >= 0.0) {
  37988. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  37989. }
  37990. else {
  37991. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  37992. }
  37993. this.rotation.z = 0;
  37994. if (isNaN(this.rotation.x)) {
  37995. this.rotation.x = 0;
  37996. }
  37997. if (isNaN(this.rotation.y)) {
  37998. this.rotation.y = 0;
  37999. }
  38000. if (isNaN(this.rotation.z)) {
  38001. this.rotation.z = 0;
  38002. }
  38003. if (this.rotationQuaternion) {
  38004. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38005. }
  38006. };
  38007. /**
  38008. * Return the current target position of the camera. This value is expressed in local space.
  38009. */
  38010. TargetCamera.prototype.getTarget = function () {
  38011. return this._currentTarget;
  38012. };
  38013. TargetCamera.prototype._decideIfNeedsToMove = function () {
  38014. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38015. };
  38016. TargetCamera.prototype._updatePosition = function () {
  38017. if (this.parent) {
  38018. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  38019. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  38020. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  38021. return;
  38022. }
  38023. this.position.addInPlace(this.cameraDirection);
  38024. };
  38025. TargetCamera.prototype._checkInputs = function () {
  38026. var needToMove = this._decideIfNeedsToMove();
  38027. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  38028. // Move
  38029. if (needToMove) {
  38030. this._updatePosition();
  38031. }
  38032. // Rotate
  38033. if (needToRotate) {
  38034. this.rotation.x += this.cameraRotation.x;
  38035. this.rotation.y += this.cameraRotation.y;
  38036. //rotate, if quaternion is set and rotation was used
  38037. if (this.rotationQuaternion) {
  38038. var len = this.rotation.lengthSquared();
  38039. if (len) {
  38040. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38041. }
  38042. }
  38043. if (!this.noRotationConstraint) {
  38044. var limit = (Math.PI / 2) * 0.95;
  38045. if (this.rotation.x > limit)
  38046. this.rotation.x = limit;
  38047. if (this.rotation.x < -limit)
  38048. this.rotation.x = -limit;
  38049. }
  38050. }
  38051. // Inertia
  38052. if (needToMove) {
  38053. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  38054. this.cameraDirection.x = 0;
  38055. }
  38056. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  38057. this.cameraDirection.y = 0;
  38058. }
  38059. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  38060. this.cameraDirection.z = 0;
  38061. }
  38062. this.cameraDirection.scaleInPlace(this.inertia);
  38063. }
  38064. if (needToRotate) {
  38065. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  38066. this.cameraRotation.x = 0;
  38067. }
  38068. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  38069. this.cameraRotation.y = 0;
  38070. }
  38071. this.cameraRotation.scaleInPlace(this.inertia);
  38072. }
  38073. _super.prototype._checkInputs.call(this);
  38074. };
  38075. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  38076. if (this.rotationQuaternion) {
  38077. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  38078. }
  38079. else {
  38080. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  38081. }
  38082. //update the up vector!
  38083. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  38084. };
  38085. TargetCamera.prototype._getViewMatrix = function () {
  38086. if (!this.lockedTarget) {
  38087. // Compute
  38088. this._updateCameraRotationMatrix();
  38089. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  38090. // Computing target and final matrix
  38091. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  38092. }
  38093. else {
  38094. var targetPosition = this._getLockedTargetPosition();
  38095. if (targetPosition) {
  38096. this._currentTarget.copyFrom(targetPosition);
  38097. }
  38098. }
  38099. if (this.getScene().useRightHandedSystem) {
  38100. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  38101. }
  38102. else {
  38103. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  38104. }
  38105. return this._viewMatrix;
  38106. };
  38107. /**
  38108. * @override
  38109. * Override Camera.createRigCamera
  38110. */
  38111. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  38112. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  38113. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  38114. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  38115. if (!this.rotationQuaternion) {
  38116. this.rotationQuaternion = new BABYLON.Quaternion();
  38117. }
  38118. rigCamera._cameraRigParams = {};
  38119. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  38120. }
  38121. return rigCamera;
  38122. }
  38123. return null;
  38124. };
  38125. /**
  38126. * @override
  38127. * Override Camera._updateRigCameras
  38128. */
  38129. TargetCamera.prototype._updateRigCameras = function () {
  38130. var camLeft = this._rigCameras[0];
  38131. var camRight = this._rigCameras[1];
  38132. switch (this.cameraRigMode) {
  38133. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  38134. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  38135. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  38136. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  38137. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  38138. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  38139. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  38140. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  38141. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  38142. camLeft.setTarget(this.getTarget());
  38143. camRight.setTarget(this.getTarget());
  38144. break;
  38145. case BABYLON.Camera.RIG_MODE_VR:
  38146. if (camLeft.rotationQuaternion) {
  38147. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38148. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38149. }
  38150. else {
  38151. camLeft.rotation.copyFrom(this.rotation);
  38152. camRight.rotation.copyFrom(this.rotation);
  38153. }
  38154. camLeft.position.copyFrom(this.position);
  38155. camRight.position.copyFrom(this.position);
  38156. break;
  38157. }
  38158. _super.prototype._updateRigCameras.call(this);
  38159. };
  38160. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  38161. if (!this._rigCamTransformMatrix) {
  38162. this._rigCamTransformMatrix = new BABYLON.Matrix();
  38163. }
  38164. var target = this.getTarget();
  38165. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  38166. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  38167. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  38168. };
  38169. TargetCamera.prototype.getClassName = function () {
  38170. return "TargetCamera";
  38171. };
  38172. __decorate([
  38173. BABYLON.serializeAsVector3()
  38174. ], TargetCamera.prototype, "rotation", void 0);
  38175. __decorate([
  38176. BABYLON.serialize()
  38177. ], TargetCamera.prototype, "speed", void 0);
  38178. __decorate([
  38179. BABYLON.serializeAsMeshReference("lockedTargetId")
  38180. ], TargetCamera.prototype, "lockedTarget", void 0);
  38181. return TargetCamera;
  38182. }(BABYLON.Camera));
  38183. BABYLON.TargetCamera = TargetCamera;
  38184. })(BABYLON || (BABYLON = {}));
  38185. //# sourceMappingURL=babylon.targetCamera.js.map
  38186. var BABYLON;
  38187. (function (BABYLON) {
  38188. var FreeCamera = /** @class */ (function (_super) {
  38189. __extends(FreeCamera, _super);
  38190. function FreeCamera(name, position, scene) {
  38191. var _this = _super.call(this, name, position, scene) || this;
  38192. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  38193. _this.checkCollisions = false;
  38194. _this.applyGravity = false;
  38195. _this._needMoveForGravity = false;
  38196. _this._oldPosition = BABYLON.Vector3.Zero();
  38197. _this._diffPosition = BABYLON.Vector3.Zero();
  38198. _this._newPosition = BABYLON.Vector3.Zero();
  38199. // Collisions
  38200. _this._collisionMask = -1;
  38201. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38202. if (collidedMesh === void 0) { collidedMesh = null; }
  38203. //TODO move this to the collision coordinator!
  38204. if (_this.getScene().workerCollisions)
  38205. newPosition.multiplyInPlace(_this._collider.radius);
  38206. var updatePosition = function (newPos) {
  38207. _this._newPosition.copyFrom(newPos);
  38208. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  38209. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  38210. _this.position.addInPlace(_this._diffPosition);
  38211. if (_this.onCollide && collidedMesh) {
  38212. _this.onCollide(collidedMesh);
  38213. }
  38214. }
  38215. };
  38216. updatePosition(newPosition);
  38217. };
  38218. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  38219. _this.inputs.addKeyboard().addMouse();
  38220. return _this;
  38221. }
  38222. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  38223. //-- begin properties for backward compatibility for inputs
  38224. get: function () {
  38225. var mouse = this.inputs.attached["mouse"];
  38226. if (mouse)
  38227. return mouse.angularSensibility;
  38228. return 0;
  38229. },
  38230. set: function (value) {
  38231. var mouse = this.inputs.attached["mouse"];
  38232. if (mouse)
  38233. mouse.angularSensibility = value;
  38234. },
  38235. enumerable: true,
  38236. configurable: true
  38237. });
  38238. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  38239. get: function () {
  38240. var keyboard = this.inputs.attached["keyboard"];
  38241. if (keyboard)
  38242. return keyboard.keysUp;
  38243. return [];
  38244. },
  38245. set: function (value) {
  38246. var keyboard = this.inputs.attached["keyboard"];
  38247. if (keyboard)
  38248. keyboard.keysUp = value;
  38249. },
  38250. enumerable: true,
  38251. configurable: true
  38252. });
  38253. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  38254. get: function () {
  38255. var keyboard = this.inputs.attached["keyboard"];
  38256. if (keyboard)
  38257. return keyboard.keysDown;
  38258. return [];
  38259. },
  38260. set: function (value) {
  38261. var keyboard = this.inputs.attached["keyboard"];
  38262. if (keyboard)
  38263. keyboard.keysDown = value;
  38264. },
  38265. enumerable: true,
  38266. configurable: true
  38267. });
  38268. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  38269. get: function () {
  38270. var keyboard = this.inputs.attached["keyboard"];
  38271. if (keyboard)
  38272. return keyboard.keysLeft;
  38273. return [];
  38274. },
  38275. set: function (value) {
  38276. var keyboard = this.inputs.attached["keyboard"];
  38277. if (keyboard)
  38278. keyboard.keysLeft = value;
  38279. },
  38280. enumerable: true,
  38281. configurable: true
  38282. });
  38283. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  38284. get: function () {
  38285. var keyboard = this.inputs.attached["keyboard"];
  38286. if (keyboard)
  38287. return keyboard.keysRight;
  38288. return [];
  38289. },
  38290. set: function (value) {
  38291. var keyboard = this.inputs.attached["keyboard"];
  38292. if (keyboard)
  38293. keyboard.keysRight = value;
  38294. },
  38295. enumerable: true,
  38296. configurable: true
  38297. });
  38298. // Controls
  38299. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  38300. this.inputs.attachElement(element, noPreventDefault);
  38301. };
  38302. FreeCamera.prototype.detachControl = function (element) {
  38303. this.inputs.detachElement(element);
  38304. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38305. this.cameraRotation = new BABYLON.Vector2(0, 0);
  38306. };
  38307. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  38308. get: function () {
  38309. return this._collisionMask;
  38310. },
  38311. set: function (mask) {
  38312. this._collisionMask = !isNaN(mask) ? mask : -1;
  38313. },
  38314. enumerable: true,
  38315. configurable: true
  38316. });
  38317. FreeCamera.prototype._collideWithWorld = function (displacement) {
  38318. var globalPosition;
  38319. if (this.parent) {
  38320. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  38321. }
  38322. else {
  38323. globalPosition = this.position;
  38324. }
  38325. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  38326. if (!this._collider) {
  38327. this._collider = new BABYLON.Collider();
  38328. }
  38329. this._collider.radius = this.ellipsoid;
  38330. this._collider.collisionMask = this._collisionMask;
  38331. //no need for clone, as long as gravity is not on.
  38332. var actualDisplacement = displacement;
  38333. //add gravity to the direction to prevent the dual-collision checking
  38334. if (this.applyGravity) {
  38335. //this prevents mending with cameraDirection, a global variable of the free camera class.
  38336. actualDisplacement = displacement.add(this.getScene().gravity);
  38337. }
  38338. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  38339. };
  38340. FreeCamera.prototype._checkInputs = function () {
  38341. if (!this._localDirection) {
  38342. this._localDirection = BABYLON.Vector3.Zero();
  38343. this._transformedDirection = BABYLON.Vector3.Zero();
  38344. }
  38345. this.inputs.checkInputs();
  38346. _super.prototype._checkInputs.call(this);
  38347. };
  38348. FreeCamera.prototype._decideIfNeedsToMove = function () {
  38349. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38350. };
  38351. FreeCamera.prototype._updatePosition = function () {
  38352. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  38353. this._collideWithWorld(this.cameraDirection);
  38354. }
  38355. else {
  38356. _super.prototype._updatePosition.call(this);
  38357. }
  38358. };
  38359. FreeCamera.prototype.dispose = function () {
  38360. this.inputs.clear();
  38361. _super.prototype.dispose.call(this);
  38362. };
  38363. FreeCamera.prototype.getClassName = function () {
  38364. return "FreeCamera";
  38365. };
  38366. __decorate([
  38367. BABYLON.serializeAsVector3()
  38368. ], FreeCamera.prototype, "ellipsoid", void 0);
  38369. __decorate([
  38370. BABYLON.serialize()
  38371. ], FreeCamera.prototype, "checkCollisions", void 0);
  38372. __decorate([
  38373. BABYLON.serialize()
  38374. ], FreeCamera.prototype, "applyGravity", void 0);
  38375. return FreeCamera;
  38376. }(BABYLON.TargetCamera));
  38377. BABYLON.FreeCamera = FreeCamera;
  38378. })(BABYLON || (BABYLON = {}));
  38379. //# sourceMappingURL=babylon.freeCamera.js.map
  38380. var BABYLON;
  38381. (function (BABYLON) {
  38382. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  38383. function ArcRotateCameraKeyboardMoveInput() {
  38384. this._keys = new Array();
  38385. this.keysUp = [38];
  38386. this.keysDown = [40];
  38387. this.keysLeft = [37];
  38388. this.keysRight = [39];
  38389. this.keysReset = [220];
  38390. this.panningSensibility = 50.0;
  38391. this.zoomingSensibility = 25.0;
  38392. this.useAltToZoom = true;
  38393. }
  38394. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38395. var _this = this;
  38396. if (this._onCanvasBlurObserver) {
  38397. return;
  38398. }
  38399. this._scene = this.camera.getScene();
  38400. this._engine = this._scene.getEngine();
  38401. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38402. _this._keys = [];
  38403. });
  38404. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38405. var evt = info.event;
  38406. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38407. _this._ctrlPressed = evt.ctrlKey;
  38408. _this._altPressed = evt.altKey;
  38409. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38410. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38411. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38412. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38413. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38414. var index = _this._keys.indexOf(evt.keyCode);
  38415. if (index === -1) {
  38416. _this._keys.push(evt.keyCode);
  38417. }
  38418. if (evt.preventDefault) {
  38419. if (!noPreventDefault) {
  38420. evt.preventDefault();
  38421. }
  38422. }
  38423. }
  38424. }
  38425. else {
  38426. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38427. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38428. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38429. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  38430. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  38431. var index = _this._keys.indexOf(evt.keyCode);
  38432. if (index >= 0) {
  38433. _this._keys.splice(index, 1);
  38434. }
  38435. if (evt.preventDefault) {
  38436. if (!noPreventDefault) {
  38437. evt.preventDefault();
  38438. }
  38439. }
  38440. }
  38441. }
  38442. });
  38443. };
  38444. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38445. if (this._scene) {
  38446. if (this._onKeyboardObserver) {
  38447. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38448. }
  38449. if (this._onCanvasBlurObserver) {
  38450. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38451. }
  38452. this._onKeyboardObserver = null;
  38453. this._onCanvasBlurObserver = null;
  38454. }
  38455. this._keys = [];
  38456. };
  38457. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38458. if (this._onKeyboardObserver) {
  38459. var camera = this.camera;
  38460. for (var index = 0; index < this._keys.length; index++) {
  38461. var keyCode = this._keys[index];
  38462. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38463. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38464. camera.inertialPanningX -= 1 / this.panningSensibility;
  38465. }
  38466. else {
  38467. camera.inertialAlphaOffset -= 0.01;
  38468. }
  38469. }
  38470. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38471. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38472. camera.inertialPanningY += 1 / this.panningSensibility;
  38473. }
  38474. else if (this._altPressed && this.useAltToZoom) {
  38475. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  38476. }
  38477. else {
  38478. camera.inertialBetaOffset -= 0.01;
  38479. }
  38480. }
  38481. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38482. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38483. camera.inertialPanningX += 1 / this.panningSensibility;
  38484. }
  38485. else {
  38486. camera.inertialAlphaOffset += 0.01;
  38487. }
  38488. }
  38489. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38490. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38491. camera.inertialPanningY -= 1 / this.panningSensibility;
  38492. }
  38493. else if (this._altPressed && this.useAltToZoom) {
  38494. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  38495. }
  38496. else {
  38497. camera.inertialBetaOffset += 0.01;
  38498. }
  38499. }
  38500. else if (this.keysReset.indexOf(keyCode) !== -1) {
  38501. camera.restoreState();
  38502. }
  38503. }
  38504. }
  38505. };
  38506. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  38507. return "ArcRotateCameraKeyboardMoveInput";
  38508. };
  38509. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38510. return "keyboard";
  38511. };
  38512. __decorate([
  38513. BABYLON.serialize()
  38514. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38515. __decorate([
  38516. BABYLON.serialize()
  38517. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38518. __decorate([
  38519. BABYLON.serialize()
  38520. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38521. __decorate([
  38522. BABYLON.serialize()
  38523. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38524. __decorate([
  38525. BABYLON.serialize()
  38526. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  38527. __decorate([
  38528. BABYLON.serialize()
  38529. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  38530. __decorate([
  38531. BABYLON.serialize()
  38532. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  38533. __decorate([
  38534. BABYLON.serialize()
  38535. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  38536. return ArcRotateCameraKeyboardMoveInput;
  38537. }());
  38538. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  38539. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  38540. })(BABYLON || (BABYLON = {}));
  38541. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  38542. var BABYLON;
  38543. (function (BABYLON) {
  38544. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  38545. function ArcRotateCameraMouseWheelInput() {
  38546. this.wheelPrecision = 3.0;
  38547. /**
  38548. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  38549. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  38550. */
  38551. this.wheelDeltaPercentage = 0;
  38552. }
  38553. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  38554. var _this = this;
  38555. this._wheel = function (p, s) {
  38556. //sanity check - this should be a PointerWheel event.
  38557. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  38558. return;
  38559. var event = p.event;
  38560. var delta = 0;
  38561. if (event.wheelDelta) {
  38562. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  38563. }
  38564. else if (event.detail) {
  38565. delta = -event.detail / _this.wheelPrecision;
  38566. }
  38567. if (delta)
  38568. _this.camera.inertialRadiusOffset += delta;
  38569. if (event.preventDefault) {
  38570. if (!noPreventDefault) {
  38571. event.preventDefault();
  38572. }
  38573. }
  38574. };
  38575. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  38576. };
  38577. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  38578. if (this._observer && element) {
  38579. this.camera.getScene().onPointerObservable.remove(this._observer);
  38580. this._observer = null;
  38581. this._wheel = null;
  38582. }
  38583. };
  38584. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  38585. return "ArcRotateCameraMouseWheelInput";
  38586. };
  38587. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  38588. return "mousewheel";
  38589. };
  38590. __decorate([
  38591. BABYLON.serialize()
  38592. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  38593. __decorate([
  38594. BABYLON.serialize()
  38595. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  38596. return ArcRotateCameraMouseWheelInput;
  38597. }());
  38598. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  38599. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  38600. })(BABYLON || (BABYLON = {}));
  38601. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  38602. var BABYLON;
  38603. (function (BABYLON) {
  38604. var ArcRotateCameraPointersInput = /** @class */ (function () {
  38605. function ArcRotateCameraPointersInput() {
  38606. this.buttons = [0, 1, 2];
  38607. this.angularSensibilityX = 1000.0;
  38608. this.angularSensibilityY = 1000.0;
  38609. this.pinchPrecision = 12.0;
  38610. /**
  38611. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  38612. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  38613. */
  38614. this.pinchDeltaPercentage = 0;
  38615. this.panningSensibility = 1000.0;
  38616. this.multiTouchPanning = true;
  38617. this.multiTouchPanAndZoom = true;
  38618. this._isPanClick = false;
  38619. this.pinchInwards = true;
  38620. }
  38621. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  38622. var _this = this;
  38623. var engine = this.camera.getEngine();
  38624. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  38625. var pointA = null;
  38626. var pointB = null;
  38627. var previousPinchSquaredDistance = 0;
  38628. var initialDistance = 0;
  38629. var twoFingerActivityCount = 0;
  38630. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  38631. this._pointerInput = function (p, s) {
  38632. var evt = p.event;
  38633. var isTouch = p.event.pointerType === "touch";
  38634. if (engine.isInVRExclusivePointerMode) {
  38635. return;
  38636. }
  38637. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38638. return;
  38639. }
  38640. var srcElement = (evt.srcElement || evt.target);
  38641. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38642. try {
  38643. srcElement.setPointerCapture(evt.pointerId);
  38644. }
  38645. catch (e) {
  38646. //Nothing to do with the error. Execution will continue.
  38647. }
  38648. // Manage panning with pan button click
  38649. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  38650. // manage pointers
  38651. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  38652. if (pointA === null) {
  38653. pointA = cacheSoloPointer;
  38654. }
  38655. else if (pointB === null) {
  38656. pointB = cacheSoloPointer;
  38657. }
  38658. if (!noPreventDefault) {
  38659. evt.preventDefault();
  38660. element.focus();
  38661. }
  38662. }
  38663. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  38664. _this.camera.restoreState();
  38665. }
  38666. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38667. try {
  38668. srcElement.releasePointerCapture(evt.pointerId);
  38669. }
  38670. catch (e) {
  38671. //Nothing to do with the error.
  38672. }
  38673. cacheSoloPointer = null;
  38674. previousPinchSquaredDistance = 0;
  38675. previousMultiTouchPanPosition.isPaning = false;
  38676. previousMultiTouchPanPosition.isPinching = false;
  38677. twoFingerActivityCount = 0;
  38678. initialDistance = 0;
  38679. if (!isTouch) {
  38680. pointB = null; // Mouse and pen are mono pointer
  38681. }
  38682. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38683. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38684. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38685. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38686. if (engine.badOS) {
  38687. pointA = pointB = null;
  38688. }
  38689. else {
  38690. //only remove the impacted pointer in case of multitouch allowing on most
  38691. //platforms switching from rotate to zoom and pan seamlessly.
  38692. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38693. pointA = pointB;
  38694. pointB = null;
  38695. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38696. }
  38697. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38698. pointB = null;
  38699. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38700. }
  38701. else {
  38702. pointA = pointB = null;
  38703. }
  38704. }
  38705. if (!noPreventDefault) {
  38706. evt.preventDefault();
  38707. }
  38708. }
  38709. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38710. if (!noPreventDefault) {
  38711. evt.preventDefault();
  38712. }
  38713. // One button down
  38714. if (pointA && pointB === null && cacheSoloPointer) {
  38715. if (_this.panningSensibility !== 0 &&
  38716. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38717. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38718. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38719. }
  38720. else {
  38721. var offsetX = evt.clientX - cacheSoloPointer.x;
  38722. var offsetY = evt.clientY - cacheSoloPointer.y;
  38723. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38724. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38725. }
  38726. cacheSoloPointer.x = evt.clientX;
  38727. cacheSoloPointer.y = evt.clientY;
  38728. }
  38729. else if (pointA && pointB) {
  38730. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38731. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38732. ed.x = evt.clientX;
  38733. ed.y = evt.clientY;
  38734. var direction = _this.pinchInwards ? 1 : -1;
  38735. var distX = pointA.x - pointB.x;
  38736. var distY = pointA.y - pointB.y;
  38737. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38738. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38739. if (previousPinchSquaredDistance === 0) {
  38740. initialDistance = pinchDistance;
  38741. previousPinchSquaredDistance = pinchSquaredDistance;
  38742. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38743. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38744. return;
  38745. }
  38746. if (_this.multiTouchPanAndZoom) {
  38747. if (_this.pinchDeltaPercentage) {
  38748. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38749. }
  38750. else {
  38751. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38752. (_this.pinchPrecision *
  38753. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38754. direction);
  38755. }
  38756. if (_this.panningSensibility !== 0) {
  38757. var pointersCenterX = (pointA.x + pointB.x) / 2;
  38758. var pointersCenterY = (pointA.y + pointB.y) / 2;
  38759. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  38760. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  38761. previousMultiTouchPanPosition.x = pointersCenterX;
  38762. previousMultiTouchPanPosition.y = pointersCenterY;
  38763. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  38764. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  38765. }
  38766. }
  38767. else {
  38768. twoFingerActivityCount++;
  38769. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  38770. if (_this.pinchDeltaPercentage) {
  38771. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38772. }
  38773. else {
  38774. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38775. (_this.pinchPrecision *
  38776. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38777. direction);
  38778. }
  38779. previousMultiTouchPanPosition.isPaning = false;
  38780. previousMultiTouchPanPosition.isPinching = true;
  38781. }
  38782. else {
  38783. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  38784. if (!previousMultiTouchPanPosition.isPaning) {
  38785. previousMultiTouchPanPosition.isPaning = true;
  38786. previousMultiTouchPanPosition.isPinching = false;
  38787. previousMultiTouchPanPosition.x = ed.x;
  38788. previousMultiTouchPanPosition.y = ed.y;
  38789. return;
  38790. }
  38791. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  38792. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  38793. }
  38794. }
  38795. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  38796. previousMultiTouchPanPosition.x = ed.x;
  38797. previousMultiTouchPanPosition.y = ed.y;
  38798. }
  38799. }
  38800. previousPinchSquaredDistance = pinchSquaredDistance;
  38801. }
  38802. }
  38803. };
  38804. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  38805. this._onContextMenu = function (evt) {
  38806. evt.preventDefault();
  38807. };
  38808. if (!this.camera._useCtrlForPanning) {
  38809. element.addEventListener("contextmenu", this._onContextMenu, false);
  38810. }
  38811. this._onLostFocus = function () {
  38812. //this._keys = [];
  38813. pointA = pointB = null;
  38814. previousPinchSquaredDistance = 0;
  38815. previousMultiTouchPanPosition.isPaning = false;
  38816. previousMultiTouchPanPosition.isPinching = false;
  38817. twoFingerActivityCount = 0;
  38818. cacheSoloPointer = null;
  38819. initialDistance = 0;
  38820. };
  38821. this._onMouseMove = function (evt) {
  38822. if (!engine.isPointerLock) {
  38823. return;
  38824. }
  38825. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38826. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38827. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38828. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38829. if (!noPreventDefault) {
  38830. evt.preventDefault();
  38831. }
  38832. };
  38833. this._onGestureStart = function (e) {
  38834. if (window.MSGesture === undefined) {
  38835. return;
  38836. }
  38837. if (!_this._MSGestureHandler) {
  38838. _this._MSGestureHandler = new MSGesture();
  38839. _this._MSGestureHandler.target = element;
  38840. }
  38841. _this._MSGestureHandler.addPointer(e.pointerId);
  38842. };
  38843. this._onGesture = function (e) {
  38844. _this.camera.radius *= e.scale;
  38845. if (e.preventDefault) {
  38846. if (!noPreventDefault) {
  38847. e.stopPropagation();
  38848. e.preventDefault();
  38849. }
  38850. }
  38851. };
  38852. element.addEventListener("mousemove", this._onMouseMove, false);
  38853. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  38854. element.addEventListener("MSGestureChange", this._onGesture, false);
  38855. BABYLON.Tools.RegisterTopRootEvents([
  38856. { name: "blur", handler: this._onLostFocus }
  38857. ]);
  38858. };
  38859. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  38860. if (this._onLostFocus) {
  38861. BABYLON.Tools.UnregisterTopRootEvents([
  38862. { name: "blur", handler: this._onLostFocus }
  38863. ]);
  38864. }
  38865. if (element && this._observer) {
  38866. this.camera.getScene().onPointerObservable.remove(this._observer);
  38867. this._observer = null;
  38868. if (this._onContextMenu) {
  38869. element.removeEventListener("contextmenu", this._onContextMenu);
  38870. }
  38871. if (this._onMouseMove) {
  38872. element.removeEventListener("mousemove", this._onMouseMove);
  38873. }
  38874. if (this._onGestureStart) {
  38875. element.removeEventListener("MSPointerDown", this._onGestureStart);
  38876. }
  38877. if (this._onGesture) {
  38878. element.removeEventListener("MSGestureChange", this._onGesture);
  38879. }
  38880. this._isPanClick = false;
  38881. this.pinchInwards = true;
  38882. this._onMouseMove = null;
  38883. this._onGestureStart = null;
  38884. this._onGesture = null;
  38885. this._MSGestureHandler = null;
  38886. this._onLostFocus = null;
  38887. this._onContextMenu = null;
  38888. }
  38889. };
  38890. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  38891. return "ArcRotateCameraPointersInput";
  38892. };
  38893. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  38894. return "pointers";
  38895. };
  38896. __decorate([
  38897. BABYLON.serialize()
  38898. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  38899. __decorate([
  38900. BABYLON.serialize()
  38901. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  38902. __decorate([
  38903. BABYLON.serialize()
  38904. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  38905. __decorate([
  38906. BABYLON.serialize()
  38907. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  38908. __decorate([
  38909. BABYLON.serialize()
  38910. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  38911. __decorate([
  38912. BABYLON.serialize()
  38913. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  38914. __decorate([
  38915. BABYLON.serialize()
  38916. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  38917. __decorate([
  38918. BABYLON.serialize()
  38919. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  38920. return ArcRotateCameraPointersInput;
  38921. }());
  38922. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  38923. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  38924. })(BABYLON || (BABYLON = {}));
  38925. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  38926. var BABYLON;
  38927. (function (BABYLON) {
  38928. var ArcRotateCamera = /** @class */ (function (_super) {
  38929. __extends(ArcRotateCamera, _super);
  38930. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  38931. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  38932. _this.inertialAlphaOffset = 0;
  38933. _this.inertialBetaOffset = 0;
  38934. _this.inertialRadiusOffset = 0;
  38935. _this.lowerAlphaLimit = null;
  38936. _this.upperAlphaLimit = null;
  38937. _this.lowerBetaLimit = 0.01;
  38938. _this.upperBetaLimit = Math.PI;
  38939. _this.lowerRadiusLimit = null;
  38940. _this.upperRadiusLimit = null;
  38941. _this.inertialPanningX = 0;
  38942. _this.inertialPanningY = 0;
  38943. _this.pinchToPanMaxDistance = 20;
  38944. _this.panningDistanceLimit = null;
  38945. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  38946. _this.panningInertia = 0.9;
  38947. //-- end properties for backward compatibility for inputs
  38948. _this.zoomOnFactor = 1;
  38949. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  38950. _this.allowUpsideDown = true;
  38951. _this._viewMatrix = new BABYLON.Matrix();
  38952. // Panning
  38953. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  38954. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  38955. _this.checkCollisions = false;
  38956. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38957. _this._previousPosition = BABYLON.Vector3.Zero();
  38958. _this._collisionVelocity = BABYLON.Vector3.Zero();
  38959. _this._newPosition = BABYLON.Vector3.Zero();
  38960. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38961. if (collidedMesh === void 0) { collidedMesh = null; }
  38962. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  38963. newPosition.multiplyInPlace(_this._collider.radius);
  38964. }
  38965. if (!collidedMesh) {
  38966. _this._previousPosition.copyFrom(_this.position);
  38967. }
  38968. else {
  38969. _this.setPosition(newPosition);
  38970. if (_this.onCollide) {
  38971. _this.onCollide(collidedMesh);
  38972. }
  38973. }
  38974. // Recompute because of constraints
  38975. var cosa = Math.cos(_this.alpha);
  38976. var sina = Math.sin(_this.alpha);
  38977. var cosb = Math.cos(_this.beta);
  38978. var sinb = Math.sin(_this.beta);
  38979. if (sinb === 0) {
  38980. sinb = 0.0001;
  38981. }
  38982. var target = _this._getTargetPosition();
  38983. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  38984. _this.position.copyFrom(_this._newPosition);
  38985. var up = _this.upVector;
  38986. if (_this.allowUpsideDown && _this.beta < 0) {
  38987. up = up.clone();
  38988. up = up.negate();
  38989. }
  38990. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  38991. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  38992. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  38993. _this._collisionTriggered = false;
  38994. };
  38995. _this._target = BABYLON.Vector3.Zero();
  38996. if (target) {
  38997. _this.setTarget(target);
  38998. }
  38999. _this.alpha = alpha;
  39000. _this.beta = beta;
  39001. _this.radius = radius;
  39002. _this.getViewMatrix();
  39003. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  39004. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  39005. return _this;
  39006. }
  39007. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  39008. get: function () {
  39009. return this._target;
  39010. },
  39011. set: function (value) {
  39012. this.setTarget(value);
  39013. },
  39014. enumerable: true,
  39015. configurable: true
  39016. });
  39017. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  39018. //-- begin properties for backward compatibility for inputs
  39019. get: function () {
  39020. var pointers = this.inputs.attached["pointers"];
  39021. if (pointers)
  39022. return pointers.angularSensibilityX;
  39023. return 0;
  39024. },
  39025. set: function (value) {
  39026. var pointers = this.inputs.attached["pointers"];
  39027. if (pointers) {
  39028. pointers.angularSensibilityX = value;
  39029. }
  39030. },
  39031. enumerable: true,
  39032. configurable: true
  39033. });
  39034. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  39035. get: function () {
  39036. var pointers = this.inputs.attached["pointers"];
  39037. if (pointers)
  39038. return pointers.angularSensibilityY;
  39039. return 0;
  39040. },
  39041. set: function (value) {
  39042. var pointers = this.inputs.attached["pointers"];
  39043. if (pointers) {
  39044. pointers.angularSensibilityY = value;
  39045. }
  39046. },
  39047. enumerable: true,
  39048. configurable: true
  39049. });
  39050. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  39051. get: function () {
  39052. var pointers = this.inputs.attached["pointers"];
  39053. if (pointers)
  39054. return pointers.pinchPrecision;
  39055. return 0;
  39056. },
  39057. set: function (value) {
  39058. var pointers = this.inputs.attached["pointers"];
  39059. if (pointers) {
  39060. pointers.pinchPrecision = value;
  39061. }
  39062. },
  39063. enumerable: true,
  39064. configurable: true
  39065. });
  39066. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  39067. get: function () {
  39068. var pointers = this.inputs.attached["pointers"];
  39069. if (pointers)
  39070. return pointers.pinchDeltaPercentage;
  39071. return 0;
  39072. },
  39073. set: function (value) {
  39074. var pointers = this.inputs.attached["pointers"];
  39075. if (pointers) {
  39076. pointers.pinchDeltaPercentage = value;
  39077. }
  39078. },
  39079. enumerable: true,
  39080. configurable: true
  39081. });
  39082. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  39083. get: function () {
  39084. var pointers = this.inputs.attached["pointers"];
  39085. if (pointers)
  39086. return pointers.panningSensibility;
  39087. return 0;
  39088. },
  39089. set: function (value) {
  39090. var pointers = this.inputs.attached["pointers"];
  39091. if (pointers) {
  39092. pointers.panningSensibility = value;
  39093. }
  39094. },
  39095. enumerable: true,
  39096. configurable: true
  39097. });
  39098. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  39099. get: function () {
  39100. var keyboard = this.inputs.attached["keyboard"];
  39101. if (keyboard)
  39102. return keyboard.keysUp;
  39103. return [];
  39104. },
  39105. set: function (value) {
  39106. var keyboard = this.inputs.attached["keyboard"];
  39107. if (keyboard)
  39108. keyboard.keysUp = value;
  39109. },
  39110. enumerable: true,
  39111. configurable: true
  39112. });
  39113. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  39114. get: function () {
  39115. var keyboard = this.inputs.attached["keyboard"];
  39116. if (keyboard)
  39117. return keyboard.keysDown;
  39118. return [];
  39119. },
  39120. set: function (value) {
  39121. var keyboard = this.inputs.attached["keyboard"];
  39122. if (keyboard)
  39123. keyboard.keysDown = value;
  39124. },
  39125. enumerable: true,
  39126. configurable: true
  39127. });
  39128. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  39129. get: function () {
  39130. var keyboard = this.inputs.attached["keyboard"];
  39131. if (keyboard)
  39132. return keyboard.keysLeft;
  39133. return [];
  39134. },
  39135. set: function (value) {
  39136. var keyboard = this.inputs.attached["keyboard"];
  39137. if (keyboard)
  39138. keyboard.keysLeft = value;
  39139. },
  39140. enumerable: true,
  39141. configurable: true
  39142. });
  39143. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  39144. get: function () {
  39145. var keyboard = this.inputs.attached["keyboard"];
  39146. if (keyboard)
  39147. return keyboard.keysRight;
  39148. return [];
  39149. },
  39150. set: function (value) {
  39151. var keyboard = this.inputs.attached["keyboard"];
  39152. if (keyboard)
  39153. keyboard.keysRight = value;
  39154. },
  39155. enumerable: true,
  39156. configurable: true
  39157. });
  39158. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  39159. get: function () {
  39160. var mousewheel = this.inputs.attached["mousewheel"];
  39161. if (mousewheel)
  39162. return mousewheel.wheelPrecision;
  39163. return 0;
  39164. },
  39165. set: function (value) {
  39166. var mousewheel = this.inputs.attached["mousewheel"];
  39167. if (mousewheel)
  39168. mousewheel.wheelPrecision = value;
  39169. },
  39170. enumerable: true,
  39171. configurable: true
  39172. });
  39173. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  39174. get: function () {
  39175. var mousewheel = this.inputs.attached["mousewheel"];
  39176. if (mousewheel)
  39177. return mousewheel.wheelDeltaPercentage;
  39178. return 0;
  39179. },
  39180. set: function (value) {
  39181. var mousewheel = this.inputs.attached["mousewheel"];
  39182. if (mousewheel)
  39183. mousewheel.wheelDeltaPercentage = value;
  39184. },
  39185. enumerable: true,
  39186. configurable: true
  39187. });
  39188. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  39189. get: function () {
  39190. return this._bouncingBehavior;
  39191. },
  39192. enumerable: true,
  39193. configurable: true
  39194. });
  39195. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  39196. get: function () {
  39197. return this._bouncingBehavior != null;
  39198. },
  39199. set: function (value) {
  39200. if (value === this.useBouncingBehavior) {
  39201. return;
  39202. }
  39203. if (value) {
  39204. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  39205. this.addBehavior(this._bouncingBehavior);
  39206. }
  39207. else if (this._bouncingBehavior) {
  39208. this.removeBehavior(this._bouncingBehavior);
  39209. this._bouncingBehavior = null;
  39210. }
  39211. },
  39212. enumerable: true,
  39213. configurable: true
  39214. });
  39215. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  39216. get: function () {
  39217. return this._framingBehavior;
  39218. },
  39219. enumerable: true,
  39220. configurable: true
  39221. });
  39222. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  39223. get: function () {
  39224. return this._framingBehavior != null;
  39225. },
  39226. set: function (value) {
  39227. if (value === this.useFramingBehavior) {
  39228. return;
  39229. }
  39230. if (value) {
  39231. this._framingBehavior = new BABYLON.FramingBehavior();
  39232. this.addBehavior(this._framingBehavior);
  39233. }
  39234. else if (this._framingBehavior) {
  39235. this.removeBehavior(this._framingBehavior);
  39236. this._framingBehavior = null;
  39237. }
  39238. },
  39239. enumerable: true,
  39240. configurable: true
  39241. });
  39242. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  39243. get: function () {
  39244. return this._autoRotationBehavior;
  39245. },
  39246. enumerable: true,
  39247. configurable: true
  39248. });
  39249. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  39250. get: function () {
  39251. return this._autoRotationBehavior != null;
  39252. },
  39253. set: function (value) {
  39254. if (value === this.useAutoRotationBehavior) {
  39255. return;
  39256. }
  39257. if (value) {
  39258. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  39259. this.addBehavior(this._autoRotationBehavior);
  39260. }
  39261. else if (this._autoRotationBehavior) {
  39262. this.removeBehavior(this._autoRotationBehavior);
  39263. this._autoRotationBehavior = null;
  39264. }
  39265. },
  39266. enumerable: true,
  39267. configurable: true
  39268. });
  39269. // Cache
  39270. ArcRotateCamera.prototype._initCache = function () {
  39271. _super.prototype._initCache.call(this);
  39272. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39273. this._cache.alpha = undefined;
  39274. this._cache.beta = undefined;
  39275. this._cache.radius = undefined;
  39276. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  39277. };
  39278. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  39279. if (!ignoreParentClass) {
  39280. _super.prototype._updateCache.call(this);
  39281. }
  39282. this._cache._target.copyFrom(this._getTargetPosition());
  39283. this._cache.alpha = this.alpha;
  39284. this._cache.beta = this.beta;
  39285. this._cache.radius = this.radius;
  39286. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  39287. };
  39288. ArcRotateCamera.prototype._getTargetPosition = function () {
  39289. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  39290. var pos = this._targetHost.getAbsolutePosition();
  39291. if (this._targetBoundingCenter) {
  39292. pos.addToRef(this._targetBoundingCenter, this._target);
  39293. }
  39294. else {
  39295. this._target.copyFrom(pos);
  39296. }
  39297. }
  39298. var lockedTargetPosition = this._getLockedTargetPosition();
  39299. if (lockedTargetPosition) {
  39300. return lockedTargetPosition;
  39301. }
  39302. return this._target;
  39303. };
  39304. ArcRotateCamera.prototype.storeState = function () {
  39305. this._storedAlpha = this.alpha;
  39306. this._storedBeta = this.beta;
  39307. this._storedRadius = this.radius;
  39308. this._storedTarget = this._getTargetPosition().clone();
  39309. return _super.prototype.storeState.call(this);
  39310. };
  39311. /**
  39312. * Restored camera state. You must call storeState() first
  39313. */
  39314. ArcRotateCamera.prototype._restoreStateValues = function () {
  39315. if (!_super.prototype._restoreStateValues.call(this)) {
  39316. return false;
  39317. }
  39318. this.alpha = this._storedAlpha;
  39319. this.beta = this._storedBeta;
  39320. this.radius = this._storedRadius;
  39321. this.setTarget(this._storedTarget.clone());
  39322. this.inertialAlphaOffset = 0;
  39323. this.inertialBetaOffset = 0;
  39324. this.inertialRadiusOffset = 0;
  39325. this.inertialPanningX = 0;
  39326. this.inertialPanningY = 0;
  39327. return true;
  39328. };
  39329. // Synchronized
  39330. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  39331. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  39332. return false;
  39333. return this._cache._target.equals(this._getTargetPosition())
  39334. && this._cache.alpha === this.alpha
  39335. && this._cache.beta === this.beta
  39336. && this._cache.radius === this.radius
  39337. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  39338. };
  39339. // Methods
  39340. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  39341. var _this = this;
  39342. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  39343. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  39344. this._useCtrlForPanning = useCtrlForPanning;
  39345. this._panningMouseButton = panningMouseButton;
  39346. this.inputs.attachElement(element, noPreventDefault);
  39347. this._reset = function () {
  39348. _this.inertialAlphaOffset = 0;
  39349. _this.inertialBetaOffset = 0;
  39350. _this.inertialRadiusOffset = 0;
  39351. _this.inertialPanningX = 0;
  39352. _this.inertialPanningY = 0;
  39353. };
  39354. };
  39355. ArcRotateCamera.prototype.detachControl = function (element) {
  39356. this.inputs.detachElement(element);
  39357. if (this._reset) {
  39358. this._reset();
  39359. }
  39360. };
  39361. ArcRotateCamera.prototype._checkInputs = function () {
  39362. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  39363. if (this._collisionTriggered) {
  39364. return;
  39365. }
  39366. this.inputs.checkInputs();
  39367. // Inertia
  39368. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  39369. if (this.getScene().useRightHandedSystem) {
  39370. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39371. }
  39372. else {
  39373. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  39374. }
  39375. this.beta += this.inertialBetaOffset;
  39376. this.radius -= this.inertialRadiusOffset;
  39377. this.inertialAlphaOffset *= this.inertia;
  39378. this.inertialBetaOffset *= this.inertia;
  39379. this.inertialRadiusOffset *= this.inertia;
  39380. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  39381. this.inertialAlphaOffset = 0;
  39382. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  39383. this.inertialBetaOffset = 0;
  39384. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  39385. this.inertialRadiusOffset = 0;
  39386. }
  39387. // Panning inertia
  39388. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  39389. if (!this._localDirection) {
  39390. this._localDirection = BABYLON.Vector3.Zero();
  39391. this._transformedDirection = BABYLON.Vector3.Zero();
  39392. }
  39393. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  39394. this._localDirection.multiplyInPlace(this.panningAxis);
  39395. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  39396. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  39397. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  39398. if (!this.panningAxis.y) {
  39399. this._transformedDirection.y = 0;
  39400. }
  39401. if (!this._targetHost) {
  39402. if (this.panningDistanceLimit) {
  39403. this._transformedDirection.addInPlace(this._target);
  39404. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  39405. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  39406. this._target.copyFrom(this._transformedDirection);
  39407. }
  39408. }
  39409. else {
  39410. this._target.addInPlace(this._transformedDirection);
  39411. }
  39412. }
  39413. this.inertialPanningX *= this.panningInertia;
  39414. this.inertialPanningY *= this.panningInertia;
  39415. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  39416. this.inertialPanningX = 0;
  39417. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  39418. this.inertialPanningY = 0;
  39419. }
  39420. // Limits
  39421. this._checkLimits();
  39422. _super.prototype._checkInputs.call(this);
  39423. };
  39424. ArcRotateCamera.prototype._checkLimits = function () {
  39425. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  39426. if (this.allowUpsideDown && this.beta > Math.PI) {
  39427. this.beta = this.beta - (2 * Math.PI);
  39428. }
  39429. }
  39430. else {
  39431. if (this.beta < this.lowerBetaLimit) {
  39432. this.beta = this.lowerBetaLimit;
  39433. }
  39434. }
  39435. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  39436. if (this.allowUpsideDown && this.beta < -Math.PI) {
  39437. this.beta = this.beta + (2 * Math.PI);
  39438. }
  39439. }
  39440. else {
  39441. if (this.beta > this.upperBetaLimit) {
  39442. this.beta = this.upperBetaLimit;
  39443. }
  39444. }
  39445. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  39446. this.alpha = this.lowerAlphaLimit;
  39447. }
  39448. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  39449. this.alpha = this.upperAlphaLimit;
  39450. }
  39451. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  39452. this.radius = this.lowerRadiusLimit;
  39453. }
  39454. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  39455. this.radius = this.upperRadiusLimit;
  39456. }
  39457. };
  39458. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  39459. var radiusv3 = this.position.subtract(this._getTargetPosition());
  39460. this.radius = radiusv3.length();
  39461. if (this.radius === 0) {
  39462. this.radius = 0.0001; // Just to avoid division by zero
  39463. }
  39464. // Alpha
  39465. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  39466. if (radiusv3.z < 0) {
  39467. this.alpha = 2 * Math.PI - this.alpha;
  39468. }
  39469. // Beta
  39470. this.beta = Math.acos(radiusv3.y / this.radius);
  39471. this._checkLimits();
  39472. };
  39473. ArcRotateCamera.prototype.setPosition = function (position) {
  39474. if (this.position.equals(position)) {
  39475. return;
  39476. }
  39477. this.position.copyFrom(position);
  39478. this.rebuildAnglesAndRadius();
  39479. };
  39480. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  39481. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  39482. if (allowSamePosition === void 0) { allowSamePosition = false; }
  39483. if (target.getBoundingInfo) {
  39484. if (toBoundingCenter) {
  39485. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  39486. }
  39487. else {
  39488. this._targetBoundingCenter = null;
  39489. }
  39490. this._targetHost = target;
  39491. this._target = this._getTargetPosition();
  39492. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  39493. }
  39494. else {
  39495. var newTarget = target;
  39496. var currentTarget = this._getTargetPosition();
  39497. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  39498. return;
  39499. }
  39500. this._targetHost = null;
  39501. this._target = newTarget;
  39502. this._targetBoundingCenter = null;
  39503. this.onMeshTargetChangedObservable.notifyObservers(null);
  39504. }
  39505. this.rebuildAnglesAndRadius();
  39506. };
  39507. ArcRotateCamera.prototype._getViewMatrix = function () {
  39508. // Compute
  39509. var cosa = Math.cos(this.alpha);
  39510. var sina = Math.sin(this.alpha);
  39511. var cosb = Math.cos(this.beta);
  39512. var sinb = Math.sin(this.beta);
  39513. if (sinb === 0) {
  39514. sinb = 0.0001;
  39515. }
  39516. var target = this._getTargetPosition();
  39517. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  39518. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  39519. if (!this._collider) {
  39520. this._collider = new BABYLON.Collider();
  39521. }
  39522. this._collider.radius = this.collisionRadius;
  39523. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  39524. this._collisionTriggered = true;
  39525. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39526. }
  39527. else {
  39528. this.position.copyFrom(this._newPosition);
  39529. var up = this.upVector;
  39530. if (this.allowUpsideDown && sinb < 0) {
  39531. up = up.clone();
  39532. up = up.negate();
  39533. }
  39534. if (this.getScene().useRightHandedSystem) {
  39535. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  39536. }
  39537. else {
  39538. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  39539. }
  39540. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  39541. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  39542. }
  39543. this._currentTarget = target;
  39544. return this._viewMatrix;
  39545. };
  39546. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  39547. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39548. meshes = meshes || this.getScene().meshes;
  39549. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  39550. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  39551. this.radius = distance * this.zoomOnFactor;
  39552. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  39553. };
  39554. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  39555. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39556. var meshesOrMinMaxVector;
  39557. var distance;
  39558. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  39559. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  39560. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  39561. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  39562. }
  39563. else {
  39564. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  39565. meshesOrMinMaxVector = minMaxVectorAndDistance;
  39566. distance = minMaxVectorAndDistance.distance;
  39567. }
  39568. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  39569. if (!doNotUpdateMaxZ) {
  39570. this.maxZ = distance * 2;
  39571. }
  39572. };
  39573. /**
  39574. * @override
  39575. * Override Camera.createRigCamera
  39576. */
  39577. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39578. var alphaShift = 0;
  39579. switch (this.cameraRigMode) {
  39580. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39581. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39582. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39583. case BABYLON.Camera.RIG_MODE_VR:
  39584. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  39585. break;
  39586. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39587. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  39588. break;
  39589. }
  39590. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  39591. rigCam._cameraRigParams = {};
  39592. return rigCam;
  39593. };
  39594. /**
  39595. * @override
  39596. * Override Camera._updateRigCameras
  39597. */
  39598. ArcRotateCamera.prototype._updateRigCameras = function () {
  39599. var camLeft = this._rigCameras[0];
  39600. var camRight = this._rigCameras[1];
  39601. camLeft.beta = camRight.beta = this.beta;
  39602. camLeft.radius = camRight.radius = this.radius;
  39603. switch (this.cameraRigMode) {
  39604. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39605. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39606. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39607. case BABYLON.Camera.RIG_MODE_VR:
  39608. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39609. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39610. break;
  39611. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39612. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39613. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39614. break;
  39615. }
  39616. _super.prototype._updateRigCameras.call(this);
  39617. };
  39618. ArcRotateCamera.prototype.dispose = function () {
  39619. this.inputs.clear();
  39620. _super.prototype.dispose.call(this);
  39621. };
  39622. ArcRotateCamera.prototype.getClassName = function () {
  39623. return "ArcRotateCamera";
  39624. };
  39625. __decorate([
  39626. BABYLON.serialize()
  39627. ], ArcRotateCamera.prototype, "alpha", void 0);
  39628. __decorate([
  39629. BABYLON.serialize()
  39630. ], ArcRotateCamera.prototype, "beta", void 0);
  39631. __decorate([
  39632. BABYLON.serialize()
  39633. ], ArcRotateCamera.prototype, "radius", void 0);
  39634. __decorate([
  39635. BABYLON.serializeAsVector3("target")
  39636. ], ArcRotateCamera.prototype, "_target", void 0);
  39637. __decorate([
  39638. BABYLON.serialize()
  39639. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  39640. __decorate([
  39641. BABYLON.serialize()
  39642. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  39643. __decorate([
  39644. BABYLON.serialize()
  39645. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  39646. __decorate([
  39647. BABYLON.serialize()
  39648. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  39649. __decorate([
  39650. BABYLON.serialize()
  39651. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  39652. __decorate([
  39653. BABYLON.serialize()
  39654. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  39655. __decorate([
  39656. BABYLON.serialize()
  39657. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  39658. __decorate([
  39659. BABYLON.serialize()
  39660. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  39661. __decorate([
  39662. BABYLON.serialize()
  39663. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  39664. __decorate([
  39665. BABYLON.serialize()
  39666. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  39667. __decorate([
  39668. BABYLON.serialize()
  39669. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  39670. __decorate([
  39671. BABYLON.serialize()
  39672. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  39673. __decorate([
  39674. BABYLON.serialize()
  39675. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  39676. __decorate([
  39677. BABYLON.serializeAsVector3()
  39678. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39679. __decorate([
  39680. BABYLON.serialize()
  39681. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39682. __decorate([
  39683. BABYLON.serialize()
  39684. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39685. __decorate([
  39686. BABYLON.serialize()
  39687. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39688. return ArcRotateCamera;
  39689. }(BABYLON.TargetCamera));
  39690. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39691. })(BABYLON || (BABYLON = {}));
  39692. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39693. var BABYLON;
  39694. (function (BABYLON) {
  39695. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39696. __extends(ArcRotateCameraInputsManager, _super);
  39697. function ArcRotateCameraInputsManager(camera) {
  39698. return _super.call(this, camera) || this;
  39699. }
  39700. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39701. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39702. return this;
  39703. };
  39704. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39705. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39706. return this;
  39707. };
  39708. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39709. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39710. return this;
  39711. };
  39712. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39713. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39714. return this;
  39715. };
  39716. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39717. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39718. return this;
  39719. };
  39720. return ArcRotateCameraInputsManager;
  39721. }(BABYLON.CameraInputsManager));
  39722. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39723. })(BABYLON || (BABYLON = {}));
  39724. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39725. var BABYLON;
  39726. (function (BABYLON) {
  39727. var HemisphericLight = /** @class */ (function (_super) {
  39728. __extends(HemisphericLight, _super);
  39729. /**
  39730. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39731. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39732. * The HemisphericLight can't cast shadows.
  39733. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39734. */
  39735. function HemisphericLight(name, direction, scene) {
  39736. var _this = _super.call(this, name, scene) || this;
  39737. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39738. _this.direction = direction || BABYLON.Vector3.Up();
  39739. return _this;
  39740. }
  39741. HemisphericLight.prototype._buildUniformLayout = function () {
  39742. this._uniformBuffer.addUniform("vLightData", 4);
  39743. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39744. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39745. this._uniformBuffer.addUniform("vLightGround", 3);
  39746. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39747. this._uniformBuffer.addUniform("depthValues", 2);
  39748. this._uniformBuffer.create();
  39749. };
  39750. /**
  39751. * Returns the string "HemisphericLight".
  39752. */
  39753. HemisphericLight.prototype.getClassName = function () {
  39754. return "HemisphericLight";
  39755. };
  39756. /**
  39757. * Sets the HemisphericLight direction towards the passed target (Vector3).
  39758. * Returns the updated direction.
  39759. */
  39760. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  39761. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  39762. return this.direction;
  39763. };
  39764. HemisphericLight.prototype.getShadowGenerator = function () {
  39765. return null;
  39766. };
  39767. /**
  39768. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  39769. * Returns the HemisphericLight.
  39770. */
  39771. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  39772. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39773. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  39774. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  39775. return this;
  39776. };
  39777. HemisphericLight.prototype._getWorldMatrix = function () {
  39778. if (!this._worldMatrix) {
  39779. this._worldMatrix = BABYLON.Matrix.Identity();
  39780. }
  39781. return this._worldMatrix;
  39782. };
  39783. /**
  39784. * Returns the integer 3.
  39785. */
  39786. HemisphericLight.prototype.getTypeID = function () {
  39787. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  39788. };
  39789. __decorate([
  39790. BABYLON.serializeAsColor3()
  39791. ], HemisphericLight.prototype, "groundColor", void 0);
  39792. __decorate([
  39793. BABYLON.serializeAsVector3()
  39794. ], HemisphericLight.prototype, "direction", void 0);
  39795. return HemisphericLight;
  39796. }(BABYLON.Light));
  39797. BABYLON.HemisphericLight = HemisphericLight;
  39798. })(BABYLON || (BABYLON = {}));
  39799. //# sourceMappingURL=babylon.hemisphericLight.js.map
  39800. var BABYLON;
  39801. (function (BABYLON) {
  39802. var ShadowLight = /** @class */ (function (_super) {
  39803. __extends(ShadowLight, _super);
  39804. function ShadowLight() {
  39805. var _this = _super !== null && _super.apply(this, arguments) || this;
  39806. _this._needProjectionMatrixCompute = true;
  39807. return _this;
  39808. }
  39809. Object.defineProperty(ShadowLight.prototype, "direction", {
  39810. get: function () {
  39811. return this._direction;
  39812. },
  39813. set: function (value) {
  39814. this._direction = value;
  39815. },
  39816. enumerable: true,
  39817. configurable: true
  39818. });
  39819. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  39820. get: function () {
  39821. return this._shadowMinZ;
  39822. },
  39823. set: function (value) {
  39824. this._shadowMinZ = value;
  39825. this.forceProjectionMatrixCompute();
  39826. },
  39827. enumerable: true,
  39828. configurable: true
  39829. });
  39830. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  39831. get: function () {
  39832. return this._shadowMaxZ;
  39833. },
  39834. set: function (value) {
  39835. this._shadowMaxZ = value;
  39836. this.forceProjectionMatrixCompute();
  39837. },
  39838. enumerable: true,
  39839. configurable: true
  39840. });
  39841. /**
  39842. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  39843. */
  39844. ShadowLight.prototype.computeTransformedInformation = function () {
  39845. if (this.parent && this.parent.getWorldMatrix) {
  39846. if (!this.transformedPosition) {
  39847. this.transformedPosition = BABYLON.Vector3.Zero();
  39848. }
  39849. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  39850. // In case the direction is present.
  39851. if (this.direction) {
  39852. if (!this.transformedDirection) {
  39853. this.transformedDirection = BABYLON.Vector3.Zero();
  39854. }
  39855. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  39856. }
  39857. return true;
  39858. }
  39859. return false;
  39860. };
  39861. /**
  39862. * Return the depth scale used for the shadow map.
  39863. */
  39864. ShadowLight.prototype.getDepthScale = function () {
  39865. return 50.0;
  39866. };
  39867. /**
  39868. * Returns the light direction (Vector3) for any passed face index.
  39869. */
  39870. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  39871. return this.transformedDirection ? this.transformedDirection : this.direction;
  39872. };
  39873. /**
  39874. * Returns the DirectionalLight absolute position in the World.
  39875. */
  39876. ShadowLight.prototype.getAbsolutePosition = function () {
  39877. return this.transformedPosition ? this.transformedPosition : this.position;
  39878. };
  39879. /**
  39880. * Sets the DirectionalLight direction toward the passed target (Vector3).
  39881. * Returns the updated DirectionalLight direction (Vector3).
  39882. */
  39883. ShadowLight.prototype.setDirectionToTarget = function (target) {
  39884. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  39885. return this.direction;
  39886. };
  39887. /**
  39888. * Returns the light rotation (Vector3).
  39889. */
  39890. ShadowLight.prototype.getRotation = function () {
  39891. this.direction.normalize();
  39892. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  39893. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  39894. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  39895. };
  39896. /**
  39897. * Boolean : false by default.
  39898. */
  39899. ShadowLight.prototype.needCube = function () {
  39900. return false;
  39901. };
  39902. /**
  39903. * Specifies wether or not the projection matrix should be recomputed this frame.
  39904. */
  39905. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  39906. return this._needProjectionMatrixCompute;
  39907. };
  39908. /**
  39909. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  39910. */
  39911. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  39912. this._needProjectionMatrixCompute = true;
  39913. };
  39914. /**
  39915. * Get the world matrix of the sahdow lights.
  39916. */
  39917. ShadowLight.prototype._getWorldMatrix = function () {
  39918. if (!this._worldMatrix) {
  39919. this._worldMatrix = BABYLON.Matrix.Identity();
  39920. }
  39921. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  39922. return this._worldMatrix;
  39923. };
  39924. /**
  39925. * Gets the minZ used for shadow according to both the scene and the light.
  39926. * @param activeCamera
  39927. */
  39928. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  39929. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  39930. };
  39931. /**
  39932. * Gets the maxZ used for shadow according to both the scene and the light.
  39933. * @param activeCamera
  39934. */
  39935. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  39936. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  39937. };
  39938. /**
  39939. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  39940. * Returns the light.
  39941. */
  39942. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39943. if (this.customProjectionMatrixBuilder) {
  39944. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  39945. }
  39946. else {
  39947. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39948. }
  39949. return this;
  39950. };
  39951. __decorate([
  39952. BABYLON.serializeAsVector3()
  39953. ], ShadowLight.prototype, "position", void 0);
  39954. __decorate([
  39955. BABYLON.serializeAsVector3()
  39956. ], ShadowLight.prototype, "direction", null);
  39957. __decorate([
  39958. BABYLON.serialize()
  39959. ], ShadowLight.prototype, "shadowMinZ", null);
  39960. __decorate([
  39961. BABYLON.serialize()
  39962. ], ShadowLight.prototype, "shadowMaxZ", null);
  39963. return ShadowLight;
  39964. }(BABYLON.Light));
  39965. BABYLON.ShadowLight = ShadowLight;
  39966. })(BABYLON || (BABYLON = {}));
  39967. //# sourceMappingURL=babylon.shadowLight.js.map
  39968. var BABYLON;
  39969. (function (BABYLON) {
  39970. var PointLight = /** @class */ (function (_super) {
  39971. __extends(PointLight, _super);
  39972. /**
  39973. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  39974. * A PointLight emits the light in every direction.
  39975. * It can cast shadows.
  39976. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  39977. * ```javascript
  39978. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  39979. * ```
  39980. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39981. */
  39982. function PointLight(name, position, scene) {
  39983. var _this = _super.call(this, name, scene) || this;
  39984. _this._shadowAngle = Math.PI / 2;
  39985. _this.position = position;
  39986. return _this;
  39987. }
  39988. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  39989. /**
  39990. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39991. * This specifies what angle the shadow will use to be created.
  39992. *
  39993. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39994. */
  39995. get: function () {
  39996. return this._shadowAngle;
  39997. },
  39998. /**
  39999. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40000. * This specifies what angle the shadow will use to be created.
  40001. *
  40002. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40003. */
  40004. set: function (value) {
  40005. this._shadowAngle = value;
  40006. this.forceProjectionMatrixCompute();
  40007. },
  40008. enumerable: true,
  40009. configurable: true
  40010. });
  40011. Object.defineProperty(PointLight.prototype, "direction", {
  40012. get: function () {
  40013. return this._direction;
  40014. },
  40015. /**
  40016. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40017. */
  40018. set: function (value) {
  40019. var previousNeedCube = this.needCube();
  40020. this._direction = value;
  40021. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40022. this._shadowGenerator.recreateShadowMap();
  40023. }
  40024. },
  40025. enumerable: true,
  40026. configurable: true
  40027. });
  40028. /**
  40029. * Returns the string "PointLight"
  40030. */
  40031. PointLight.prototype.getClassName = function () {
  40032. return "PointLight";
  40033. };
  40034. /**
  40035. * Returns the integer 0.
  40036. */
  40037. PointLight.prototype.getTypeID = function () {
  40038. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40039. };
  40040. /**
  40041. * Specifies wether or not the shadowmap should be a cube texture.
  40042. */
  40043. PointLight.prototype.needCube = function () {
  40044. return !this.direction;
  40045. };
  40046. /**
  40047. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40048. */
  40049. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40050. if (this.direction) {
  40051. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40052. }
  40053. else {
  40054. switch (faceIndex) {
  40055. case 0:
  40056. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40057. case 1:
  40058. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40059. case 2:
  40060. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40061. case 3:
  40062. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40063. case 4:
  40064. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40065. case 5:
  40066. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40067. }
  40068. }
  40069. return BABYLON.Vector3.Zero();
  40070. };
  40071. /**
  40072. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  40073. * - fov = PI / 2
  40074. * - aspect ratio : 1.0
  40075. * - z-near and far equal to the active camera minZ and maxZ.
  40076. * Returns the PointLight.
  40077. */
  40078. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40079. var activeCamera = this.getScene().activeCamera;
  40080. if (!activeCamera) {
  40081. return;
  40082. }
  40083. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40084. };
  40085. PointLight.prototype._buildUniformLayout = function () {
  40086. this._uniformBuffer.addUniform("vLightData", 4);
  40087. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40088. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40089. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40090. this._uniformBuffer.addUniform("depthValues", 2);
  40091. this._uniformBuffer.create();
  40092. };
  40093. /**
  40094. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  40095. * Returns the PointLight.
  40096. */
  40097. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  40098. if (this.computeTransformedInformation()) {
  40099. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  40100. return this;
  40101. }
  40102. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  40103. return this;
  40104. };
  40105. __decorate([
  40106. BABYLON.serialize()
  40107. ], PointLight.prototype, "shadowAngle", null);
  40108. return PointLight;
  40109. }(BABYLON.ShadowLight));
  40110. BABYLON.PointLight = PointLight;
  40111. })(BABYLON || (BABYLON = {}));
  40112. //# sourceMappingURL=babylon.pointLight.js.map
  40113. var BABYLON;
  40114. (function (BABYLON) {
  40115. var DirectionalLight = /** @class */ (function (_super) {
  40116. __extends(DirectionalLight, _super);
  40117. /**
  40118. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  40119. * The directional light is emitted from everywhere in the given direction.
  40120. * It can cast shawdows.
  40121. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40122. */
  40123. function DirectionalLight(name, direction, scene) {
  40124. var _this = _super.call(this, name, scene) || this;
  40125. _this._shadowFrustumSize = 0;
  40126. _this._shadowOrthoScale = 0.5;
  40127. _this.autoUpdateExtends = true;
  40128. // Cache
  40129. _this._orthoLeft = Number.MAX_VALUE;
  40130. _this._orthoRight = Number.MIN_VALUE;
  40131. _this._orthoTop = Number.MIN_VALUE;
  40132. _this._orthoBottom = Number.MAX_VALUE;
  40133. _this.position = direction.scale(-1.0);
  40134. _this.direction = direction;
  40135. return _this;
  40136. }
  40137. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  40138. /**
  40139. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  40140. */
  40141. get: function () {
  40142. return this._shadowFrustumSize;
  40143. },
  40144. /**
  40145. * Specifies a fix frustum size for the shadow generation.
  40146. */
  40147. set: function (value) {
  40148. this._shadowFrustumSize = value;
  40149. this.forceProjectionMatrixCompute();
  40150. },
  40151. enumerable: true,
  40152. configurable: true
  40153. });
  40154. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  40155. get: function () {
  40156. return this._shadowOrthoScale;
  40157. },
  40158. set: function (value) {
  40159. this._shadowOrthoScale = value;
  40160. this.forceProjectionMatrixCompute();
  40161. },
  40162. enumerable: true,
  40163. configurable: true
  40164. });
  40165. /**
  40166. * Returns the string "DirectionalLight".
  40167. */
  40168. DirectionalLight.prototype.getClassName = function () {
  40169. return "DirectionalLight";
  40170. };
  40171. /**
  40172. * Returns the integer 1.
  40173. */
  40174. DirectionalLight.prototype.getTypeID = function () {
  40175. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  40176. };
  40177. /**
  40178. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  40179. * Returns the DirectionalLight Shadow projection matrix.
  40180. */
  40181. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40182. if (this.shadowFrustumSize > 0) {
  40183. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  40184. }
  40185. else {
  40186. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40187. }
  40188. };
  40189. /**
  40190. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  40191. * Returns the DirectionalLight Shadow projection matrix.
  40192. */
  40193. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  40194. var activeCamera = this.getScene().activeCamera;
  40195. if (!activeCamera) {
  40196. return;
  40197. }
  40198. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40199. };
  40200. /**
  40201. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  40202. * Returns the DirectionalLight Shadow projection matrix.
  40203. */
  40204. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40205. var activeCamera = this.getScene().activeCamera;
  40206. if (!activeCamera) {
  40207. return;
  40208. }
  40209. // Check extends
  40210. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  40211. var tempVector3 = BABYLON.Vector3.Zero();
  40212. this._orthoLeft = Number.MAX_VALUE;
  40213. this._orthoRight = Number.MIN_VALUE;
  40214. this._orthoTop = Number.MIN_VALUE;
  40215. this._orthoBottom = Number.MAX_VALUE;
  40216. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  40217. var mesh = renderList[meshIndex];
  40218. if (!mesh) {
  40219. continue;
  40220. }
  40221. var boundingInfo = mesh.getBoundingInfo();
  40222. if (!boundingInfo) {
  40223. continue;
  40224. }
  40225. var boundingBox = boundingInfo.boundingBox;
  40226. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  40227. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  40228. if (tempVector3.x < this._orthoLeft)
  40229. this._orthoLeft = tempVector3.x;
  40230. if (tempVector3.y < this._orthoBottom)
  40231. this._orthoBottom = tempVector3.y;
  40232. if (tempVector3.x > this._orthoRight)
  40233. this._orthoRight = tempVector3.x;
  40234. if (tempVector3.y > this._orthoTop)
  40235. this._orthoTop = tempVector3.y;
  40236. }
  40237. }
  40238. }
  40239. var xOffset = this._orthoRight - this._orthoLeft;
  40240. var yOffset = this._orthoTop - this._orthoBottom;
  40241. 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);
  40242. };
  40243. DirectionalLight.prototype._buildUniformLayout = function () {
  40244. this._uniformBuffer.addUniform("vLightData", 4);
  40245. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40246. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40247. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40248. this._uniformBuffer.addUniform("depthValues", 2);
  40249. this._uniformBuffer.create();
  40250. };
  40251. /**
  40252. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  40253. * Returns the DirectionalLight.
  40254. */
  40255. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  40256. if (this.computeTransformedInformation()) {
  40257. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  40258. return this;
  40259. }
  40260. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  40261. return this;
  40262. };
  40263. /**
  40264. * Gets the minZ used for shadow according to both the scene and the light.
  40265. *
  40266. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40267. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40268. * @param activeCamera
  40269. */
  40270. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  40271. return 1;
  40272. };
  40273. /**
  40274. * Gets the maxZ used for shadow according to both the scene and the light.
  40275. *
  40276. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  40277. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  40278. * @param activeCamera
  40279. */
  40280. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  40281. return 1;
  40282. };
  40283. __decorate([
  40284. BABYLON.serialize()
  40285. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  40286. __decorate([
  40287. BABYLON.serialize()
  40288. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  40289. __decorate([
  40290. BABYLON.serialize()
  40291. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  40292. return DirectionalLight;
  40293. }(BABYLON.ShadowLight));
  40294. BABYLON.DirectionalLight = DirectionalLight;
  40295. })(BABYLON || (BABYLON = {}));
  40296. //# sourceMappingURL=babylon.directionalLight.js.map
  40297. var BABYLON;
  40298. (function (BABYLON) {
  40299. var SpotLight = /** @class */ (function (_super) {
  40300. __extends(SpotLight, _super);
  40301. /**
  40302. * Creates a SpotLight object in the scene with the passed parameters :
  40303. * - `position` (Vector3) is the initial SpotLight position,
  40304. * - `direction` (Vector3) is the initial SpotLight direction,
  40305. * - `angle` (float, in radians) is the spot light cone angle,
  40306. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  40307. * A spot light is a simply light oriented cone.
  40308. * It can cast shadows.
  40309. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40310. */
  40311. function SpotLight(name, position, direction, angle, exponent, scene) {
  40312. var _this = _super.call(this, name, scene) || this;
  40313. _this.position = position;
  40314. _this.direction = direction;
  40315. _this.angle = angle;
  40316. _this.exponent = exponent;
  40317. return _this;
  40318. }
  40319. Object.defineProperty(SpotLight.prototype, "angle", {
  40320. get: function () {
  40321. return this._angle;
  40322. },
  40323. set: function (value) {
  40324. this._angle = value;
  40325. this.forceProjectionMatrixCompute();
  40326. },
  40327. enumerable: true,
  40328. configurable: true
  40329. });
  40330. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  40331. get: function () {
  40332. return this._shadowAngleScale;
  40333. },
  40334. /**
  40335. * Allows scaling the angle of the light for shadow generation only.
  40336. */
  40337. set: function (value) {
  40338. this._shadowAngleScale = value;
  40339. this.forceProjectionMatrixCompute();
  40340. },
  40341. enumerable: true,
  40342. configurable: true
  40343. });
  40344. /**
  40345. * Returns the string "SpotLight".
  40346. */
  40347. SpotLight.prototype.getClassName = function () {
  40348. return "SpotLight";
  40349. };
  40350. /**
  40351. * Returns the integer 2.
  40352. */
  40353. SpotLight.prototype.getTypeID = function () {
  40354. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  40355. };
  40356. /**
  40357. * 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.
  40358. * Returns the SpotLight.
  40359. */
  40360. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40361. var activeCamera = this.getScene().activeCamera;
  40362. if (!activeCamera) {
  40363. return;
  40364. }
  40365. this._shadowAngleScale = this._shadowAngleScale || 1;
  40366. var angle = this._shadowAngleScale * this._angle;
  40367. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  40368. };
  40369. SpotLight.prototype._buildUniformLayout = function () {
  40370. this._uniformBuffer.addUniform("vLightData", 4);
  40371. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40372. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40373. this._uniformBuffer.addUniform("vLightDirection", 3);
  40374. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40375. this._uniformBuffer.addUniform("depthValues", 2);
  40376. this._uniformBuffer.create();
  40377. };
  40378. /**
  40379. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  40380. * Return the SpotLight.
  40381. */
  40382. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  40383. var normalizeDirection;
  40384. if (this.computeTransformedInformation()) {
  40385. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  40386. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  40387. }
  40388. else {
  40389. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  40390. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40391. }
  40392. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  40393. return this;
  40394. };
  40395. __decorate([
  40396. BABYLON.serialize()
  40397. ], SpotLight.prototype, "angle", null);
  40398. __decorate([
  40399. BABYLON.serialize()
  40400. /**
  40401. * Allows scaling the angle of the light for shadow generation only.
  40402. */
  40403. ], SpotLight.prototype, "shadowAngleScale", null);
  40404. __decorate([
  40405. BABYLON.serialize()
  40406. ], SpotLight.prototype, "exponent", void 0);
  40407. return SpotLight;
  40408. }(BABYLON.ShadowLight));
  40409. BABYLON.SpotLight = SpotLight;
  40410. })(BABYLON || (BABYLON = {}));
  40411. //# sourceMappingURL=babylon.spotLight.js.map
  40412. var BABYLON;
  40413. (function (BABYLON) {
  40414. var AnimationRange = /** @class */ (function () {
  40415. function AnimationRange(name, from, to) {
  40416. this.name = name;
  40417. this.from = from;
  40418. this.to = to;
  40419. }
  40420. AnimationRange.prototype.clone = function () {
  40421. return new AnimationRange(this.name, this.from, this.to);
  40422. };
  40423. return AnimationRange;
  40424. }());
  40425. BABYLON.AnimationRange = AnimationRange;
  40426. /**
  40427. * Composed of a frame, and an action function
  40428. */
  40429. var AnimationEvent = /** @class */ (function () {
  40430. function AnimationEvent(frame, action, onlyOnce) {
  40431. this.frame = frame;
  40432. this.action = action;
  40433. this.onlyOnce = onlyOnce;
  40434. this.isDone = false;
  40435. }
  40436. return AnimationEvent;
  40437. }());
  40438. BABYLON.AnimationEvent = AnimationEvent;
  40439. var PathCursor = /** @class */ (function () {
  40440. function PathCursor(path) {
  40441. this.path = path;
  40442. this._onchange = new Array();
  40443. this.value = 0;
  40444. this.animations = new Array();
  40445. }
  40446. PathCursor.prototype.getPoint = function () {
  40447. var point = this.path.getPointAtLengthPosition(this.value);
  40448. return new BABYLON.Vector3(point.x, 0, point.y);
  40449. };
  40450. PathCursor.prototype.moveAhead = function (step) {
  40451. if (step === void 0) { step = 0.002; }
  40452. this.move(step);
  40453. return this;
  40454. };
  40455. PathCursor.prototype.moveBack = function (step) {
  40456. if (step === void 0) { step = 0.002; }
  40457. this.move(-step);
  40458. return this;
  40459. };
  40460. PathCursor.prototype.move = function (step) {
  40461. if (Math.abs(step) > 1) {
  40462. throw "step size should be less than 1.";
  40463. }
  40464. this.value += step;
  40465. this.ensureLimits();
  40466. this.raiseOnChange();
  40467. return this;
  40468. };
  40469. PathCursor.prototype.ensureLimits = function () {
  40470. while (this.value > 1) {
  40471. this.value -= 1;
  40472. }
  40473. while (this.value < 0) {
  40474. this.value += 1;
  40475. }
  40476. return this;
  40477. };
  40478. // used by animation engine
  40479. PathCursor.prototype.raiseOnChange = function () {
  40480. var _this = this;
  40481. this._onchange.forEach(function (f) { return f(_this); });
  40482. return this;
  40483. };
  40484. PathCursor.prototype.onchange = function (f) {
  40485. this._onchange.push(f);
  40486. return this;
  40487. };
  40488. return PathCursor;
  40489. }());
  40490. BABYLON.PathCursor = PathCursor;
  40491. var Animation = /** @class */ (function () {
  40492. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  40493. this.name = name;
  40494. this.targetProperty = targetProperty;
  40495. this.framePerSecond = framePerSecond;
  40496. this.dataType = dataType;
  40497. this.loopMode = loopMode;
  40498. this.enableBlending = enableBlending;
  40499. this._runtimeAnimations = new Array();
  40500. // The set of event that will be linked to this animation
  40501. this._events = new Array();
  40502. this.blendingSpeed = 0.01;
  40503. this._ranges = {};
  40504. this.targetPropertyPath = targetProperty.split(".");
  40505. this.dataType = dataType;
  40506. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  40507. }
  40508. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  40509. var dataType = undefined;
  40510. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  40511. dataType = Animation.ANIMATIONTYPE_FLOAT;
  40512. }
  40513. else if (from instanceof BABYLON.Quaternion) {
  40514. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  40515. }
  40516. else if (from instanceof BABYLON.Vector3) {
  40517. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  40518. }
  40519. else if (from instanceof BABYLON.Vector2) {
  40520. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  40521. }
  40522. else if (from instanceof BABYLON.Color3) {
  40523. dataType = Animation.ANIMATIONTYPE_COLOR3;
  40524. }
  40525. else if (from instanceof BABYLON.Size) {
  40526. dataType = Animation.ANIMATIONTYPE_SIZE;
  40527. }
  40528. if (dataType == undefined) {
  40529. return null;
  40530. }
  40531. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  40532. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  40533. animation.setKeys(keys);
  40534. if (easingFunction !== undefined) {
  40535. animation.setEasingFunction(easingFunction);
  40536. }
  40537. return animation;
  40538. };
  40539. /**
  40540. * Sets up an animation.
  40541. * @param property the property to animate
  40542. * @param animationType the animation type to apply
  40543. * @param easingFunction the easing function used in the animation
  40544. * @returns The created animation
  40545. */
  40546. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  40547. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40548. animation.setEasingFunction(easingFunction);
  40549. return animation;
  40550. };
  40551. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40552. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40553. if (!animation) {
  40554. return null;
  40555. }
  40556. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40557. };
  40558. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40559. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40560. if (!animation) {
  40561. return null;
  40562. }
  40563. node.animations.push(animation);
  40564. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40565. };
  40566. /**
  40567. * Transition property of the Camera to the target Value.
  40568. * @param property The property to transition
  40569. * @param targetValue The target Value of the property
  40570. * @param host The object where the property to animate belongs
  40571. * @param scene Scene used to run the animation
  40572. * @param frameRate Framerate (in frame/s) to use
  40573. * @param transition The transition type we want to use
  40574. * @param duration The duration of the animation, in milliseconds
  40575. * @param onAnimationEnd Call back trigger at the end of the animation.
  40576. */
  40577. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  40578. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  40579. if (duration <= 0) {
  40580. host[property] = targetValue;
  40581. if (onAnimationEnd) {
  40582. onAnimationEnd();
  40583. }
  40584. return null;
  40585. }
  40586. var endFrame = frameRate * (duration / 1000);
  40587. transition.setKeys([{
  40588. frame: 0,
  40589. value: host[property].clone ? host[property].clone() : host[property]
  40590. },
  40591. {
  40592. frame: endFrame,
  40593. value: targetValue
  40594. }]);
  40595. if (!host.animations) {
  40596. host.animations = [];
  40597. }
  40598. host.animations.push(transition);
  40599. var animation = scene.beginAnimation(host, 0, endFrame, false);
  40600. animation.onAnimationEnd = onAnimationEnd;
  40601. return animation;
  40602. };
  40603. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  40604. /**
  40605. * Return the array of runtime animations currently using this animation
  40606. */
  40607. get: function () {
  40608. return this._runtimeAnimations;
  40609. },
  40610. enumerable: true,
  40611. configurable: true
  40612. });
  40613. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  40614. get: function () {
  40615. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  40616. var runtimeAnimation = _a[_i];
  40617. if (!runtimeAnimation.isStopped) {
  40618. return true;
  40619. }
  40620. }
  40621. return false;
  40622. },
  40623. enumerable: true,
  40624. configurable: true
  40625. });
  40626. // Methods
  40627. /**
  40628. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  40629. */
  40630. Animation.prototype.toString = function (fullDetails) {
  40631. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  40632. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  40633. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  40634. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  40635. if (fullDetails) {
  40636. ret += ", Ranges: {";
  40637. var first = true;
  40638. for (var name in this._ranges) {
  40639. if (first) {
  40640. ret += ", ";
  40641. first = false;
  40642. }
  40643. ret += name;
  40644. }
  40645. ret += "}";
  40646. }
  40647. return ret;
  40648. };
  40649. /**
  40650. * Add an event to this animation.
  40651. */
  40652. Animation.prototype.addEvent = function (event) {
  40653. this._events.push(event);
  40654. };
  40655. /**
  40656. * Remove all events found at the given frame
  40657. * @param frame
  40658. */
  40659. Animation.prototype.removeEvents = function (frame) {
  40660. for (var index = 0; index < this._events.length; index++) {
  40661. if (this._events[index].frame === frame) {
  40662. this._events.splice(index, 1);
  40663. index--;
  40664. }
  40665. }
  40666. };
  40667. Animation.prototype.getEvents = function () {
  40668. return this._events;
  40669. };
  40670. Animation.prototype.createRange = function (name, from, to) {
  40671. // check name not already in use; could happen for bones after serialized
  40672. if (!this._ranges[name]) {
  40673. this._ranges[name] = new AnimationRange(name, from, to);
  40674. }
  40675. };
  40676. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40677. if (deleteFrames === void 0) { deleteFrames = true; }
  40678. var range = this._ranges[name];
  40679. if (!range) {
  40680. return;
  40681. }
  40682. if (deleteFrames) {
  40683. var from = range.from;
  40684. var to = range.to;
  40685. // this loop MUST go high to low for multiple splices to work
  40686. for (var key = this._keys.length - 1; key >= 0; key--) {
  40687. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40688. this._keys.splice(key, 1);
  40689. }
  40690. }
  40691. }
  40692. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40693. };
  40694. Animation.prototype.getRange = function (name) {
  40695. return this._ranges[name];
  40696. };
  40697. Animation.prototype.getKeys = function () {
  40698. return this._keys;
  40699. };
  40700. Animation.prototype.getHighestFrame = function () {
  40701. var ret = 0;
  40702. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40703. if (ret < this._keys[key].frame) {
  40704. ret = this._keys[key].frame;
  40705. }
  40706. }
  40707. return ret;
  40708. };
  40709. Animation.prototype.getEasingFunction = function () {
  40710. return this._easingFunction;
  40711. };
  40712. Animation.prototype.setEasingFunction = function (easingFunction) {
  40713. this._easingFunction = easingFunction;
  40714. };
  40715. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40716. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40717. };
  40718. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40719. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40720. };
  40721. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40722. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40723. };
  40724. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40725. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40726. };
  40727. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40728. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40729. };
  40730. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40731. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40732. };
  40733. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40734. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40735. };
  40736. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40737. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40738. };
  40739. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40740. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40741. };
  40742. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40743. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40744. };
  40745. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40746. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40747. };
  40748. Animation.prototype.clone = function () {
  40749. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40750. clone.enableBlending = this.enableBlending;
  40751. clone.blendingSpeed = this.blendingSpeed;
  40752. if (this._keys) {
  40753. clone.setKeys(this._keys);
  40754. }
  40755. if (this._ranges) {
  40756. clone._ranges = {};
  40757. for (var name in this._ranges) {
  40758. var range = this._ranges[name];
  40759. if (!range) {
  40760. continue;
  40761. }
  40762. clone._ranges[name] = range.clone();
  40763. }
  40764. }
  40765. return clone;
  40766. };
  40767. Animation.prototype.setKeys = function (values) {
  40768. this._keys = values.slice(0);
  40769. };
  40770. Animation.prototype.serialize = function () {
  40771. var serializationObject = {};
  40772. serializationObject.name = this.name;
  40773. serializationObject.property = this.targetProperty;
  40774. serializationObject.framePerSecond = this.framePerSecond;
  40775. serializationObject.dataType = this.dataType;
  40776. serializationObject.loopBehavior = this.loopMode;
  40777. serializationObject.enableBlending = this.enableBlending;
  40778. serializationObject.blendingSpeed = this.blendingSpeed;
  40779. var dataType = this.dataType;
  40780. serializationObject.keys = [];
  40781. var keys = this.getKeys();
  40782. for (var index = 0; index < keys.length; index++) {
  40783. var animationKey = keys[index];
  40784. var key = {};
  40785. key.frame = animationKey.frame;
  40786. switch (dataType) {
  40787. case Animation.ANIMATIONTYPE_FLOAT:
  40788. key.values = [animationKey.value];
  40789. break;
  40790. case Animation.ANIMATIONTYPE_QUATERNION:
  40791. case Animation.ANIMATIONTYPE_MATRIX:
  40792. case Animation.ANIMATIONTYPE_VECTOR3:
  40793. case Animation.ANIMATIONTYPE_COLOR3:
  40794. key.values = animationKey.value.asArray();
  40795. break;
  40796. }
  40797. serializationObject.keys.push(key);
  40798. }
  40799. serializationObject.ranges = [];
  40800. for (var name in this._ranges) {
  40801. var source = this._ranges[name];
  40802. if (!source) {
  40803. continue;
  40804. }
  40805. var range = {};
  40806. range.name = name;
  40807. range.from = source.from;
  40808. range.to = source.to;
  40809. serializationObject.ranges.push(range);
  40810. }
  40811. return serializationObject;
  40812. };
  40813. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  40814. get: function () {
  40815. return Animation._ANIMATIONTYPE_FLOAT;
  40816. },
  40817. enumerable: true,
  40818. configurable: true
  40819. });
  40820. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  40821. get: function () {
  40822. return Animation._ANIMATIONTYPE_VECTOR3;
  40823. },
  40824. enumerable: true,
  40825. configurable: true
  40826. });
  40827. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  40828. get: function () {
  40829. return Animation._ANIMATIONTYPE_VECTOR2;
  40830. },
  40831. enumerable: true,
  40832. configurable: true
  40833. });
  40834. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  40835. get: function () {
  40836. return Animation._ANIMATIONTYPE_SIZE;
  40837. },
  40838. enumerable: true,
  40839. configurable: true
  40840. });
  40841. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  40842. get: function () {
  40843. return Animation._ANIMATIONTYPE_QUATERNION;
  40844. },
  40845. enumerable: true,
  40846. configurable: true
  40847. });
  40848. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  40849. get: function () {
  40850. return Animation._ANIMATIONTYPE_MATRIX;
  40851. },
  40852. enumerable: true,
  40853. configurable: true
  40854. });
  40855. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  40856. get: function () {
  40857. return Animation._ANIMATIONTYPE_COLOR3;
  40858. },
  40859. enumerable: true,
  40860. configurable: true
  40861. });
  40862. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  40863. get: function () {
  40864. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  40865. },
  40866. enumerable: true,
  40867. configurable: true
  40868. });
  40869. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  40870. get: function () {
  40871. return Animation._ANIMATIONLOOPMODE_CYCLE;
  40872. },
  40873. enumerable: true,
  40874. configurable: true
  40875. });
  40876. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  40877. get: function () {
  40878. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  40879. },
  40880. enumerable: true,
  40881. configurable: true
  40882. });
  40883. Animation.Parse = function (parsedAnimation) {
  40884. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  40885. var dataType = parsedAnimation.dataType;
  40886. var keys = [];
  40887. var data;
  40888. var index;
  40889. if (parsedAnimation.enableBlending) {
  40890. animation.enableBlending = parsedAnimation.enableBlending;
  40891. }
  40892. if (parsedAnimation.blendingSpeed) {
  40893. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  40894. }
  40895. for (index = 0; index < parsedAnimation.keys.length; index++) {
  40896. var key = parsedAnimation.keys[index];
  40897. var inTangent;
  40898. var outTangent;
  40899. switch (dataType) {
  40900. case Animation.ANIMATIONTYPE_FLOAT:
  40901. data = key.values[0];
  40902. if (key.values.length >= 1) {
  40903. inTangent = key.values[1];
  40904. }
  40905. if (key.values.length >= 2) {
  40906. outTangent = key.values[2];
  40907. }
  40908. break;
  40909. case Animation.ANIMATIONTYPE_QUATERNION:
  40910. data = BABYLON.Quaternion.FromArray(key.values);
  40911. if (key.values.length >= 8) {
  40912. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  40913. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  40914. inTangent = _inTangent;
  40915. }
  40916. }
  40917. if (key.values.length >= 12) {
  40918. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  40919. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  40920. outTangent = _outTangent;
  40921. }
  40922. }
  40923. break;
  40924. case Animation.ANIMATIONTYPE_MATRIX:
  40925. data = BABYLON.Matrix.FromArray(key.values);
  40926. break;
  40927. case Animation.ANIMATIONTYPE_COLOR3:
  40928. data = BABYLON.Color3.FromArray(key.values);
  40929. break;
  40930. case Animation.ANIMATIONTYPE_VECTOR3:
  40931. default:
  40932. data = BABYLON.Vector3.FromArray(key.values);
  40933. break;
  40934. }
  40935. var keyData = {};
  40936. keyData.frame = key.frame;
  40937. keyData.value = data;
  40938. if (inTangent != undefined) {
  40939. keyData.inTangent = inTangent;
  40940. }
  40941. if (outTangent != undefined) {
  40942. keyData.outTangent = outTangent;
  40943. }
  40944. keys.push(keyData);
  40945. }
  40946. animation.setKeys(keys);
  40947. if (parsedAnimation.ranges) {
  40948. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  40949. data = parsedAnimation.ranges[index];
  40950. animation.createRange(data.name, data.from, data.to);
  40951. }
  40952. }
  40953. return animation;
  40954. };
  40955. Animation.AppendSerializedAnimations = function (source, destination) {
  40956. if (source.animations) {
  40957. destination.animations = [];
  40958. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  40959. var animation = source.animations[animationIndex];
  40960. destination.animations.push(animation.serialize());
  40961. }
  40962. }
  40963. };
  40964. Animation.AllowMatricesInterpolation = false;
  40965. // Statics
  40966. Animation._ANIMATIONTYPE_FLOAT = 0;
  40967. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  40968. Animation._ANIMATIONTYPE_QUATERNION = 2;
  40969. Animation._ANIMATIONTYPE_MATRIX = 3;
  40970. Animation._ANIMATIONTYPE_COLOR3 = 4;
  40971. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  40972. Animation._ANIMATIONTYPE_SIZE = 6;
  40973. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  40974. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  40975. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  40976. return Animation;
  40977. }());
  40978. BABYLON.Animation = Animation;
  40979. })(BABYLON || (BABYLON = {}));
  40980. //# sourceMappingURL=babylon.animation.js.map
  40981. var BABYLON;
  40982. (function (BABYLON) {
  40983. var RuntimeAnimation = /** @class */ (function () {
  40984. function RuntimeAnimation(target, animation) {
  40985. this._offsetsCache = {};
  40986. this._highLimitsCache = {};
  40987. this._stopped = false;
  40988. this._blendingFactor = 0;
  40989. this._ratioOffset = 0;
  40990. this._animation = animation;
  40991. this._target = target;
  40992. animation._runtimeAnimations.push(this);
  40993. }
  40994. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  40995. get: function () {
  40996. return this._animation;
  40997. },
  40998. enumerable: true,
  40999. configurable: true
  41000. });
  41001. RuntimeAnimation.prototype.reset = function () {
  41002. this._offsetsCache = {};
  41003. this._highLimitsCache = {};
  41004. this.currentFrame = 0;
  41005. this._blendingFactor = 0;
  41006. this._originalBlendValue = null;
  41007. };
  41008. RuntimeAnimation.prototype.isStopped = function () {
  41009. return this._stopped;
  41010. };
  41011. RuntimeAnimation.prototype.dispose = function () {
  41012. var index = this._animation.runtimeAnimations.indexOf(this);
  41013. if (index > -1) {
  41014. this._animation.runtimeAnimations.splice(index, 1);
  41015. }
  41016. };
  41017. RuntimeAnimation.prototype._getKeyValue = function (value) {
  41018. if (typeof value === "function") {
  41019. return value();
  41020. }
  41021. return value;
  41022. };
  41023. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  41024. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  41025. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  41026. }
  41027. this.currentFrame = currentFrame;
  41028. var keys = this._animation.getKeys();
  41029. // Try to get a hash to find the right key
  41030. 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));
  41031. if (keys[startKeyIndex].frame >= currentFrame) {
  41032. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  41033. startKeyIndex--;
  41034. }
  41035. }
  41036. for (var key = startKeyIndex; key < keys.length; key++) {
  41037. var endKey = keys[key + 1];
  41038. if (endKey.frame >= currentFrame) {
  41039. var startKey = keys[key];
  41040. var startValue = this._getKeyValue(startKey.value);
  41041. var endValue = this._getKeyValue(endKey.value);
  41042. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  41043. var frameDelta = endKey.frame - startKey.frame;
  41044. // gradient : percent of currentFrame between the frame inf and the frame sup
  41045. var gradient = (currentFrame - startKey.frame) / frameDelta;
  41046. // check for easingFunction and correction of gradient
  41047. var easingFunction = this._animation.getEasingFunction();
  41048. if (easingFunction != null) {
  41049. gradient = easingFunction.ease(gradient);
  41050. }
  41051. switch (this._animation.dataType) {
  41052. // Float
  41053. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41054. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  41055. switch (loopMode) {
  41056. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41057. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41058. return floatValue;
  41059. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41060. return offsetValue * repeatCount + floatValue;
  41061. }
  41062. break;
  41063. // Quaternion
  41064. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41065. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  41066. switch (loopMode) {
  41067. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41068. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41069. return quatValue;
  41070. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41071. return quatValue.add(offsetValue.scale(repeatCount));
  41072. }
  41073. return quatValue;
  41074. // Vector3
  41075. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41076. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  41077. switch (loopMode) {
  41078. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41079. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41080. return vec3Value;
  41081. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41082. return vec3Value.add(offsetValue.scale(repeatCount));
  41083. }
  41084. // Vector2
  41085. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41086. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  41087. switch (loopMode) {
  41088. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41089. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41090. return vec2Value;
  41091. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41092. return vec2Value.add(offsetValue.scale(repeatCount));
  41093. }
  41094. // Size
  41095. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41096. switch (loopMode) {
  41097. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41098. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41099. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  41100. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41101. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41102. }
  41103. // Color3
  41104. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41105. switch (loopMode) {
  41106. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41107. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41108. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  41109. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41110. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  41111. }
  41112. // Matrix
  41113. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  41114. switch (loopMode) {
  41115. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  41116. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  41117. if (BABYLON.Animation.AllowMatricesInterpolation) {
  41118. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  41119. }
  41120. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  41121. return startValue;
  41122. }
  41123. default:
  41124. break;
  41125. }
  41126. break;
  41127. }
  41128. }
  41129. return this._getKeyValue(keys[keys.length - 1].value);
  41130. };
  41131. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  41132. if (blend === void 0) { blend = false; }
  41133. // Set value
  41134. var path;
  41135. var destination;
  41136. var targetPropertyPath = this._animation.targetPropertyPath;
  41137. if (targetPropertyPath.length > 1) {
  41138. var property = this._target[targetPropertyPath[0]];
  41139. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  41140. property = property[targetPropertyPath[index]];
  41141. }
  41142. path = targetPropertyPath[targetPropertyPath.length - 1];
  41143. destination = property;
  41144. }
  41145. else {
  41146. path = targetPropertyPath[0];
  41147. destination = this._target;
  41148. }
  41149. // Blending
  41150. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  41151. if (!this._originalBlendValue) {
  41152. if (destination[path].clone) {
  41153. this._originalBlendValue = destination[path].clone();
  41154. }
  41155. else {
  41156. this._originalBlendValue = destination[path];
  41157. }
  41158. }
  41159. if (this._originalBlendValue.prototype) {
  41160. if (this._originalBlendValue.prototype.Lerp) {
  41161. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  41162. }
  41163. else {
  41164. destination[path] = currentValue;
  41165. }
  41166. }
  41167. else if (this._originalBlendValue.m) {
  41168. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  41169. }
  41170. else {
  41171. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  41172. }
  41173. this._blendingFactor += this._animation.blendingSpeed;
  41174. }
  41175. else {
  41176. destination[path] = currentValue;
  41177. }
  41178. if (this._target.markAsDirty) {
  41179. this._target.markAsDirty(this._animation.targetProperty);
  41180. }
  41181. };
  41182. RuntimeAnimation.prototype.goToFrame = function (frame) {
  41183. var keys = this._animation.getKeys();
  41184. if (frame < keys[0].frame) {
  41185. frame = keys[0].frame;
  41186. }
  41187. else if (frame > keys[keys.length - 1].frame) {
  41188. frame = keys[keys.length - 1].frame;
  41189. }
  41190. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  41191. this.setValue(currentValue);
  41192. };
  41193. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  41194. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  41195. this._ratioOffset = this._previousRatio - newRatio;
  41196. };
  41197. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  41198. if (blend === void 0) { blend = false; }
  41199. var targetPropertyPath = this._animation.targetPropertyPath;
  41200. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  41201. this._stopped = true;
  41202. return false;
  41203. }
  41204. var returnValue = true;
  41205. var keys = this._animation.getKeys();
  41206. // Adding a start key at frame 0 if missing
  41207. if (keys[0].frame !== 0) {
  41208. var newKey = { frame: 0, value: keys[0].value };
  41209. keys.splice(0, 0, newKey);
  41210. }
  41211. // Check limits
  41212. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  41213. from = keys[0].frame;
  41214. }
  41215. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  41216. to = keys[keys.length - 1].frame;
  41217. }
  41218. //to and from cannot be the same key
  41219. if (from === to) {
  41220. if (from > keys[0].frame) {
  41221. from--;
  41222. }
  41223. else if (to < keys[keys.length - 1].frame) {
  41224. to++;
  41225. }
  41226. }
  41227. // Compute ratio
  41228. var range = to - from;
  41229. var offsetValue;
  41230. // ratio represents the frame delta between from and to
  41231. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  41232. var highLimitValue = 0;
  41233. this._previousDelay = delay;
  41234. this._previousRatio = ratio;
  41235. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  41236. returnValue = false;
  41237. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  41238. }
  41239. else {
  41240. // Get max value if required
  41241. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  41242. var keyOffset = to.toString() + from.toString();
  41243. if (!this._offsetsCache[keyOffset]) {
  41244. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41245. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  41246. switch (this._animation.dataType) {
  41247. // Float
  41248. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41249. this._offsetsCache[keyOffset] = toValue - fromValue;
  41250. break;
  41251. // Quaternion
  41252. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41253. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41254. break;
  41255. // Vector3
  41256. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41257. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41258. // Vector2
  41259. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41260. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41261. // Size
  41262. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41263. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41264. // Color3
  41265. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41266. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  41267. default:
  41268. break;
  41269. }
  41270. this._highLimitsCache[keyOffset] = toValue;
  41271. }
  41272. highLimitValue = this._highLimitsCache[keyOffset];
  41273. offsetValue = this._offsetsCache[keyOffset];
  41274. }
  41275. }
  41276. if (offsetValue === undefined) {
  41277. switch (this._animation.dataType) {
  41278. // Float
  41279. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  41280. offsetValue = 0;
  41281. break;
  41282. // Quaternion
  41283. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  41284. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  41285. break;
  41286. // Vector3
  41287. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  41288. offsetValue = BABYLON.Vector3.Zero();
  41289. break;
  41290. // Vector2
  41291. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  41292. offsetValue = BABYLON.Vector2.Zero();
  41293. break;
  41294. // Size
  41295. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  41296. offsetValue = BABYLON.Size.Zero();
  41297. break;
  41298. // Color3
  41299. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  41300. offsetValue = BABYLON.Color3.Black();
  41301. }
  41302. }
  41303. // Compute value
  41304. var repeatCount = (ratio / range) >> 0;
  41305. var currentFrame = returnValue ? from + ratio % range : to;
  41306. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  41307. // Set value
  41308. this.setValue(currentValue);
  41309. // Check events
  41310. var events = this._animation.getEvents();
  41311. for (var index = 0; index < events.length; index++) {
  41312. // Make sure current frame has passed event frame and that event frame is within the current range
  41313. // Also, handle both forward and reverse animations
  41314. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  41315. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  41316. var event = events[index];
  41317. if (!event.isDone) {
  41318. // If event should be done only once, remove it.
  41319. if (event.onlyOnce) {
  41320. events.splice(index, 1);
  41321. index--;
  41322. }
  41323. event.isDone = true;
  41324. event.action();
  41325. } // Don't do anything if the event has already be done.
  41326. }
  41327. else if (events[index].isDone && !events[index].onlyOnce) {
  41328. // reset event, the animation is looping
  41329. events[index].isDone = false;
  41330. }
  41331. }
  41332. if (!returnValue) {
  41333. this._stopped = true;
  41334. }
  41335. return returnValue;
  41336. };
  41337. return RuntimeAnimation;
  41338. }());
  41339. BABYLON.RuntimeAnimation = RuntimeAnimation;
  41340. })(BABYLON || (BABYLON = {}));
  41341. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  41342. var BABYLON;
  41343. (function (BABYLON) {
  41344. var Animatable = /** @class */ (function () {
  41345. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  41346. if (fromFrame === void 0) { fromFrame = 0; }
  41347. if (toFrame === void 0) { toFrame = 100; }
  41348. if (loopAnimation === void 0) { loopAnimation = false; }
  41349. if (speedRatio === void 0) { speedRatio = 1.0; }
  41350. this.target = target;
  41351. this.fromFrame = fromFrame;
  41352. this.toFrame = toFrame;
  41353. this.loopAnimation = loopAnimation;
  41354. this.onAnimationEnd = onAnimationEnd;
  41355. this._localDelayOffset = null;
  41356. this._pausedDelay = null;
  41357. this._runtimeAnimations = new Array();
  41358. this._paused = false;
  41359. this._speedRatio = 1;
  41360. this.animationStarted = false;
  41361. if (animations) {
  41362. this.appendAnimations(target, animations);
  41363. }
  41364. this._speedRatio = speedRatio;
  41365. this._scene = scene;
  41366. scene._activeAnimatables.push(this);
  41367. }
  41368. Object.defineProperty(Animatable.prototype, "speedRatio", {
  41369. get: function () {
  41370. return this._speedRatio;
  41371. },
  41372. set: function (value) {
  41373. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  41374. var animation = this._runtimeAnimations[index];
  41375. animation._prepareForSpeedRatioChange(value);
  41376. }
  41377. this._speedRatio = value;
  41378. },
  41379. enumerable: true,
  41380. configurable: true
  41381. });
  41382. // Methods
  41383. Animatable.prototype.getAnimations = function () {
  41384. return this._runtimeAnimations;
  41385. };
  41386. Animatable.prototype.appendAnimations = function (target, animations) {
  41387. for (var index = 0; index < animations.length; index++) {
  41388. var animation = animations[index];
  41389. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  41390. }
  41391. };
  41392. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  41393. var runtimeAnimations = this._runtimeAnimations;
  41394. for (var index = 0; index < runtimeAnimations.length; index++) {
  41395. if (runtimeAnimations[index].animation.targetProperty === property) {
  41396. return runtimeAnimations[index].animation;
  41397. }
  41398. }
  41399. return null;
  41400. };
  41401. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  41402. var runtimeAnimations = this._runtimeAnimations;
  41403. for (var index = 0; index < runtimeAnimations.length; index++) {
  41404. if (runtimeAnimations[index].animation.targetProperty === property) {
  41405. return runtimeAnimations[index];
  41406. }
  41407. }
  41408. return null;
  41409. };
  41410. Animatable.prototype.reset = function () {
  41411. var runtimeAnimations = this._runtimeAnimations;
  41412. for (var index = 0; index < runtimeAnimations.length; index++) {
  41413. runtimeAnimations[index].reset();
  41414. }
  41415. this._localDelayOffset = null;
  41416. this._pausedDelay = null;
  41417. };
  41418. Animatable.prototype.enableBlending = function (blendingSpeed) {
  41419. var runtimeAnimations = this._runtimeAnimations;
  41420. for (var index = 0; index < runtimeAnimations.length; index++) {
  41421. runtimeAnimations[index].animation.enableBlending = true;
  41422. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  41423. }
  41424. };
  41425. Animatable.prototype.disableBlending = function () {
  41426. var runtimeAnimations = this._runtimeAnimations;
  41427. for (var index = 0; index < runtimeAnimations.length; index++) {
  41428. runtimeAnimations[index].animation.enableBlending = false;
  41429. }
  41430. };
  41431. Animatable.prototype.goToFrame = function (frame) {
  41432. var runtimeAnimations = this._runtimeAnimations;
  41433. if (runtimeAnimations[0]) {
  41434. var fps = runtimeAnimations[0].animation.framePerSecond;
  41435. var currentFrame = runtimeAnimations[0].currentFrame;
  41436. var adjustTime = frame - currentFrame;
  41437. var delay = adjustTime * 1000 / fps;
  41438. if (this._localDelayOffset === null) {
  41439. this._localDelayOffset = 0;
  41440. }
  41441. this._localDelayOffset -= delay;
  41442. }
  41443. for (var index = 0; index < runtimeAnimations.length; index++) {
  41444. runtimeAnimations[index].goToFrame(frame);
  41445. }
  41446. };
  41447. Animatable.prototype.pause = function () {
  41448. if (this._paused) {
  41449. return;
  41450. }
  41451. this._paused = true;
  41452. };
  41453. Animatable.prototype.restart = function () {
  41454. this._paused = false;
  41455. };
  41456. Animatable.prototype.stop = function (animationName) {
  41457. if (animationName) {
  41458. var idx = this._scene._activeAnimatables.indexOf(this);
  41459. if (idx > -1) {
  41460. var runtimeAnimations = this._runtimeAnimations;
  41461. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  41462. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  41463. continue;
  41464. }
  41465. runtimeAnimations[index].dispose();
  41466. runtimeAnimations.splice(index, 1);
  41467. }
  41468. if (runtimeAnimations.length == 0) {
  41469. this._scene._activeAnimatables.splice(idx, 1);
  41470. if (this.onAnimationEnd) {
  41471. this.onAnimationEnd();
  41472. }
  41473. }
  41474. }
  41475. }
  41476. else {
  41477. var index = this._scene._activeAnimatables.indexOf(this);
  41478. if (index > -1) {
  41479. this._scene._activeAnimatables.splice(index, 1);
  41480. var runtimeAnimations = this._runtimeAnimations;
  41481. for (var index = 0; index < runtimeAnimations.length; index++) {
  41482. runtimeAnimations[index].dispose();
  41483. }
  41484. if (this.onAnimationEnd) {
  41485. this.onAnimationEnd();
  41486. }
  41487. }
  41488. }
  41489. };
  41490. Animatable.prototype._animate = function (delay) {
  41491. if (this._paused) {
  41492. this.animationStarted = false;
  41493. if (this._pausedDelay === null) {
  41494. this._pausedDelay = delay;
  41495. }
  41496. return true;
  41497. }
  41498. if (this._localDelayOffset === null) {
  41499. this._localDelayOffset = delay;
  41500. }
  41501. else if (this._pausedDelay !== null) {
  41502. this._localDelayOffset += delay - this._pausedDelay;
  41503. this._pausedDelay = null;
  41504. }
  41505. // Animating
  41506. var running = false;
  41507. var runtimeAnimations = this._runtimeAnimations;
  41508. var index;
  41509. for (index = 0; index < runtimeAnimations.length; index++) {
  41510. var animation = runtimeAnimations[index];
  41511. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  41512. running = running || isRunning;
  41513. }
  41514. this.animationStarted = running;
  41515. if (!running) {
  41516. // Remove from active animatables
  41517. index = this._scene._activeAnimatables.indexOf(this);
  41518. this._scene._activeAnimatables.splice(index, 1);
  41519. // Dispose all runtime animations
  41520. for (index = 0; index < runtimeAnimations.length; index++) {
  41521. runtimeAnimations[index].dispose();
  41522. }
  41523. }
  41524. if (!running && this.onAnimationEnd) {
  41525. this.onAnimationEnd();
  41526. this.onAnimationEnd = null;
  41527. }
  41528. return running;
  41529. };
  41530. return Animatable;
  41531. }());
  41532. BABYLON.Animatable = Animatable;
  41533. })(BABYLON || (BABYLON = {}));
  41534. //# sourceMappingURL=babylon.animatable.js.map
  41535. var BABYLON;
  41536. (function (BABYLON) {
  41537. var EasingFunction = /** @class */ (function () {
  41538. function EasingFunction() {
  41539. // Properties
  41540. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  41541. }
  41542. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  41543. get: function () {
  41544. return EasingFunction._EASINGMODE_EASEIN;
  41545. },
  41546. enumerable: true,
  41547. configurable: true
  41548. });
  41549. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  41550. get: function () {
  41551. return EasingFunction._EASINGMODE_EASEOUT;
  41552. },
  41553. enumerable: true,
  41554. configurable: true
  41555. });
  41556. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  41557. get: function () {
  41558. return EasingFunction._EASINGMODE_EASEINOUT;
  41559. },
  41560. enumerable: true,
  41561. configurable: true
  41562. });
  41563. EasingFunction.prototype.setEasingMode = function (easingMode) {
  41564. var n = Math.min(Math.max(easingMode, 0), 2);
  41565. this._easingMode = n;
  41566. };
  41567. EasingFunction.prototype.getEasingMode = function () {
  41568. return this._easingMode;
  41569. };
  41570. EasingFunction.prototype.easeInCore = function (gradient) {
  41571. throw new Error('You must implement this method');
  41572. };
  41573. EasingFunction.prototype.ease = function (gradient) {
  41574. switch (this._easingMode) {
  41575. case EasingFunction.EASINGMODE_EASEIN:
  41576. return this.easeInCore(gradient);
  41577. case EasingFunction.EASINGMODE_EASEOUT:
  41578. return (1 - this.easeInCore(1 - gradient));
  41579. }
  41580. if (gradient >= 0.5) {
  41581. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  41582. }
  41583. return (this.easeInCore(gradient * 2) * 0.5);
  41584. };
  41585. //Statics
  41586. EasingFunction._EASINGMODE_EASEIN = 0;
  41587. EasingFunction._EASINGMODE_EASEOUT = 1;
  41588. EasingFunction._EASINGMODE_EASEINOUT = 2;
  41589. return EasingFunction;
  41590. }());
  41591. BABYLON.EasingFunction = EasingFunction;
  41592. var CircleEase = /** @class */ (function (_super) {
  41593. __extends(CircleEase, _super);
  41594. function CircleEase() {
  41595. return _super !== null && _super.apply(this, arguments) || this;
  41596. }
  41597. CircleEase.prototype.easeInCore = function (gradient) {
  41598. gradient = Math.max(0, Math.min(1, gradient));
  41599. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  41600. };
  41601. return CircleEase;
  41602. }(EasingFunction));
  41603. BABYLON.CircleEase = CircleEase;
  41604. var BackEase = /** @class */ (function (_super) {
  41605. __extends(BackEase, _super);
  41606. function BackEase(amplitude) {
  41607. if (amplitude === void 0) { amplitude = 1; }
  41608. var _this = _super.call(this) || this;
  41609. _this.amplitude = amplitude;
  41610. return _this;
  41611. }
  41612. BackEase.prototype.easeInCore = function (gradient) {
  41613. var num = Math.max(0, this.amplitude);
  41614. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  41615. };
  41616. return BackEase;
  41617. }(EasingFunction));
  41618. BABYLON.BackEase = BackEase;
  41619. var BounceEase = /** @class */ (function (_super) {
  41620. __extends(BounceEase, _super);
  41621. function BounceEase(bounces, bounciness) {
  41622. if (bounces === void 0) { bounces = 3; }
  41623. if (bounciness === void 0) { bounciness = 2; }
  41624. var _this = _super.call(this) || this;
  41625. _this.bounces = bounces;
  41626. _this.bounciness = bounciness;
  41627. return _this;
  41628. }
  41629. BounceEase.prototype.easeInCore = function (gradient) {
  41630. var y = Math.max(0.0, this.bounces);
  41631. var bounciness = this.bounciness;
  41632. if (bounciness <= 1.0) {
  41633. bounciness = 1.001;
  41634. }
  41635. var num9 = Math.pow(bounciness, y);
  41636. var num5 = 1.0 - bounciness;
  41637. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  41638. var num15 = gradient * num4;
  41639. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  41640. var num3 = Math.floor(num65);
  41641. var num13 = num3 + 1.0;
  41642. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  41643. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  41644. var num7 = (num8 + num12) * 0.5;
  41645. var num6 = gradient - num7;
  41646. var num2 = num7 - num8;
  41647. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  41648. };
  41649. return BounceEase;
  41650. }(EasingFunction));
  41651. BABYLON.BounceEase = BounceEase;
  41652. var CubicEase = /** @class */ (function (_super) {
  41653. __extends(CubicEase, _super);
  41654. function CubicEase() {
  41655. return _super !== null && _super.apply(this, arguments) || this;
  41656. }
  41657. CubicEase.prototype.easeInCore = function (gradient) {
  41658. return (gradient * gradient * gradient);
  41659. };
  41660. return CubicEase;
  41661. }(EasingFunction));
  41662. BABYLON.CubicEase = CubicEase;
  41663. var ElasticEase = /** @class */ (function (_super) {
  41664. __extends(ElasticEase, _super);
  41665. function ElasticEase(oscillations, springiness) {
  41666. if (oscillations === void 0) { oscillations = 3; }
  41667. if (springiness === void 0) { springiness = 3; }
  41668. var _this = _super.call(this) || this;
  41669. _this.oscillations = oscillations;
  41670. _this.springiness = springiness;
  41671. return _this;
  41672. }
  41673. ElasticEase.prototype.easeInCore = function (gradient) {
  41674. var num2;
  41675. var num3 = Math.max(0.0, this.oscillations);
  41676. var num = Math.max(0.0, this.springiness);
  41677. if (num == 0) {
  41678. num2 = gradient;
  41679. }
  41680. else {
  41681. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41682. }
  41683. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41684. };
  41685. return ElasticEase;
  41686. }(EasingFunction));
  41687. BABYLON.ElasticEase = ElasticEase;
  41688. var ExponentialEase = /** @class */ (function (_super) {
  41689. __extends(ExponentialEase, _super);
  41690. function ExponentialEase(exponent) {
  41691. if (exponent === void 0) { exponent = 2; }
  41692. var _this = _super.call(this) || this;
  41693. _this.exponent = exponent;
  41694. return _this;
  41695. }
  41696. ExponentialEase.prototype.easeInCore = function (gradient) {
  41697. if (this.exponent <= 0) {
  41698. return gradient;
  41699. }
  41700. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41701. };
  41702. return ExponentialEase;
  41703. }(EasingFunction));
  41704. BABYLON.ExponentialEase = ExponentialEase;
  41705. var PowerEase = /** @class */ (function (_super) {
  41706. __extends(PowerEase, _super);
  41707. function PowerEase(power) {
  41708. if (power === void 0) { power = 2; }
  41709. var _this = _super.call(this) || this;
  41710. _this.power = power;
  41711. return _this;
  41712. }
  41713. PowerEase.prototype.easeInCore = function (gradient) {
  41714. var y = Math.max(0.0, this.power);
  41715. return Math.pow(gradient, y);
  41716. };
  41717. return PowerEase;
  41718. }(EasingFunction));
  41719. BABYLON.PowerEase = PowerEase;
  41720. var QuadraticEase = /** @class */ (function (_super) {
  41721. __extends(QuadraticEase, _super);
  41722. function QuadraticEase() {
  41723. return _super !== null && _super.apply(this, arguments) || this;
  41724. }
  41725. QuadraticEase.prototype.easeInCore = function (gradient) {
  41726. return (gradient * gradient);
  41727. };
  41728. return QuadraticEase;
  41729. }(EasingFunction));
  41730. BABYLON.QuadraticEase = QuadraticEase;
  41731. var QuarticEase = /** @class */ (function (_super) {
  41732. __extends(QuarticEase, _super);
  41733. function QuarticEase() {
  41734. return _super !== null && _super.apply(this, arguments) || this;
  41735. }
  41736. QuarticEase.prototype.easeInCore = function (gradient) {
  41737. return (gradient * gradient * gradient * gradient);
  41738. };
  41739. return QuarticEase;
  41740. }(EasingFunction));
  41741. BABYLON.QuarticEase = QuarticEase;
  41742. var QuinticEase = /** @class */ (function (_super) {
  41743. __extends(QuinticEase, _super);
  41744. function QuinticEase() {
  41745. return _super !== null && _super.apply(this, arguments) || this;
  41746. }
  41747. QuinticEase.prototype.easeInCore = function (gradient) {
  41748. return (gradient * gradient * gradient * gradient * gradient);
  41749. };
  41750. return QuinticEase;
  41751. }(EasingFunction));
  41752. BABYLON.QuinticEase = QuinticEase;
  41753. var SineEase = /** @class */ (function (_super) {
  41754. __extends(SineEase, _super);
  41755. function SineEase() {
  41756. return _super !== null && _super.apply(this, arguments) || this;
  41757. }
  41758. SineEase.prototype.easeInCore = function (gradient) {
  41759. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  41760. };
  41761. return SineEase;
  41762. }(EasingFunction));
  41763. BABYLON.SineEase = SineEase;
  41764. var BezierCurveEase = /** @class */ (function (_super) {
  41765. __extends(BezierCurveEase, _super);
  41766. function BezierCurveEase(x1, y1, x2, y2) {
  41767. if (x1 === void 0) { x1 = 0; }
  41768. if (y1 === void 0) { y1 = 0; }
  41769. if (x2 === void 0) { x2 = 1; }
  41770. if (y2 === void 0) { y2 = 1; }
  41771. var _this = _super.call(this) || this;
  41772. _this.x1 = x1;
  41773. _this.y1 = y1;
  41774. _this.x2 = x2;
  41775. _this.y2 = y2;
  41776. return _this;
  41777. }
  41778. BezierCurveEase.prototype.easeInCore = function (gradient) {
  41779. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  41780. };
  41781. return BezierCurveEase;
  41782. }(EasingFunction));
  41783. BABYLON.BezierCurveEase = BezierCurveEase;
  41784. })(BABYLON || (BABYLON = {}));
  41785. //# sourceMappingURL=babylon.easing.js.map
  41786. var BABYLON;
  41787. (function (BABYLON) {
  41788. var Condition = /** @class */ (function () {
  41789. function Condition(actionManager) {
  41790. this._actionManager = actionManager;
  41791. }
  41792. Condition.prototype.isValid = function () {
  41793. return true;
  41794. };
  41795. Condition.prototype._getProperty = function (propertyPath) {
  41796. return this._actionManager._getProperty(propertyPath);
  41797. };
  41798. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41799. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41800. };
  41801. Condition.prototype.serialize = function () {
  41802. };
  41803. Condition.prototype._serialize = function (serializedCondition) {
  41804. return {
  41805. type: 2,
  41806. children: [],
  41807. name: serializedCondition.name,
  41808. properties: serializedCondition.properties
  41809. };
  41810. };
  41811. return Condition;
  41812. }());
  41813. BABYLON.Condition = Condition;
  41814. var ValueCondition = /** @class */ (function (_super) {
  41815. __extends(ValueCondition, _super);
  41816. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41817. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41818. var _this = _super.call(this, actionManager) || this;
  41819. _this.propertyPath = propertyPath;
  41820. _this.value = value;
  41821. _this.operator = operator;
  41822. _this._target = target;
  41823. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41824. _this._property = _this._getProperty(_this.propertyPath);
  41825. return _this;
  41826. }
  41827. Object.defineProperty(ValueCondition, "IsEqual", {
  41828. get: function () {
  41829. return ValueCondition._IsEqual;
  41830. },
  41831. enumerable: true,
  41832. configurable: true
  41833. });
  41834. Object.defineProperty(ValueCondition, "IsDifferent", {
  41835. get: function () {
  41836. return ValueCondition._IsDifferent;
  41837. },
  41838. enumerable: true,
  41839. configurable: true
  41840. });
  41841. Object.defineProperty(ValueCondition, "IsGreater", {
  41842. get: function () {
  41843. return ValueCondition._IsGreater;
  41844. },
  41845. enumerable: true,
  41846. configurable: true
  41847. });
  41848. Object.defineProperty(ValueCondition, "IsLesser", {
  41849. get: function () {
  41850. return ValueCondition._IsLesser;
  41851. },
  41852. enumerable: true,
  41853. configurable: true
  41854. });
  41855. // Methods
  41856. ValueCondition.prototype.isValid = function () {
  41857. switch (this.operator) {
  41858. case ValueCondition.IsGreater:
  41859. return this._effectiveTarget[this._property] > this.value;
  41860. case ValueCondition.IsLesser:
  41861. return this._effectiveTarget[this._property] < this.value;
  41862. case ValueCondition.IsEqual:
  41863. case ValueCondition.IsDifferent:
  41864. var check;
  41865. if (this.value.equals) {
  41866. check = this.value.equals(this._effectiveTarget[this._property]);
  41867. }
  41868. else {
  41869. check = this.value === this._effectiveTarget[this._property];
  41870. }
  41871. return this.operator === ValueCondition.IsEqual ? check : !check;
  41872. }
  41873. return false;
  41874. };
  41875. ValueCondition.prototype.serialize = function () {
  41876. return this._serialize({
  41877. name: "ValueCondition",
  41878. properties: [
  41879. BABYLON.Action._GetTargetProperty(this._target),
  41880. { name: "propertyPath", value: this.propertyPath },
  41881. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41882. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41883. ]
  41884. });
  41885. };
  41886. ValueCondition.GetOperatorName = function (operator) {
  41887. switch (operator) {
  41888. case ValueCondition._IsEqual: return "IsEqual";
  41889. case ValueCondition._IsDifferent: return "IsDifferent";
  41890. case ValueCondition._IsGreater: return "IsGreater";
  41891. case ValueCondition._IsLesser: return "IsLesser";
  41892. default: return "";
  41893. }
  41894. };
  41895. // Statics
  41896. ValueCondition._IsEqual = 0;
  41897. ValueCondition._IsDifferent = 1;
  41898. ValueCondition._IsGreater = 2;
  41899. ValueCondition._IsLesser = 3;
  41900. return ValueCondition;
  41901. }(Condition));
  41902. BABYLON.ValueCondition = ValueCondition;
  41903. var PredicateCondition = /** @class */ (function (_super) {
  41904. __extends(PredicateCondition, _super);
  41905. function PredicateCondition(actionManager, predicate) {
  41906. var _this = _super.call(this, actionManager) || this;
  41907. _this.predicate = predicate;
  41908. return _this;
  41909. }
  41910. PredicateCondition.prototype.isValid = function () {
  41911. return this.predicate();
  41912. };
  41913. return PredicateCondition;
  41914. }(Condition));
  41915. BABYLON.PredicateCondition = PredicateCondition;
  41916. var StateCondition = /** @class */ (function (_super) {
  41917. __extends(StateCondition, _super);
  41918. function StateCondition(actionManager, target, value) {
  41919. var _this = _super.call(this, actionManager) || this;
  41920. _this.value = value;
  41921. _this._target = target;
  41922. return _this;
  41923. }
  41924. // Methods
  41925. StateCondition.prototype.isValid = function () {
  41926. return this._target.state === this.value;
  41927. };
  41928. StateCondition.prototype.serialize = function () {
  41929. return this._serialize({
  41930. name: "StateCondition",
  41931. properties: [
  41932. BABYLON.Action._GetTargetProperty(this._target),
  41933. { name: "value", value: this.value }
  41934. ]
  41935. });
  41936. };
  41937. return StateCondition;
  41938. }(Condition));
  41939. BABYLON.StateCondition = StateCondition;
  41940. })(BABYLON || (BABYLON = {}));
  41941. //# sourceMappingURL=babylon.condition.js.map
  41942. var BABYLON;
  41943. (function (BABYLON) {
  41944. var Action = /** @class */ (function () {
  41945. function Action(triggerOptions, condition) {
  41946. this.triggerOptions = triggerOptions;
  41947. this.onBeforeExecuteObservable = new BABYLON.Observable();
  41948. if (triggerOptions.parameter) {
  41949. this.trigger = triggerOptions.trigger;
  41950. this._triggerParameter = triggerOptions.parameter;
  41951. }
  41952. else {
  41953. this.trigger = triggerOptions;
  41954. }
  41955. this._nextActiveAction = this;
  41956. this._condition = condition;
  41957. }
  41958. // Methods
  41959. Action.prototype._prepare = function () {
  41960. };
  41961. Action.prototype.getTriggerParameter = function () {
  41962. return this._triggerParameter;
  41963. };
  41964. Action.prototype._executeCurrent = function (evt) {
  41965. if (this._nextActiveAction._condition) {
  41966. var condition = this._nextActiveAction._condition;
  41967. var currentRenderId = this._actionManager.getScene().getRenderId();
  41968. // We cache the current evaluation for the current frame
  41969. if (condition._evaluationId === currentRenderId) {
  41970. if (!condition._currentResult) {
  41971. return;
  41972. }
  41973. }
  41974. else {
  41975. condition._evaluationId = currentRenderId;
  41976. if (!condition.isValid()) {
  41977. condition._currentResult = false;
  41978. return;
  41979. }
  41980. condition._currentResult = true;
  41981. }
  41982. }
  41983. this.onBeforeExecuteObservable.notifyObservers(this);
  41984. this._nextActiveAction.execute(evt);
  41985. this.skipToNextActiveAction();
  41986. };
  41987. Action.prototype.execute = function (evt) {
  41988. };
  41989. Action.prototype.skipToNextActiveAction = function () {
  41990. if (this._nextActiveAction._child) {
  41991. if (!this._nextActiveAction._child._actionManager) {
  41992. this._nextActiveAction._child._actionManager = this._actionManager;
  41993. }
  41994. this._nextActiveAction = this._nextActiveAction._child;
  41995. }
  41996. else {
  41997. this._nextActiveAction = this;
  41998. }
  41999. };
  42000. Action.prototype.then = function (action) {
  42001. this._child = action;
  42002. action._actionManager = this._actionManager;
  42003. action._prepare();
  42004. return action;
  42005. };
  42006. Action.prototype._getProperty = function (propertyPath) {
  42007. return this._actionManager._getProperty(propertyPath);
  42008. };
  42009. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  42010. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42011. };
  42012. Action.prototype.serialize = function (parent) {
  42013. };
  42014. // Called by BABYLON.Action objects in serialize(...). Internal use
  42015. Action.prototype._serialize = function (serializedAction, parent) {
  42016. var serializationObject = {
  42017. type: 1,
  42018. children: [],
  42019. name: serializedAction.name,
  42020. properties: serializedAction.properties || []
  42021. };
  42022. // Serialize child
  42023. if (this._child) {
  42024. this._child.serialize(serializationObject);
  42025. }
  42026. // Check if "this" has a condition
  42027. if (this._condition) {
  42028. var serializedCondition = this._condition.serialize();
  42029. serializedCondition.children.push(serializationObject);
  42030. if (parent) {
  42031. parent.children.push(serializedCondition);
  42032. }
  42033. return serializedCondition;
  42034. }
  42035. if (parent) {
  42036. parent.children.push(serializationObject);
  42037. }
  42038. return serializationObject;
  42039. };
  42040. Action._SerializeValueAsString = function (value) {
  42041. if (typeof value === "number") {
  42042. return value.toString();
  42043. }
  42044. if (typeof value === "boolean") {
  42045. return value ? "true" : "false";
  42046. }
  42047. if (value instanceof BABYLON.Vector2) {
  42048. return value.x + ", " + value.y;
  42049. }
  42050. if (value instanceof BABYLON.Vector3) {
  42051. return value.x + ", " + value.y + ", " + value.z;
  42052. }
  42053. if (value instanceof BABYLON.Color3) {
  42054. return value.r + ", " + value.g + ", " + value.b;
  42055. }
  42056. if (value instanceof BABYLON.Color4) {
  42057. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  42058. }
  42059. return value; // string
  42060. };
  42061. Action._GetTargetProperty = function (target) {
  42062. return {
  42063. name: "target",
  42064. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  42065. : target instanceof BABYLON.Light ? "LightProperties"
  42066. : target instanceof BABYLON.Camera ? "CameraProperties"
  42067. : "SceneProperties",
  42068. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  42069. };
  42070. };
  42071. return Action;
  42072. }());
  42073. BABYLON.Action = Action;
  42074. })(BABYLON || (BABYLON = {}));
  42075. //# sourceMappingURL=babylon.action.js.map
  42076. var BABYLON;
  42077. (function (BABYLON) {
  42078. /**
  42079. * ActionEvent is the event beint sent when an action is triggered.
  42080. */
  42081. var ActionEvent = /** @class */ (function () {
  42082. /**
  42083. * @param source The mesh or sprite that triggered the action.
  42084. * @param pointerX The X mouse cursor position at the time of the event
  42085. * @param pointerY The Y mouse cursor position at the time of the event
  42086. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  42087. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  42088. */
  42089. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  42090. this.source = source;
  42091. this.pointerX = pointerX;
  42092. this.pointerY = pointerY;
  42093. this.meshUnderPointer = meshUnderPointer;
  42094. this.sourceEvent = sourceEvent;
  42095. this.additionalData = additionalData;
  42096. }
  42097. /**
  42098. * Helper function to auto-create an ActionEvent from a source mesh.
  42099. * @param source The source mesh that triggered the event
  42100. * @param evt {Event} The original (browser) event
  42101. */
  42102. ActionEvent.CreateNew = function (source, evt, additionalData) {
  42103. var scene = source.getScene();
  42104. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42105. };
  42106. /**
  42107. * Helper function to auto-create an ActionEvent from a source mesh.
  42108. * @param source The source sprite that triggered the event
  42109. * @param scene Scene associated with the sprite
  42110. * @param evt {Event} The original (browser) event
  42111. */
  42112. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  42113. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42114. };
  42115. /**
  42116. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  42117. * @param scene the scene where the event occurred
  42118. * @param evt {Event} The original (browser) event
  42119. */
  42120. ActionEvent.CreateNewFromScene = function (scene, evt) {
  42121. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  42122. };
  42123. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  42124. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  42125. };
  42126. return ActionEvent;
  42127. }());
  42128. BABYLON.ActionEvent = ActionEvent;
  42129. /**
  42130. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  42131. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  42132. */
  42133. var ActionManager = /** @class */ (function () {
  42134. function ActionManager(scene) {
  42135. // Members
  42136. this.actions = new Array();
  42137. this.hoverCursor = '';
  42138. this._scene = scene;
  42139. scene._actionManagers.push(this);
  42140. }
  42141. Object.defineProperty(ActionManager, "NothingTrigger", {
  42142. get: function () {
  42143. return ActionManager._NothingTrigger;
  42144. },
  42145. enumerable: true,
  42146. configurable: true
  42147. });
  42148. Object.defineProperty(ActionManager, "OnPickTrigger", {
  42149. get: function () {
  42150. return ActionManager._OnPickTrigger;
  42151. },
  42152. enumerable: true,
  42153. configurable: true
  42154. });
  42155. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  42156. get: function () {
  42157. return ActionManager._OnLeftPickTrigger;
  42158. },
  42159. enumerable: true,
  42160. configurable: true
  42161. });
  42162. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  42163. get: function () {
  42164. return ActionManager._OnRightPickTrigger;
  42165. },
  42166. enumerable: true,
  42167. configurable: true
  42168. });
  42169. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  42170. get: function () {
  42171. return ActionManager._OnCenterPickTrigger;
  42172. },
  42173. enumerable: true,
  42174. configurable: true
  42175. });
  42176. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  42177. get: function () {
  42178. return ActionManager._OnPickDownTrigger;
  42179. },
  42180. enumerable: true,
  42181. configurable: true
  42182. });
  42183. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  42184. get: function () {
  42185. return ActionManager._OnDoublePickTrigger;
  42186. },
  42187. enumerable: true,
  42188. configurable: true
  42189. });
  42190. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  42191. get: function () {
  42192. return ActionManager._OnPickUpTrigger;
  42193. },
  42194. enumerable: true,
  42195. configurable: true
  42196. });
  42197. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  42198. /// This trigger will only be raised if you also declared a OnPickDown
  42199. get: function () {
  42200. return ActionManager._OnPickOutTrigger;
  42201. },
  42202. enumerable: true,
  42203. configurable: true
  42204. });
  42205. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  42206. get: function () {
  42207. return ActionManager._OnLongPressTrigger;
  42208. },
  42209. enumerable: true,
  42210. configurable: true
  42211. });
  42212. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  42213. get: function () {
  42214. return ActionManager._OnPointerOverTrigger;
  42215. },
  42216. enumerable: true,
  42217. configurable: true
  42218. });
  42219. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  42220. get: function () {
  42221. return ActionManager._OnPointerOutTrigger;
  42222. },
  42223. enumerable: true,
  42224. configurable: true
  42225. });
  42226. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  42227. get: function () {
  42228. return ActionManager._OnEveryFrameTrigger;
  42229. },
  42230. enumerable: true,
  42231. configurable: true
  42232. });
  42233. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  42234. get: function () {
  42235. return ActionManager._OnIntersectionEnterTrigger;
  42236. },
  42237. enumerable: true,
  42238. configurable: true
  42239. });
  42240. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  42241. get: function () {
  42242. return ActionManager._OnIntersectionExitTrigger;
  42243. },
  42244. enumerable: true,
  42245. configurable: true
  42246. });
  42247. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  42248. get: function () {
  42249. return ActionManager._OnKeyDownTrigger;
  42250. },
  42251. enumerable: true,
  42252. configurable: true
  42253. });
  42254. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  42255. get: function () {
  42256. return ActionManager._OnKeyUpTrigger;
  42257. },
  42258. enumerable: true,
  42259. configurable: true
  42260. });
  42261. // Methods
  42262. ActionManager.prototype.dispose = function () {
  42263. var index = this._scene._actionManagers.indexOf(this);
  42264. for (var i = 0; i < this.actions.length; i++) {
  42265. var action = this.actions[i];
  42266. ActionManager.Triggers[action.trigger]--;
  42267. if (ActionManager.Triggers[action.trigger] === 0) {
  42268. delete ActionManager.Triggers[action.trigger];
  42269. }
  42270. }
  42271. if (index > -1) {
  42272. this._scene._actionManagers.splice(index, 1);
  42273. }
  42274. };
  42275. ActionManager.prototype.getScene = function () {
  42276. return this._scene;
  42277. };
  42278. /**
  42279. * Does this action manager handles actions of any of the given triggers
  42280. * @param {number[]} triggers - the triggers to be tested
  42281. * @return {boolean} whether one (or more) of the triggers is handeled
  42282. */
  42283. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  42284. for (var index = 0; index < this.actions.length; index++) {
  42285. var action = this.actions[index];
  42286. if (triggers.indexOf(action.trigger) > -1) {
  42287. return true;
  42288. }
  42289. }
  42290. return false;
  42291. };
  42292. /**
  42293. * Does this action manager handles actions of a given trigger
  42294. * @param {number} trigger - the trigger to be tested
  42295. * @return {boolean} whether the trigger is handeled
  42296. */
  42297. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  42298. for (var index = 0; index < this.actions.length; index++) {
  42299. var action = this.actions[index];
  42300. if (action.trigger === trigger) {
  42301. return true;
  42302. }
  42303. }
  42304. return false;
  42305. };
  42306. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  42307. /**
  42308. * Does this action manager has pointer triggers
  42309. * @return {boolean} whether or not it has pointer triggers
  42310. */
  42311. get: function () {
  42312. for (var index = 0; index < this.actions.length; index++) {
  42313. var action = this.actions[index];
  42314. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  42315. return true;
  42316. }
  42317. }
  42318. return false;
  42319. },
  42320. enumerable: true,
  42321. configurable: true
  42322. });
  42323. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  42324. /**
  42325. * Does this action manager has pick triggers
  42326. * @return {boolean} whether or not it has pick triggers
  42327. */
  42328. get: function () {
  42329. for (var index = 0; index < this.actions.length; index++) {
  42330. var action = this.actions[index];
  42331. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  42332. return true;
  42333. }
  42334. }
  42335. return false;
  42336. },
  42337. enumerable: true,
  42338. configurable: true
  42339. });
  42340. Object.defineProperty(ActionManager, "HasTriggers", {
  42341. /**
  42342. * Does exist one action manager with at least one trigger
  42343. * @return {boolean} whether or not it exists one action manager with one trigger
  42344. **/
  42345. get: function () {
  42346. for (var t in ActionManager.Triggers) {
  42347. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42348. return true;
  42349. }
  42350. }
  42351. return false;
  42352. },
  42353. enumerable: true,
  42354. configurable: true
  42355. });
  42356. Object.defineProperty(ActionManager, "HasPickTriggers", {
  42357. /**
  42358. * Does exist one action manager with at least one pick trigger
  42359. * @return {boolean} whether or not it exists one action manager with one pick trigger
  42360. **/
  42361. get: function () {
  42362. for (var t in ActionManager.Triggers) {
  42363. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42364. var t_int = parseInt(t);
  42365. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  42366. return true;
  42367. }
  42368. }
  42369. }
  42370. return false;
  42371. },
  42372. enumerable: true,
  42373. configurable: true
  42374. });
  42375. /**
  42376. * Does exist one action manager that handles actions of a given trigger
  42377. * @param {number} trigger - the trigger to be tested
  42378. * @return {boolean} whether the trigger is handeled by at least one action manager
  42379. **/
  42380. ActionManager.HasSpecificTrigger = function (trigger) {
  42381. for (var t in ActionManager.Triggers) {
  42382. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42383. var t_int = parseInt(t);
  42384. if (t_int === trigger) {
  42385. return true;
  42386. }
  42387. }
  42388. }
  42389. return false;
  42390. };
  42391. /**
  42392. * Registers an action to this action manager
  42393. * @param {BABYLON.Action} action - the action to be registered
  42394. * @return {BABYLON.Action} the action amended (prepared) after registration
  42395. */
  42396. ActionManager.prototype.registerAction = function (action) {
  42397. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  42398. if (this.getScene().actionManager !== this) {
  42399. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  42400. return null;
  42401. }
  42402. }
  42403. this.actions.push(action);
  42404. if (ActionManager.Triggers[action.trigger]) {
  42405. ActionManager.Triggers[action.trigger]++;
  42406. }
  42407. else {
  42408. ActionManager.Triggers[action.trigger] = 1;
  42409. }
  42410. action._actionManager = this;
  42411. action._prepare();
  42412. return action;
  42413. };
  42414. /**
  42415. * Process a specific trigger
  42416. * @param {number} trigger - the trigger to process
  42417. * @param evt {BABYLON.ActionEvent} the event details to be processed
  42418. */
  42419. ActionManager.prototype.processTrigger = function (trigger, evt) {
  42420. for (var index = 0; index < this.actions.length; index++) {
  42421. var action = this.actions[index];
  42422. if (action.trigger === trigger) {
  42423. if (evt) {
  42424. if (trigger === ActionManager.OnKeyUpTrigger
  42425. || trigger === ActionManager.OnKeyDownTrigger) {
  42426. var parameter = action.getTriggerParameter();
  42427. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  42428. if (!parameter.toLowerCase) {
  42429. continue;
  42430. }
  42431. var lowerCase = parameter.toLowerCase();
  42432. if (lowerCase !== evt.sourceEvent.key) {
  42433. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  42434. var actualkey = String.fromCharCode(unicode).toLowerCase();
  42435. if (actualkey !== lowerCase) {
  42436. continue;
  42437. }
  42438. }
  42439. }
  42440. }
  42441. }
  42442. action._executeCurrent(evt);
  42443. }
  42444. }
  42445. };
  42446. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  42447. var properties = propertyPath.split(".");
  42448. for (var index = 0; index < properties.length - 1; index++) {
  42449. target = target[properties[index]];
  42450. }
  42451. return target;
  42452. };
  42453. ActionManager.prototype._getProperty = function (propertyPath) {
  42454. var properties = propertyPath.split(".");
  42455. return properties[properties.length - 1];
  42456. };
  42457. ActionManager.prototype.serialize = function (name) {
  42458. var root = {
  42459. children: new Array(),
  42460. name: name,
  42461. type: 3,
  42462. properties: new Array() // Empty for root but required
  42463. };
  42464. for (var i = 0; i < this.actions.length; i++) {
  42465. var triggerObject = {
  42466. type: 0,
  42467. children: new Array(),
  42468. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  42469. properties: new Array()
  42470. };
  42471. var triggerOptions = this.actions[i].triggerOptions;
  42472. if (triggerOptions && typeof triggerOptions !== "number") {
  42473. if (triggerOptions.parameter instanceof BABYLON.Node) {
  42474. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  42475. }
  42476. else {
  42477. var parameter = {};
  42478. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  42479. if (triggerOptions.parameter.mesh) {
  42480. parameter._meshId = triggerOptions.parameter.mesh.id;
  42481. }
  42482. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  42483. }
  42484. }
  42485. // Serialize child action, recursively
  42486. this.actions[i].serialize(triggerObject);
  42487. // Add serialized trigger
  42488. root.children.push(triggerObject);
  42489. }
  42490. return root;
  42491. };
  42492. ActionManager.Parse = function (parsedActions, object, scene) {
  42493. var actionManager = new BABYLON.ActionManager(scene);
  42494. if (object === null)
  42495. scene.actionManager = actionManager;
  42496. else
  42497. object.actionManager = actionManager;
  42498. // instanciate a new object
  42499. var instanciate = function (name, params) {
  42500. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  42501. newInstance.constructor.apply(newInstance, params);
  42502. return newInstance;
  42503. };
  42504. var parseParameter = function (name, value, target, propertyPath) {
  42505. if (propertyPath === null) {
  42506. // String, boolean or float
  42507. var floatValue = parseFloat(value);
  42508. if (value === "true" || value === "false")
  42509. return value === "true";
  42510. else
  42511. return isNaN(floatValue) ? value : floatValue;
  42512. }
  42513. var effectiveTarget = propertyPath.split(".");
  42514. var values = value.split(",");
  42515. // Get effective Target
  42516. for (var i = 0; i < effectiveTarget.length; i++) {
  42517. target = target[effectiveTarget[i]];
  42518. }
  42519. // Return appropriate value with its type
  42520. if (typeof (target) === "boolean")
  42521. return values[0] === "true";
  42522. if (typeof (target) === "string")
  42523. return values[0];
  42524. // Parameters with multiple values such as Vector3 etc.
  42525. var split = new Array();
  42526. for (var i = 0; i < values.length; i++)
  42527. split.push(parseFloat(values[i]));
  42528. if (target instanceof BABYLON.Vector3)
  42529. return BABYLON.Vector3.FromArray(split);
  42530. if (target instanceof BABYLON.Vector4)
  42531. return BABYLON.Vector4.FromArray(split);
  42532. if (target instanceof BABYLON.Color3)
  42533. return BABYLON.Color3.FromArray(split);
  42534. if (target instanceof BABYLON.Color4)
  42535. return BABYLON.Color4.FromArray(split);
  42536. return parseFloat(values[0]);
  42537. };
  42538. // traverse graph per trigger
  42539. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  42540. if (combineArray === void 0) { combineArray = null; }
  42541. if (parsedAction.detached)
  42542. return;
  42543. var parameters = new Array();
  42544. var target = null;
  42545. var propertyPath = null;
  42546. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  42547. // Parameters
  42548. if (parsedAction.type === 2)
  42549. parameters.push(actionManager);
  42550. else
  42551. parameters.push(trigger);
  42552. if (combine) {
  42553. var actions = new Array();
  42554. for (var j = 0; j < parsedAction.combine.length; j++) {
  42555. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  42556. }
  42557. parameters.push(actions);
  42558. }
  42559. else {
  42560. for (var i = 0; i < parsedAction.properties.length; i++) {
  42561. var value = parsedAction.properties[i].value;
  42562. var name = parsedAction.properties[i].name;
  42563. var targetType = parsedAction.properties[i].targetType;
  42564. if (name === "target")
  42565. if (targetType !== null && targetType === "SceneProperties")
  42566. value = target = scene;
  42567. else
  42568. value = target = scene.getNodeByName(value);
  42569. else if (name === "parent")
  42570. value = scene.getNodeByName(value);
  42571. else if (name === "sound")
  42572. value = scene.getSoundByName(value);
  42573. else if (name !== "propertyPath") {
  42574. if (parsedAction.type === 2 && name === "operator")
  42575. value = BABYLON.ValueCondition[value];
  42576. else
  42577. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  42578. }
  42579. else {
  42580. propertyPath = value;
  42581. }
  42582. parameters.push(value);
  42583. }
  42584. }
  42585. if (combineArray === null) {
  42586. parameters.push(condition);
  42587. }
  42588. else {
  42589. parameters.push(null);
  42590. }
  42591. // If interpolate value action
  42592. if (parsedAction.name === "InterpolateValueAction") {
  42593. var param = parameters[parameters.length - 2];
  42594. parameters[parameters.length - 1] = param;
  42595. parameters[parameters.length - 2] = condition;
  42596. }
  42597. // Action or condition(s) and not CombineAction
  42598. var newAction = instanciate(parsedAction.name, parameters);
  42599. if (newAction instanceof BABYLON.Condition && condition !== null) {
  42600. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  42601. if (action)
  42602. action.then(nothing);
  42603. else
  42604. actionManager.registerAction(nothing);
  42605. action = nothing;
  42606. }
  42607. if (combineArray === null) {
  42608. if (newAction instanceof BABYLON.Condition) {
  42609. condition = newAction;
  42610. newAction = action;
  42611. }
  42612. else {
  42613. condition = null;
  42614. if (action)
  42615. action.then(newAction);
  42616. else
  42617. actionManager.registerAction(newAction);
  42618. }
  42619. }
  42620. else {
  42621. combineArray.push(newAction);
  42622. }
  42623. for (var i = 0; i < parsedAction.children.length; i++)
  42624. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42625. };
  42626. // triggers
  42627. for (var i = 0; i < parsedActions.children.length; i++) {
  42628. var triggerParams;
  42629. var trigger = parsedActions.children[i];
  42630. if (trigger.properties.length > 0) {
  42631. var param = trigger.properties[0].value;
  42632. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42633. if (value._meshId) {
  42634. value.mesh = scene.getMeshByID(value._meshId);
  42635. }
  42636. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  42637. }
  42638. else
  42639. triggerParams = ActionManager[trigger.name];
  42640. for (var j = 0; j < trigger.children.length; j++) {
  42641. if (!trigger.detached)
  42642. traverse(trigger.children[j], triggerParams, null, null);
  42643. }
  42644. }
  42645. };
  42646. ActionManager.GetTriggerName = function (trigger) {
  42647. switch (trigger) {
  42648. case 0: return "NothingTrigger";
  42649. case 1: return "OnPickTrigger";
  42650. case 2: return "OnLeftPickTrigger";
  42651. case 3: return "OnRightPickTrigger";
  42652. case 4: return "OnCenterPickTrigger";
  42653. case 5: return "OnPickDownTrigger";
  42654. case 6: return "OnPickUpTrigger";
  42655. case 7: return "OnLongPressTrigger";
  42656. case 8: return "OnPointerOverTrigger";
  42657. case 9: return "OnPointerOutTrigger";
  42658. case 10: return "OnEveryFrameTrigger";
  42659. case 11: return "OnIntersectionEnterTrigger";
  42660. case 12: return "OnIntersectionExitTrigger";
  42661. case 13: return "OnKeyDownTrigger";
  42662. case 14: return "OnKeyUpTrigger";
  42663. case 15: return "OnPickOutTrigger";
  42664. default: return "";
  42665. }
  42666. };
  42667. // Statics
  42668. ActionManager._NothingTrigger = 0;
  42669. ActionManager._OnPickTrigger = 1;
  42670. ActionManager._OnLeftPickTrigger = 2;
  42671. ActionManager._OnRightPickTrigger = 3;
  42672. ActionManager._OnCenterPickTrigger = 4;
  42673. ActionManager._OnPickDownTrigger = 5;
  42674. ActionManager._OnDoublePickTrigger = 6;
  42675. ActionManager._OnPickUpTrigger = 7;
  42676. ActionManager._OnLongPressTrigger = 8;
  42677. ActionManager._OnPointerOverTrigger = 9;
  42678. ActionManager._OnPointerOutTrigger = 10;
  42679. ActionManager._OnEveryFrameTrigger = 11;
  42680. ActionManager._OnIntersectionEnterTrigger = 12;
  42681. ActionManager._OnIntersectionExitTrigger = 13;
  42682. ActionManager._OnKeyDownTrigger = 14;
  42683. ActionManager._OnKeyUpTrigger = 15;
  42684. ActionManager._OnPickOutTrigger = 16;
  42685. ActionManager.Triggers = {};
  42686. return ActionManager;
  42687. }());
  42688. BABYLON.ActionManager = ActionManager;
  42689. })(BABYLON || (BABYLON = {}));
  42690. //# sourceMappingURL=babylon.actionManager.js.map
  42691. var BABYLON;
  42692. (function (BABYLON) {
  42693. var InterpolateValueAction = /** @class */ (function (_super) {
  42694. __extends(InterpolateValueAction, _super);
  42695. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42696. if (duration === void 0) { duration = 1000; }
  42697. var _this = _super.call(this, triggerOptions, condition) || this;
  42698. _this.propertyPath = propertyPath;
  42699. _this.value = value;
  42700. _this.duration = duration;
  42701. _this.stopOtherAnimations = stopOtherAnimations;
  42702. _this.onInterpolationDone = onInterpolationDone;
  42703. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42704. _this._target = _this._effectiveTarget = target;
  42705. return _this;
  42706. }
  42707. InterpolateValueAction.prototype._prepare = function () {
  42708. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42709. this._property = this._getProperty(this.propertyPath);
  42710. };
  42711. InterpolateValueAction.prototype.execute = function () {
  42712. var _this = this;
  42713. var scene = this._actionManager.getScene();
  42714. var keys = [
  42715. {
  42716. frame: 0,
  42717. value: this._effectiveTarget[this._property]
  42718. }, {
  42719. frame: 100,
  42720. value: this.value
  42721. }
  42722. ];
  42723. var dataType;
  42724. if (typeof this.value === "number") {
  42725. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42726. }
  42727. else if (this.value instanceof BABYLON.Color3) {
  42728. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42729. }
  42730. else if (this.value instanceof BABYLON.Vector3) {
  42731. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42732. }
  42733. else if (this.value instanceof BABYLON.Matrix) {
  42734. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42735. }
  42736. else if (this.value instanceof BABYLON.Quaternion) {
  42737. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42738. }
  42739. else {
  42740. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42741. return;
  42742. }
  42743. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42744. animation.setKeys(keys);
  42745. if (this.stopOtherAnimations) {
  42746. scene.stopAnimation(this._effectiveTarget);
  42747. }
  42748. var wrapper = function () {
  42749. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42750. if (_this.onInterpolationDone) {
  42751. _this.onInterpolationDone();
  42752. }
  42753. };
  42754. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  42755. };
  42756. InterpolateValueAction.prototype.serialize = function (parent) {
  42757. return _super.prototype._serialize.call(this, {
  42758. name: "InterpolateValueAction",
  42759. properties: [
  42760. BABYLON.Action._GetTargetProperty(this._target),
  42761. { name: "propertyPath", value: this.propertyPath },
  42762. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42763. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42764. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42765. ]
  42766. }, parent);
  42767. };
  42768. return InterpolateValueAction;
  42769. }(BABYLON.Action));
  42770. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42771. })(BABYLON || (BABYLON = {}));
  42772. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42773. var BABYLON;
  42774. (function (BABYLON) {
  42775. var SwitchBooleanAction = /** @class */ (function (_super) {
  42776. __extends(SwitchBooleanAction, _super);
  42777. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42778. var _this = _super.call(this, triggerOptions, condition) || this;
  42779. _this.propertyPath = propertyPath;
  42780. _this._target = _this._effectiveTarget = target;
  42781. return _this;
  42782. }
  42783. SwitchBooleanAction.prototype._prepare = function () {
  42784. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42785. this._property = this._getProperty(this.propertyPath);
  42786. };
  42787. SwitchBooleanAction.prototype.execute = function () {
  42788. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42789. };
  42790. SwitchBooleanAction.prototype.serialize = function (parent) {
  42791. return _super.prototype._serialize.call(this, {
  42792. name: "SwitchBooleanAction",
  42793. properties: [
  42794. BABYLON.Action._GetTargetProperty(this._target),
  42795. { name: "propertyPath", value: this.propertyPath }
  42796. ]
  42797. }, parent);
  42798. };
  42799. return SwitchBooleanAction;
  42800. }(BABYLON.Action));
  42801. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42802. var SetStateAction = /** @class */ (function (_super) {
  42803. __extends(SetStateAction, _super);
  42804. function SetStateAction(triggerOptions, target, value, condition) {
  42805. var _this = _super.call(this, triggerOptions, condition) || this;
  42806. _this.value = value;
  42807. _this._target = target;
  42808. return _this;
  42809. }
  42810. SetStateAction.prototype.execute = function () {
  42811. this._target.state = this.value;
  42812. };
  42813. SetStateAction.prototype.serialize = function (parent) {
  42814. return _super.prototype._serialize.call(this, {
  42815. name: "SetStateAction",
  42816. properties: [
  42817. BABYLON.Action._GetTargetProperty(this._target),
  42818. { name: "value", value: this.value }
  42819. ]
  42820. }, parent);
  42821. };
  42822. return SetStateAction;
  42823. }(BABYLON.Action));
  42824. BABYLON.SetStateAction = SetStateAction;
  42825. var SetValueAction = /** @class */ (function (_super) {
  42826. __extends(SetValueAction, _super);
  42827. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42828. var _this = _super.call(this, triggerOptions, condition) || this;
  42829. _this.propertyPath = propertyPath;
  42830. _this.value = value;
  42831. _this._target = _this._effectiveTarget = target;
  42832. return _this;
  42833. }
  42834. SetValueAction.prototype._prepare = function () {
  42835. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42836. this._property = this._getProperty(this.propertyPath);
  42837. };
  42838. SetValueAction.prototype.execute = function () {
  42839. this._effectiveTarget[this._property] = this.value;
  42840. if (this._target.markAsDirty) {
  42841. this._target.markAsDirty(this._property);
  42842. }
  42843. };
  42844. SetValueAction.prototype.serialize = function (parent) {
  42845. return _super.prototype._serialize.call(this, {
  42846. name: "SetValueAction",
  42847. properties: [
  42848. BABYLON.Action._GetTargetProperty(this._target),
  42849. { name: "propertyPath", value: this.propertyPath },
  42850. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42851. ]
  42852. }, parent);
  42853. };
  42854. return SetValueAction;
  42855. }(BABYLON.Action));
  42856. BABYLON.SetValueAction = SetValueAction;
  42857. var IncrementValueAction = /** @class */ (function (_super) {
  42858. __extends(IncrementValueAction, _super);
  42859. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42860. var _this = _super.call(this, triggerOptions, condition) || this;
  42861. _this.propertyPath = propertyPath;
  42862. _this.value = value;
  42863. _this._target = _this._effectiveTarget = target;
  42864. return _this;
  42865. }
  42866. IncrementValueAction.prototype._prepare = function () {
  42867. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42868. this._property = this._getProperty(this.propertyPath);
  42869. if (typeof this._effectiveTarget[this._property] !== "number") {
  42870. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42871. }
  42872. };
  42873. IncrementValueAction.prototype.execute = function () {
  42874. this._effectiveTarget[this._property] += this.value;
  42875. if (this._target.markAsDirty) {
  42876. this._target.markAsDirty(this._property);
  42877. }
  42878. };
  42879. IncrementValueAction.prototype.serialize = function (parent) {
  42880. return _super.prototype._serialize.call(this, {
  42881. name: "IncrementValueAction",
  42882. properties: [
  42883. BABYLON.Action._GetTargetProperty(this._target),
  42884. { name: "propertyPath", value: this.propertyPath },
  42885. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42886. ]
  42887. }, parent);
  42888. };
  42889. return IncrementValueAction;
  42890. }(BABYLON.Action));
  42891. BABYLON.IncrementValueAction = IncrementValueAction;
  42892. var PlayAnimationAction = /** @class */ (function (_super) {
  42893. __extends(PlayAnimationAction, _super);
  42894. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  42895. var _this = _super.call(this, triggerOptions, condition) || this;
  42896. _this.from = from;
  42897. _this.to = to;
  42898. _this.loop = loop;
  42899. _this._target = target;
  42900. return _this;
  42901. }
  42902. PlayAnimationAction.prototype._prepare = function () {
  42903. };
  42904. PlayAnimationAction.prototype.execute = function () {
  42905. var scene = this._actionManager.getScene();
  42906. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  42907. };
  42908. PlayAnimationAction.prototype.serialize = function (parent) {
  42909. return _super.prototype._serialize.call(this, {
  42910. name: "PlayAnimationAction",
  42911. properties: [
  42912. BABYLON.Action._GetTargetProperty(this._target),
  42913. { name: "from", value: String(this.from) },
  42914. { name: "to", value: String(this.to) },
  42915. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  42916. ]
  42917. }, parent);
  42918. };
  42919. return PlayAnimationAction;
  42920. }(BABYLON.Action));
  42921. BABYLON.PlayAnimationAction = PlayAnimationAction;
  42922. var StopAnimationAction = /** @class */ (function (_super) {
  42923. __extends(StopAnimationAction, _super);
  42924. function StopAnimationAction(triggerOptions, target, condition) {
  42925. var _this = _super.call(this, triggerOptions, condition) || this;
  42926. _this._target = target;
  42927. return _this;
  42928. }
  42929. StopAnimationAction.prototype._prepare = function () {
  42930. };
  42931. StopAnimationAction.prototype.execute = function () {
  42932. var scene = this._actionManager.getScene();
  42933. scene.stopAnimation(this._target);
  42934. };
  42935. StopAnimationAction.prototype.serialize = function (parent) {
  42936. return _super.prototype._serialize.call(this, {
  42937. name: "StopAnimationAction",
  42938. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  42939. }, parent);
  42940. };
  42941. return StopAnimationAction;
  42942. }(BABYLON.Action));
  42943. BABYLON.StopAnimationAction = StopAnimationAction;
  42944. var DoNothingAction = /** @class */ (function (_super) {
  42945. __extends(DoNothingAction, _super);
  42946. function DoNothingAction(triggerOptions, condition) {
  42947. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  42948. return _super.call(this, triggerOptions, condition) || this;
  42949. }
  42950. DoNothingAction.prototype.execute = function () {
  42951. };
  42952. DoNothingAction.prototype.serialize = function (parent) {
  42953. return _super.prototype._serialize.call(this, {
  42954. name: "DoNothingAction",
  42955. properties: []
  42956. }, parent);
  42957. };
  42958. return DoNothingAction;
  42959. }(BABYLON.Action));
  42960. BABYLON.DoNothingAction = DoNothingAction;
  42961. var CombineAction = /** @class */ (function (_super) {
  42962. __extends(CombineAction, _super);
  42963. function CombineAction(triggerOptions, children, condition) {
  42964. var _this = _super.call(this, triggerOptions, condition) || this;
  42965. _this.children = children;
  42966. return _this;
  42967. }
  42968. CombineAction.prototype._prepare = function () {
  42969. for (var index = 0; index < this.children.length; index++) {
  42970. this.children[index]._actionManager = this._actionManager;
  42971. this.children[index]._prepare();
  42972. }
  42973. };
  42974. CombineAction.prototype.execute = function (evt) {
  42975. for (var index = 0; index < this.children.length; index++) {
  42976. this.children[index].execute(evt);
  42977. }
  42978. };
  42979. CombineAction.prototype.serialize = function (parent) {
  42980. var serializationObject = _super.prototype._serialize.call(this, {
  42981. name: "CombineAction",
  42982. properties: [],
  42983. combine: []
  42984. }, parent);
  42985. for (var i = 0; i < this.children.length; i++) {
  42986. serializationObject.combine.push(this.children[i].serialize(null));
  42987. }
  42988. return serializationObject;
  42989. };
  42990. return CombineAction;
  42991. }(BABYLON.Action));
  42992. BABYLON.CombineAction = CombineAction;
  42993. var ExecuteCodeAction = /** @class */ (function (_super) {
  42994. __extends(ExecuteCodeAction, _super);
  42995. function ExecuteCodeAction(triggerOptions, func, condition) {
  42996. var _this = _super.call(this, triggerOptions, condition) || this;
  42997. _this.func = func;
  42998. return _this;
  42999. }
  43000. ExecuteCodeAction.prototype.execute = function (evt) {
  43001. this.func(evt);
  43002. };
  43003. return ExecuteCodeAction;
  43004. }(BABYLON.Action));
  43005. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  43006. var SetParentAction = /** @class */ (function (_super) {
  43007. __extends(SetParentAction, _super);
  43008. function SetParentAction(triggerOptions, target, parent, condition) {
  43009. var _this = _super.call(this, triggerOptions, condition) || this;
  43010. _this._target = target;
  43011. _this._parent = parent;
  43012. return _this;
  43013. }
  43014. SetParentAction.prototype._prepare = function () {
  43015. };
  43016. SetParentAction.prototype.execute = function () {
  43017. if (this._target.parent === this._parent) {
  43018. return;
  43019. }
  43020. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  43021. invertParentWorldMatrix.invert();
  43022. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  43023. this._target.parent = this._parent;
  43024. };
  43025. SetParentAction.prototype.serialize = function (parent) {
  43026. return _super.prototype._serialize.call(this, {
  43027. name: "SetParentAction",
  43028. properties: [
  43029. BABYLON.Action._GetTargetProperty(this._target),
  43030. BABYLON.Action._GetTargetProperty(this._parent),
  43031. ]
  43032. }, parent);
  43033. };
  43034. return SetParentAction;
  43035. }(BABYLON.Action));
  43036. BABYLON.SetParentAction = SetParentAction;
  43037. var PlaySoundAction = /** @class */ (function (_super) {
  43038. __extends(PlaySoundAction, _super);
  43039. function PlaySoundAction(triggerOptions, sound, condition) {
  43040. var _this = _super.call(this, triggerOptions, condition) || this;
  43041. _this._sound = sound;
  43042. return _this;
  43043. }
  43044. PlaySoundAction.prototype._prepare = function () {
  43045. };
  43046. PlaySoundAction.prototype.execute = function () {
  43047. if (this._sound !== undefined)
  43048. this._sound.play();
  43049. };
  43050. PlaySoundAction.prototype.serialize = function (parent) {
  43051. return _super.prototype._serialize.call(this, {
  43052. name: "PlaySoundAction",
  43053. properties: [{ name: "sound", value: this._sound.name }]
  43054. }, parent);
  43055. };
  43056. return PlaySoundAction;
  43057. }(BABYLON.Action));
  43058. BABYLON.PlaySoundAction = PlaySoundAction;
  43059. var StopSoundAction = /** @class */ (function (_super) {
  43060. __extends(StopSoundAction, _super);
  43061. function StopSoundAction(triggerOptions, sound, condition) {
  43062. var _this = _super.call(this, triggerOptions, condition) || this;
  43063. _this._sound = sound;
  43064. return _this;
  43065. }
  43066. StopSoundAction.prototype._prepare = function () {
  43067. };
  43068. StopSoundAction.prototype.execute = function () {
  43069. if (this._sound !== undefined)
  43070. this._sound.stop();
  43071. };
  43072. StopSoundAction.prototype.serialize = function (parent) {
  43073. return _super.prototype._serialize.call(this, {
  43074. name: "StopSoundAction",
  43075. properties: [{ name: "sound", value: this._sound.name }]
  43076. }, parent);
  43077. };
  43078. return StopSoundAction;
  43079. }(BABYLON.Action));
  43080. BABYLON.StopSoundAction = StopSoundAction;
  43081. })(BABYLON || (BABYLON = {}));
  43082. //# sourceMappingURL=babylon.directActions.js.map
  43083. var BABYLON;
  43084. (function (BABYLON) {
  43085. var SpriteManager = /** @class */ (function () {
  43086. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  43087. if (epsilon === void 0) { epsilon = 0.01; }
  43088. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43089. this.name = name;
  43090. this.sprites = new Array();
  43091. this.renderingGroupId = 0;
  43092. this.layerMask = 0x0FFFFFFF;
  43093. this.fogEnabled = true;
  43094. this.isPickable = false;
  43095. /**
  43096. * An event triggered when the manager is disposed.
  43097. * @type {BABYLON.Observable}
  43098. */
  43099. this.onDisposeObservable = new BABYLON.Observable();
  43100. this._vertexBuffers = {};
  43101. this._capacity = capacity;
  43102. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  43103. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43104. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43105. if (cellSize.width && cellSize.height) {
  43106. this.cellWidth = cellSize.width;
  43107. this.cellHeight = cellSize.height;
  43108. }
  43109. else if (cellSize !== undefined) {
  43110. this.cellWidth = cellSize;
  43111. this.cellHeight = cellSize;
  43112. }
  43113. else {
  43114. return;
  43115. }
  43116. this._epsilon = epsilon;
  43117. this._scene = scene;
  43118. this._scene.spriteManagers.push(this);
  43119. var indices = [];
  43120. var index = 0;
  43121. for (var count = 0; count < capacity; count++) {
  43122. indices.push(index);
  43123. indices.push(index + 1);
  43124. indices.push(index + 2);
  43125. indices.push(index);
  43126. indices.push(index + 2);
  43127. indices.push(index + 3);
  43128. index += 4;
  43129. }
  43130. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  43131. // VBO
  43132. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  43133. this._vertexData = new Float32Array(capacity * 16 * 4);
  43134. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  43135. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  43136. var options = this._buffer.createVertexBuffer("options", 4, 4);
  43137. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  43138. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  43139. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  43140. this._vertexBuffers["options"] = options;
  43141. this._vertexBuffers["cellInfo"] = cellInfo;
  43142. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  43143. // Effects
  43144. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  43145. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  43146. }
  43147. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  43148. set: function (callback) {
  43149. if (this._onDisposeObserver) {
  43150. this.onDisposeObservable.remove(this._onDisposeObserver);
  43151. }
  43152. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  43153. },
  43154. enumerable: true,
  43155. configurable: true
  43156. });
  43157. Object.defineProperty(SpriteManager.prototype, "texture", {
  43158. get: function () {
  43159. return this._spriteTexture;
  43160. },
  43161. set: function (value) {
  43162. this._spriteTexture = value;
  43163. },
  43164. enumerable: true,
  43165. configurable: true
  43166. });
  43167. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  43168. var arrayOffset = index * 16;
  43169. if (offsetX === 0)
  43170. offsetX = this._epsilon;
  43171. else if (offsetX === 1)
  43172. offsetX = 1 - this._epsilon;
  43173. if (offsetY === 0)
  43174. offsetY = this._epsilon;
  43175. else if (offsetY === 1)
  43176. offsetY = 1 - this._epsilon;
  43177. this._vertexData[arrayOffset] = sprite.position.x;
  43178. this._vertexData[arrayOffset + 1] = sprite.position.y;
  43179. this._vertexData[arrayOffset + 2] = sprite.position.z;
  43180. this._vertexData[arrayOffset + 3] = sprite.angle;
  43181. this._vertexData[arrayOffset + 4] = sprite.width;
  43182. this._vertexData[arrayOffset + 5] = sprite.height;
  43183. this._vertexData[arrayOffset + 6] = offsetX;
  43184. this._vertexData[arrayOffset + 7] = offsetY;
  43185. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  43186. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  43187. var offset = (sprite.cellIndex / rowSize) >> 0;
  43188. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  43189. this._vertexData[arrayOffset + 11] = offset;
  43190. // Color
  43191. this._vertexData[arrayOffset + 12] = sprite.color.r;
  43192. this._vertexData[arrayOffset + 13] = sprite.color.g;
  43193. this._vertexData[arrayOffset + 14] = sprite.color.b;
  43194. this._vertexData[arrayOffset + 15] = sprite.color.a;
  43195. };
  43196. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  43197. var count = Math.min(this._capacity, this.sprites.length);
  43198. var min = BABYLON.Vector3.Zero();
  43199. var max = BABYLON.Vector3.Zero();
  43200. var distance = Number.MAX_VALUE;
  43201. var currentSprite = null;
  43202. var cameraSpacePosition = BABYLON.Vector3.Zero();
  43203. var cameraView = camera.getViewMatrix();
  43204. for (var index = 0; index < count; index++) {
  43205. var sprite = this.sprites[index];
  43206. if (!sprite) {
  43207. continue;
  43208. }
  43209. if (predicate) {
  43210. if (!predicate(sprite)) {
  43211. continue;
  43212. }
  43213. }
  43214. else if (!sprite.isPickable) {
  43215. continue;
  43216. }
  43217. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  43218. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  43219. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  43220. if (ray.intersectsBoxMinMax(min, max)) {
  43221. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  43222. if (distance > currentDistance) {
  43223. distance = currentDistance;
  43224. currentSprite = sprite;
  43225. if (fastCheck) {
  43226. break;
  43227. }
  43228. }
  43229. }
  43230. }
  43231. if (currentSprite) {
  43232. var result = new BABYLON.PickingInfo();
  43233. result.hit = true;
  43234. result.pickedSprite = currentSprite;
  43235. result.distance = distance;
  43236. return result;
  43237. }
  43238. return null;
  43239. };
  43240. SpriteManager.prototype.render = function () {
  43241. // Check
  43242. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  43243. return;
  43244. var engine = this._scene.getEngine();
  43245. var baseSize = this._spriteTexture.getBaseSize();
  43246. // Sprites
  43247. var deltaTime = engine.getDeltaTime();
  43248. var max = Math.min(this._capacity, this.sprites.length);
  43249. var rowSize = baseSize.width / this.cellWidth;
  43250. var offset = 0;
  43251. for (var index = 0; index < max; index++) {
  43252. var sprite = this.sprites[index];
  43253. if (!sprite) {
  43254. continue;
  43255. }
  43256. sprite._animate(deltaTime);
  43257. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  43258. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  43259. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  43260. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  43261. }
  43262. this._buffer.update(this._vertexData);
  43263. // Render
  43264. var effect = this._effectBase;
  43265. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43266. effect = this._effectFog;
  43267. }
  43268. engine.enableEffect(effect);
  43269. var viewMatrix = this._scene.getViewMatrix();
  43270. effect.setTexture("diffuseSampler", this._spriteTexture);
  43271. effect.setMatrix("view", viewMatrix);
  43272. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  43273. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  43274. // Fog
  43275. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  43276. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  43277. effect.setColor3("vFogColor", this._scene.fogColor);
  43278. }
  43279. // VBOs
  43280. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  43281. // Draw order
  43282. engine.setDepthFunctionToLessOrEqual();
  43283. effect.setBool("alphaTest", true);
  43284. engine.setColorWrite(false);
  43285. engine.draw(true, 0, max * 6);
  43286. engine.setColorWrite(true);
  43287. effect.setBool("alphaTest", false);
  43288. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  43289. engine.draw(true, 0, max * 6);
  43290. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  43291. };
  43292. SpriteManager.prototype.dispose = function () {
  43293. if (this._buffer) {
  43294. this._buffer.dispose();
  43295. this._buffer = null;
  43296. }
  43297. if (this._indexBuffer) {
  43298. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43299. this._indexBuffer = null;
  43300. }
  43301. if (this._spriteTexture) {
  43302. this._spriteTexture.dispose();
  43303. this._spriteTexture = null;
  43304. }
  43305. // Remove from scene
  43306. var index = this._scene.spriteManagers.indexOf(this);
  43307. this._scene.spriteManagers.splice(index, 1);
  43308. // Callback
  43309. this.onDisposeObservable.notifyObservers(this);
  43310. this.onDisposeObservable.clear();
  43311. };
  43312. return SpriteManager;
  43313. }());
  43314. BABYLON.SpriteManager = SpriteManager;
  43315. })(BABYLON || (BABYLON = {}));
  43316. //# sourceMappingURL=babylon.spriteManager.js.map
  43317. var BABYLON;
  43318. (function (BABYLON) {
  43319. var Sprite = /** @class */ (function () {
  43320. function Sprite(name, manager) {
  43321. this.name = name;
  43322. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  43323. this.width = 1.0;
  43324. this.height = 1.0;
  43325. this.angle = 0;
  43326. this.cellIndex = 0;
  43327. this.invertU = 0;
  43328. this.invertV = 0;
  43329. this.animations = new Array();
  43330. this.isPickable = false;
  43331. this._animationStarted = false;
  43332. this._loopAnimation = false;
  43333. this._fromIndex = 0;
  43334. this._toIndex = 0;
  43335. this._delay = 0;
  43336. this._direction = 1;
  43337. this._time = 0;
  43338. this._manager = manager;
  43339. this._manager.sprites.push(this);
  43340. this.position = BABYLON.Vector3.Zero();
  43341. }
  43342. Object.defineProperty(Sprite.prototype, "size", {
  43343. get: function () {
  43344. return this.width;
  43345. },
  43346. set: function (value) {
  43347. this.width = value;
  43348. this.height = value;
  43349. },
  43350. enumerable: true,
  43351. configurable: true
  43352. });
  43353. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  43354. this._fromIndex = from;
  43355. this._toIndex = to;
  43356. this._loopAnimation = loop;
  43357. this._delay = delay;
  43358. this._animationStarted = true;
  43359. this._direction = from < to ? 1 : -1;
  43360. this.cellIndex = from;
  43361. this._time = 0;
  43362. this._onAnimationEnd = onAnimationEnd;
  43363. };
  43364. Sprite.prototype.stopAnimation = function () {
  43365. this._animationStarted = false;
  43366. };
  43367. Sprite.prototype._animate = function (deltaTime) {
  43368. if (!this._animationStarted)
  43369. return;
  43370. this._time += deltaTime;
  43371. if (this._time > this._delay) {
  43372. this._time = this._time % this._delay;
  43373. this.cellIndex += this._direction;
  43374. if (this.cellIndex > this._toIndex) {
  43375. if (this._loopAnimation) {
  43376. this.cellIndex = this._fromIndex;
  43377. }
  43378. else {
  43379. this.cellIndex = this._toIndex;
  43380. this._animationStarted = false;
  43381. if (this._onAnimationEnd) {
  43382. this._onAnimationEnd();
  43383. }
  43384. if (this.disposeWhenFinishedAnimating) {
  43385. this.dispose();
  43386. }
  43387. }
  43388. }
  43389. }
  43390. };
  43391. Sprite.prototype.dispose = function () {
  43392. for (var i = 0; i < this._manager.sprites.length; i++) {
  43393. if (this._manager.sprites[i] == this) {
  43394. this._manager.sprites.splice(i, 1);
  43395. }
  43396. }
  43397. };
  43398. return Sprite;
  43399. }());
  43400. BABYLON.Sprite = Sprite;
  43401. })(BABYLON || (BABYLON = {}));
  43402. //# sourceMappingURL=babylon.sprite.js.map
  43403. var BABYLON;
  43404. (function (BABYLON) {
  43405. var IntersectionInfo = /** @class */ (function () {
  43406. function IntersectionInfo(bu, bv, distance) {
  43407. this.bu = bu;
  43408. this.bv = bv;
  43409. this.distance = distance;
  43410. this.faceId = 0;
  43411. this.subMeshId = 0;
  43412. }
  43413. return IntersectionInfo;
  43414. }());
  43415. BABYLON.IntersectionInfo = IntersectionInfo;
  43416. var PickingInfo = /** @class */ (function () {
  43417. function PickingInfo() {
  43418. this.hit = false;
  43419. this.distance = 0;
  43420. this.pickedPoint = null;
  43421. this.pickedMesh = null;
  43422. this.bu = 0;
  43423. this.bv = 0;
  43424. this.faceId = -1;
  43425. this.subMeshId = 0;
  43426. this.pickedSprite = null;
  43427. }
  43428. // Methods
  43429. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  43430. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  43431. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  43432. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43433. return null;
  43434. }
  43435. var indices = this.pickedMesh.getIndices();
  43436. if (!indices) {
  43437. return null;
  43438. }
  43439. var result;
  43440. if (useVerticesNormals) {
  43441. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43442. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  43443. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  43444. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  43445. normal0 = normal0.scale(this.bu);
  43446. normal1 = normal1.scale(this.bv);
  43447. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  43448. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  43449. }
  43450. else {
  43451. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43452. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  43453. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  43454. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  43455. var p1p2 = vertex1.subtract(vertex2);
  43456. var p3p2 = vertex3.subtract(vertex2);
  43457. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  43458. }
  43459. if (useWorldCoordinates) {
  43460. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  43461. }
  43462. return BABYLON.Vector3.Normalize(result);
  43463. };
  43464. PickingInfo.prototype.getTextureCoordinates = function () {
  43465. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43466. return null;
  43467. }
  43468. var indices = this.pickedMesh.getIndices();
  43469. if (!indices) {
  43470. return null;
  43471. }
  43472. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43473. if (!uvs) {
  43474. return null;
  43475. }
  43476. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  43477. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  43478. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  43479. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  43480. uv1 = uv1.scale(this.bu);
  43481. uv2 = uv2.scale(this.bv);
  43482. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  43483. };
  43484. return PickingInfo;
  43485. }());
  43486. BABYLON.PickingInfo = PickingInfo;
  43487. })(BABYLON || (BABYLON = {}));
  43488. //# sourceMappingURL=babylon.pickingInfo.js.map
  43489. var BABYLON;
  43490. (function (BABYLON) {
  43491. var Ray = /** @class */ (function () {
  43492. function Ray(origin, direction, length) {
  43493. if (length === void 0) { length = Number.MAX_VALUE; }
  43494. this.origin = origin;
  43495. this.direction = direction;
  43496. this.length = length;
  43497. }
  43498. // Methods
  43499. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  43500. var d = 0.0;
  43501. var maxValue = Number.MAX_VALUE;
  43502. var inv;
  43503. var min;
  43504. var max;
  43505. var temp;
  43506. if (Math.abs(this.direction.x) < 0.0000001) {
  43507. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  43508. return false;
  43509. }
  43510. }
  43511. else {
  43512. inv = 1.0 / this.direction.x;
  43513. min = (minimum.x - this.origin.x) * inv;
  43514. max = (maximum.x - this.origin.x) * inv;
  43515. if (max === -Infinity) {
  43516. max = Infinity;
  43517. }
  43518. if (min > max) {
  43519. temp = min;
  43520. min = max;
  43521. max = temp;
  43522. }
  43523. d = Math.max(min, d);
  43524. maxValue = Math.min(max, maxValue);
  43525. if (d > maxValue) {
  43526. return false;
  43527. }
  43528. }
  43529. if (Math.abs(this.direction.y) < 0.0000001) {
  43530. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  43531. return false;
  43532. }
  43533. }
  43534. else {
  43535. inv = 1.0 / this.direction.y;
  43536. min = (minimum.y - this.origin.y) * inv;
  43537. max = (maximum.y - this.origin.y) * inv;
  43538. if (max === -Infinity) {
  43539. max = Infinity;
  43540. }
  43541. if (min > max) {
  43542. temp = min;
  43543. min = max;
  43544. max = temp;
  43545. }
  43546. d = Math.max(min, d);
  43547. maxValue = Math.min(max, maxValue);
  43548. if (d > maxValue) {
  43549. return false;
  43550. }
  43551. }
  43552. if (Math.abs(this.direction.z) < 0.0000001) {
  43553. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  43554. return false;
  43555. }
  43556. }
  43557. else {
  43558. inv = 1.0 / this.direction.z;
  43559. min = (minimum.z - this.origin.z) * inv;
  43560. max = (maximum.z - this.origin.z) * inv;
  43561. if (max === -Infinity) {
  43562. max = Infinity;
  43563. }
  43564. if (min > max) {
  43565. temp = min;
  43566. min = max;
  43567. max = temp;
  43568. }
  43569. d = Math.max(min, d);
  43570. maxValue = Math.min(max, maxValue);
  43571. if (d > maxValue) {
  43572. return false;
  43573. }
  43574. }
  43575. return true;
  43576. };
  43577. Ray.prototype.intersectsBox = function (box) {
  43578. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  43579. };
  43580. Ray.prototype.intersectsSphere = function (sphere) {
  43581. var x = sphere.center.x - this.origin.x;
  43582. var y = sphere.center.y - this.origin.y;
  43583. var z = sphere.center.z - this.origin.z;
  43584. var pyth = (x * x) + (y * y) + (z * z);
  43585. var rr = sphere.radius * sphere.radius;
  43586. if (pyth <= rr) {
  43587. return true;
  43588. }
  43589. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  43590. if (dot < 0.0) {
  43591. return false;
  43592. }
  43593. var temp = pyth - (dot * dot);
  43594. return temp <= rr;
  43595. };
  43596. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  43597. if (!this._edge1) {
  43598. this._edge1 = BABYLON.Vector3.Zero();
  43599. this._edge2 = BABYLON.Vector3.Zero();
  43600. this._pvec = BABYLON.Vector3.Zero();
  43601. this._tvec = BABYLON.Vector3.Zero();
  43602. this._qvec = BABYLON.Vector3.Zero();
  43603. }
  43604. vertex1.subtractToRef(vertex0, this._edge1);
  43605. vertex2.subtractToRef(vertex0, this._edge2);
  43606. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  43607. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  43608. if (det === 0) {
  43609. return null;
  43610. }
  43611. var invdet = 1 / det;
  43612. this.origin.subtractToRef(vertex0, this._tvec);
  43613. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  43614. if (bu < 0 || bu > 1.0) {
  43615. return null;
  43616. }
  43617. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  43618. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  43619. if (bv < 0 || bu + bv > 1.0) {
  43620. return null;
  43621. }
  43622. //check if the distance is longer than the predefined length.
  43623. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  43624. if (distance > this.length) {
  43625. return null;
  43626. }
  43627. return new BABYLON.IntersectionInfo(bu, bv, distance);
  43628. };
  43629. Ray.prototype.intersectsPlane = function (plane) {
  43630. var distance;
  43631. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  43632. if (Math.abs(result1) < 9.99999997475243E-07) {
  43633. return null;
  43634. }
  43635. else {
  43636. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  43637. distance = (-plane.d - result2) / result1;
  43638. if (distance < 0.0) {
  43639. if (distance < -9.99999997475243E-07) {
  43640. return null;
  43641. }
  43642. else {
  43643. return 0;
  43644. }
  43645. }
  43646. return distance;
  43647. }
  43648. };
  43649. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  43650. var tm = BABYLON.Tmp.Matrix[0];
  43651. mesh.getWorldMatrix().invertToRef(tm);
  43652. if (this._tmpRay) {
  43653. Ray.TransformToRef(this, tm, this._tmpRay);
  43654. }
  43655. else {
  43656. this._tmpRay = Ray.Transform(this, tm);
  43657. }
  43658. return mesh.intersects(this._tmpRay, fastCheck);
  43659. };
  43660. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  43661. if (results) {
  43662. results.length = 0;
  43663. }
  43664. else {
  43665. results = [];
  43666. }
  43667. for (var i = 0; i < meshes.length; i++) {
  43668. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  43669. if (pickInfo.hit) {
  43670. results.push(pickInfo);
  43671. }
  43672. }
  43673. results.sort(this._comparePickingInfo);
  43674. return results;
  43675. };
  43676. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43677. if (pickingInfoA.distance < pickingInfoB.distance) {
  43678. return -1;
  43679. }
  43680. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43681. return 1;
  43682. }
  43683. else {
  43684. return 0;
  43685. }
  43686. };
  43687. /**
  43688. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43689. * @param sega the first point of the segment to test the intersection against
  43690. * @param segb the second point of the segment to test the intersection against
  43691. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43692. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43693. */
  43694. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43695. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43696. var u = segb.subtract(sega);
  43697. var v = rsegb.subtract(this.origin);
  43698. var w = sega.subtract(this.origin);
  43699. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43700. var b = BABYLON.Vector3.Dot(u, v);
  43701. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43702. var d = BABYLON.Vector3.Dot(u, w);
  43703. var e = BABYLON.Vector3.Dot(v, w);
  43704. var D = a * c - b * b; // always >= 0
  43705. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43706. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43707. // compute the line parameters of the two closest points
  43708. if (D < Ray.smallnum) {
  43709. sN = 0.0; // force using point P0 on segment S1
  43710. sD = 1.0; // to prevent possible division by 0.0 later
  43711. tN = e;
  43712. tD = c;
  43713. }
  43714. else {
  43715. sN = (b * e - c * d);
  43716. tN = (a * e - b * d);
  43717. if (sN < 0.0) {
  43718. sN = 0.0;
  43719. tN = e;
  43720. tD = c;
  43721. }
  43722. else if (sN > sD) {
  43723. sN = sD;
  43724. tN = e + b;
  43725. tD = c;
  43726. }
  43727. }
  43728. if (tN < 0.0) {
  43729. tN = 0.0;
  43730. // recompute sc for this edge
  43731. if (-d < 0.0) {
  43732. sN = 0.0;
  43733. }
  43734. else if (-d > a)
  43735. sN = sD;
  43736. else {
  43737. sN = -d;
  43738. sD = a;
  43739. }
  43740. }
  43741. else if (tN > tD) {
  43742. tN = tD;
  43743. // recompute sc for this edge
  43744. if ((-d + b) < 0.0) {
  43745. sN = 0;
  43746. }
  43747. else if ((-d + b) > a) {
  43748. sN = sD;
  43749. }
  43750. else {
  43751. sN = (-d + b);
  43752. sD = a;
  43753. }
  43754. }
  43755. // finally do the division to get sc and tc
  43756. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  43757. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  43758. // get the difference of the two closest points
  43759. var qtc = v.multiplyByFloats(tc, tc, tc);
  43760. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  43761. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  43762. if (isIntersected) {
  43763. return qtc.length();
  43764. }
  43765. return -1;
  43766. };
  43767. // Statics
  43768. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43769. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  43770. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  43771. var direction = end.subtract(start);
  43772. direction.normalize();
  43773. return new Ray(start, direction);
  43774. };
  43775. /**
  43776. * 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
  43777. * transformed to the given world matrix.
  43778. * @param origin The origin point
  43779. * @param end The end point
  43780. * @param world a matrix to transform the ray to. Default is the identity matrix.
  43781. */
  43782. Ray.CreateNewFromTo = function (origin, end, world) {
  43783. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  43784. var direction = end.subtract(origin);
  43785. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  43786. direction.normalize();
  43787. return Ray.Transform(new Ray(origin, direction, length), world);
  43788. };
  43789. Ray.Transform = function (ray, matrix) {
  43790. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  43791. Ray.TransformToRef(ray, matrix, result);
  43792. return result;
  43793. };
  43794. Ray.TransformToRef = function (ray, matrix, result) {
  43795. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  43796. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  43797. result.length = ray.length;
  43798. var dir = result.direction;
  43799. var len = dir.length();
  43800. if (!(len === 0 || len === 1)) {
  43801. var num = 1.0 / len;
  43802. dir.x *= num;
  43803. dir.y *= num;
  43804. dir.z *= num;
  43805. result.length *= len;
  43806. }
  43807. };
  43808. Ray.smallnum = 0.00000001;
  43809. Ray.rayl = 10e8;
  43810. return Ray;
  43811. }());
  43812. BABYLON.Ray = Ray;
  43813. })(BABYLON || (BABYLON = {}));
  43814. //# sourceMappingURL=babylon.ray.js.map
  43815. var BABYLON;
  43816. (function (BABYLON) {
  43817. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  43818. if (boxMin.x > sphereCenter.x + sphereRadius)
  43819. return false;
  43820. if (sphereCenter.x - sphereRadius > boxMax.x)
  43821. return false;
  43822. if (boxMin.y > sphereCenter.y + sphereRadius)
  43823. return false;
  43824. if (sphereCenter.y - sphereRadius > boxMax.y)
  43825. return false;
  43826. if (boxMin.z > sphereCenter.z + sphereRadius)
  43827. return false;
  43828. if (sphereCenter.z - sphereRadius > boxMax.z)
  43829. return false;
  43830. return true;
  43831. };
  43832. var getLowestRoot = (function () {
  43833. var result = { root: 0, found: false };
  43834. return function (a, b, c, maxR) {
  43835. result.root = 0;
  43836. result.found = false;
  43837. var determinant = b * b - 4.0 * a * c;
  43838. if (determinant < 0)
  43839. return result;
  43840. var sqrtD = Math.sqrt(determinant);
  43841. var r1 = (-b - sqrtD) / (2.0 * a);
  43842. var r2 = (-b + sqrtD) / (2.0 * a);
  43843. if (r1 > r2) {
  43844. var temp = r2;
  43845. r2 = r1;
  43846. r1 = temp;
  43847. }
  43848. if (r1 > 0 && r1 < maxR) {
  43849. result.root = r1;
  43850. result.found = true;
  43851. return result;
  43852. }
  43853. if (r2 > 0 && r2 < maxR) {
  43854. result.root = r2;
  43855. result.found = true;
  43856. return result;
  43857. }
  43858. return result;
  43859. };
  43860. })();
  43861. var Collider = /** @class */ (function () {
  43862. function Collider() {
  43863. this.radius = BABYLON.Vector3.One();
  43864. this.retry = 0;
  43865. this.basePointWorld = BABYLON.Vector3.Zero();
  43866. this.velocityWorld = BABYLON.Vector3.Zero();
  43867. this.normalizedVelocity = BABYLON.Vector3.Zero();
  43868. this._collisionPoint = BABYLON.Vector3.Zero();
  43869. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  43870. this._tempVector = BABYLON.Vector3.Zero();
  43871. this._tempVector2 = BABYLON.Vector3.Zero();
  43872. this._tempVector3 = BABYLON.Vector3.Zero();
  43873. this._tempVector4 = BABYLON.Vector3.Zero();
  43874. this._edge = BABYLON.Vector3.Zero();
  43875. this._baseToVertex = BABYLON.Vector3.Zero();
  43876. this._destinationPoint = BABYLON.Vector3.Zero();
  43877. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  43878. this._displacementVector = BABYLON.Vector3.Zero();
  43879. this._collisionMask = -1;
  43880. }
  43881. Object.defineProperty(Collider.prototype, "collisionMask", {
  43882. get: function () {
  43883. return this._collisionMask;
  43884. },
  43885. set: function (mask) {
  43886. this._collisionMask = !isNaN(mask) ? mask : -1;
  43887. },
  43888. enumerable: true,
  43889. configurable: true
  43890. });
  43891. // Methods
  43892. Collider.prototype._initialize = function (source, dir, e) {
  43893. this.velocity = dir;
  43894. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  43895. this.basePoint = source;
  43896. source.multiplyToRef(this.radius, this.basePointWorld);
  43897. dir.multiplyToRef(this.radius, this.velocityWorld);
  43898. this.velocityWorldLength = this.velocityWorld.length();
  43899. this.epsilon = e;
  43900. this.collisionFound = false;
  43901. };
  43902. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  43903. pa.subtractToRef(point, this._tempVector);
  43904. pb.subtractToRef(point, this._tempVector2);
  43905. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  43906. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43907. if (d < 0)
  43908. return false;
  43909. pc.subtractToRef(point, this._tempVector3);
  43910. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  43911. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43912. if (d < 0)
  43913. return false;
  43914. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  43915. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43916. return d >= 0;
  43917. };
  43918. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  43919. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  43920. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  43921. if (distance > this.velocityWorldLength + max + sphereRadius) {
  43922. return false;
  43923. }
  43924. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  43925. return false;
  43926. return true;
  43927. };
  43928. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  43929. var t0;
  43930. var embeddedInPlane = false;
  43931. //defensive programming, actually not needed.
  43932. if (!trianglePlaneArray) {
  43933. trianglePlaneArray = [];
  43934. }
  43935. if (!trianglePlaneArray[faceIndex]) {
  43936. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  43937. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  43938. }
  43939. var trianglePlane = trianglePlaneArray[faceIndex];
  43940. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  43941. return;
  43942. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  43943. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  43944. if (normalDotVelocity == 0) {
  43945. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  43946. return;
  43947. embeddedInPlane = true;
  43948. t0 = 0;
  43949. }
  43950. else {
  43951. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43952. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43953. if (t0 > t1) {
  43954. var temp = t1;
  43955. t1 = t0;
  43956. t0 = temp;
  43957. }
  43958. if (t0 > 1.0 || t1 < 0.0)
  43959. return;
  43960. if (t0 < 0)
  43961. t0 = 0;
  43962. if (t0 > 1.0)
  43963. t0 = 1.0;
  43964. }
  43965. this._collisionPoint.copyFromFloats(0, 0, 0);
  43966. var found = false;
  43967. var t = 1.0;
  43968. if (!embeddedInPlane) {
  43969. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  43970. this.velocity.scaleToRef(t0, this._tempVector);
  43971. this._planeIntersectionPoint.addInPlace(this._tempVector);
  43972. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  43973. found = true;
  43974. t = t0;
  43975. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  43976. }
  43977. }
  43978. if (!found) {
  43979. var velocitySquaredLength = this.velocity.lengthSquared();
  43980. var a = velocitySquaredLength;
  43981. this.basePoint.subtractToRef(p1, this._tempVector);
  43982. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43983. var c = this._tempVector.lengthSquared() - 1.0;
  43984. var lowestRoot = getLowestRoot(a, b, c, t);
  43985. if (lowestRoot.found) {
  43986. t = lowestRoot.root;
  43987. found = true;
  43988. this._collisionPoint.copyFrom(p1);
  43989. }
  43990. this.basePoint.subtractToRef(p2, this._tempVector);
  43991. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43992. c = this._tempVector.lengthSquared() - 1.0;
  43993. lowestRoot = getLowestRoot(a, b, c, t);
  43994. if (lowestRoot.found) {
  43995. t = lowestRoot.root;
  43996. found = true;
  43997. this._collisionPoint.copyFrom(p2);
  43998. }
  43999. this.basePoint.subtractToRef(p3, this._tempVector);
  44000. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  44001. c = this._tempVector.lengthSquared() - 1.0;
  44002. lowestRoot = getLowestRoot(a, b, c, t);
  44003. if (lowestRoot.found) {
  44004. t = lowestRoot.root;
  44005. found = true;
  44006. this._collisionPoint.copyFrom(p3);
  44007. }
  44008. p2.subtractToRef(p1, this._edge);
  44009. p1.subtractToRef(this.basePoint, this._baseToVertex);
  44010. var edgeSquaredLength = this._edge.lengthSquared();
  44011. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44012. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44013. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44014. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44015. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44016. lowestRoot = getLowestRoot(a, b, c, t);
  44017. if (lowestRoot.found) {
  44018. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44019. if (f >= 0.0 && f <= 1.0) {
  44020. t = lowestRoot.root;
  44021. found = true;
  44022. this._edge.scaleInPlace(f);
  44023. p1.addToRef(this._edge, this._collisionPoint);
  44024. }
  44025. }
  44026. p3.subtractToRef(p2, this._edge);
  44027. p2.subtractToRef(this.basePoint, this._baseToVertex);
  44028. edgeSquaredLength = this._edge.lengthSquared();
  44029. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44030. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44031. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44032. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44033. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44034. lowestRoot = getLowestRoot(a, b, c, t);
  44035. if (lowestRoot.found) {
  44036. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44037. if (f >= 0.0 && f <= 1.0) {
  44038. t = lowestRoot.root;
  44039. found = true;
  44040. this._edge.scaleInPlace(f);
  44041. p2.addToRef(this._edge, this._collisionPoint);
  44042. }
  44043. }
  44044. p1.subtractToRef(p3, this._edge);
  44045. p3.subtractToRef(this.basePoint, this._baseToVertex);
  44046. edgeSquaredLength = this._edge.lengthSquared();
  44047. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  44048. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  44049. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  44050. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  44051. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  44052. lowestRoot = getLowestRoot(a, b, c, t);
  44053. if (lowestRoot.found) {
  44054. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  44055. if (f >= 0.0 && f <= 1.0) {
  44056. t = lowestRoot.root;
  44057. found = true;
  44058. this._edge.scaleInPlace(f);
  44059. p3.addToRef(this._edge, this._collisionPoint);
  44060. }
  44061. }
  44062. }
  44063. if (found) {
  44064. var distToCollision = t * this.velocity.length();
  44065. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  44066. if (!this.intersectionPoint) {
  44067. this.intersectionPoint = this._collisionPoint.clone();
  44068. }
  44069. else {
  44070. this.intersectionPoint.copyFrom(this._collisionPoint);
  44071. }
  44072. this.nearestDistance = distToCollision;
  44073. this.collisionFound = true;
  44074. }
  44075. }
  44076. };
  44077. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  44078. for (var i = indexStart; i < indexEnd; i += 3) {
  44079. var p1 = pts[indices[i] - decal];
  44080. var p2 = pts[indices[i + 1] - decal];
  44081. var p3 = pts[indices[i + 2] - decal];
  44082. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  44083. }
  44084. };
  44085. Collider.prototype._getResponse = function (pos, vel) {
  44086. pos.addToRef(vel, this._destinationPoint);
  44087. vel.scaleInPlace((this.nearestDistance / vel.length()));
  44088. this.basePoint.addToRef(vel, pos);
  44089. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  44090. this._slidePlaneNormal.normalize();
  44091. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  44092. pos.addInPlace(this._displacementVector);
  44093. this.intersectionPoint.addInPlace(this._displacementVector);
  44094. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  44095. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  44096. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  44097. };
  44098. return Collider;
  44099. }());
  44100. BABYLON.Collider = Collider;
  44101. })(BABYLON || (BABYLON = {}));
  44102. //# sourceMappingURL=babylon.collider.js.map
  44103. var BABYLON;
  44104. (function (BABYLON) {
  44105. //WebWorker code will be inserted to this variable.
  44106. BABYLON.CollisionWorker = "";
  44107. var WorkerTaskType;
  44108. (function (WorkerTaskType) {
  44109. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  44110. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  44111. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  44112. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  44113. var WorkerReplyType;
  44114. (function (WorkerReplyType) {
  44115. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  44116. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  44117. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  44118. var CollisionCoordinatorWorker = /** @class */ (function () {
  44119. function CollisionCoordinatorWorker() {
  44120. var _this = this;
  44121. this._scaledPosition = BABYLON.Vector3.Zero();
  44122. this._scaledVelocity = BABYLON.Vector3.Zero();
  44123. this.onMeshUpdated = function (mesh) {
  44124. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  44125. };
  44126. this.onGeometryUpdated = function (geometry) {
  44127. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  44128. };
  44129. this._afterRender = function () {
  44130. if (!_this._init)
  44131. return;
  44132. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  44133. return;
  44134. }
  44135. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  44136. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  44137. if (_this._runningUpdated > 4) {
  44138. return;
  44139. }
  44140. ++_this._runningUpdated;
  44141. var payload = {
  44142. updatedMeshes: _this._addUpdateMeshesList,
  44143. updatedGeometries: _this._addUpdateGeometriesList,
  44144. removedGeometries: _this._toRemoveGeometryArray,
  44145. removedMeshes: _this._toRemoveMeshesArray
  44146. };
  44147. var message = {
  44148. payload: payload,
  44149. taskType: WorkerTaskType.UPDATE
  44150. };
  44151. var serializable = [];
  44152. for (var id in payload.updatedGeometries) {
  44153. if (payload.updatedGeometries.hasOwnProperty(id)) {
  44154. //prepare transferables
  44155. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  44156. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  44157. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  44158. }
  44159. }
  44160. _this._worker.postMessage(message, serializable);
  44161. _this._addUpdateMeshesList = {};
  44162. _this._addUpdateGeometriesList = {};
  44163. _this._toRemoveGeometryArray = [];
  44164. _this._toRemoveMeshesArray = [];
  44165. };
  44166. this._onMessageFromWorker = function (e) {
  44167. var returnData = e.data;
  44168. if (returnData.error != WorkerReplyType.SUCCESS) {
  44169. //TODO what errors can be returned from the worker?
  44170. BABYLON.Tools.Warn("error returned from worker!");
  44171. return;
  44172. }
  44173. switch (returnData.taskType) {
  44174. case WorkerTaskType.INIT:
  44175. _this._init = true;
  44176. //Update the worked with ALL of the scene's current state
  44177. _this._scene.meshes.forEach(function (mesh) {
  44178. _this.onMeshAdded(mesh);
  44179. });
  44180. _this._scene.getGeometries().forEach(function (geometry) {
  44181. _this.onGeometryAdded(geometry);
  44182. });
  44183. break;
  44184. case WorkerTaskType.UPDATE:
  44185. _this._runningUpdated--;
  44186. break;
  44187. case WorkerTaskType.COLLIDE:
  44188. _this._runningCollisionTask = false;
  44189. var returnPayload = returnData.payload;
  44190. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  44191. return;
  44192. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  44193. if (callback) {
  44194. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  44195. if (mesh) {
  44196. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  44197. }
  44198. }
  44199. //cleanup
  44200. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  44201. break;
  44202. }
  44203. };
  44204. this._collisionsCallbackArray = [];
  44205. this._init = false;
  44206. this._runningUpdated = 0;
  44207. this._runningCollisionTask = false;
  44208. this._addUpdateMeshesList = {};
  44209. this._addUpdateGeometriesList = {};
  44210. this._toRemoveGeometryArray = [];
  44211. this._toRemoveMeshesArray = [];
  44212. }
  44213. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44214. if (!this._init)
  44215. return;
  44216. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  44217. return;
  44218. position.divideToRef(collider.radius, this._scaledPosition);
  44219. displacement.divideToRef(collider.radius, this._scaledVelocity);
  44220. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  44221. var payload = {
  44222. collider: {
  44223. position: this._scaledPosition.asArray(),
  44224. velocity: this._scaledVelocity.asArray(),
  44225. radius: collider.radius.asArray()
  44226. },
  44227. collisionId: collisionIndex,
  44228. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  44229. maximumRetry: maximumRetry
  44230. };
  44231. var message = {
  44232. payload: payload,
  44233. taskType: WorkerTaskType.COLLIDE
  44234. };
  44235. this._worker.postMessage(message);
  44236. };
  44237. CollisionCoordinatorWorker.prototype.init = function (scene) {
  44238. this._scene = scene;
  44239. this._scene.registerAfterRender(this._afterRender);
  44240. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  44241. this._worker = new Worker(workerUrl);
  44242. this._worker.onmessage = this._onMessageFromWorker;
  44243. var message = {
  44244. payload: {},
  44245. taskType: WorkerTaskType.INIT
  44246. };
  44247. this._worker.postMessage(message);
  44248. };
  44249. CollisionCoordinatorWorker.prototype.destroy = function () {
  44250. this._scene.unregisterAfterRender(this._afterRender);
  44251. this._worker.terminate();
  44252. };
  44253. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  44254. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  44255. this.onMeshUpdated(mesh);
  44256. };
  44257. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  44258. this._toRemoveMeshesArray.push(mesh.uniqueId);
  44259. };
  44260. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  44261. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  44262. geometry.onGeometryUpdated = this.onGeometryUpdated;
  44263. this.onGeometryUpdated(geometry);
  44264. };
  44265. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  44266. this._toRemoveGeometryArray.push(geometry.id);
  44267. };
  44268. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  44269. var submeshes = [];
  44270. if (mesh.subMeshes) {
  44271. submeshes = mesh.subMeshes.map(function (sm, idx) {
  44272. var boundingInfo = sm.getBoundingInfo();
  44273. return {
  44274. position: idx,
  44275. verticesStart: sm.verticesStart,
  44276. verticesCount: sm.verticesCount,
  44277. indexStart: sm.indexStart,
  44278. indexCount: sm.indexCount,
  44279. hasMaterial: !!sm.getMaterial(),
  44280. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44281. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44282. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44283. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  44284. };
  44285. });
  44286. }
  44287. var geometryId = null;
  44288. if (mesh instanceof BABYLON.Mesh) {
  44289. var geometry = mesh.geometry;
  44290. geometryId = geometry ? geometry.id : null;
  44291. }
  44292. else if (mesh instanceof BABYLON.InstancedMesh) {
  44293. var geometry = mesh.sourceMesh.geometry;
  44294. geometryId = geometry ? geometry.id : null;
  44295. }
  44296. var boundingInfo = mesh.getBoundingInfo();
  44297. return {
  44298. uniqueId: mesh.uniqueId,
  44299. id: mesh.id,
  44300. name: mesh.name,
  44301. geometryId: geometryId,
  44302. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  44303. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  44304. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  44305. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  44306. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  44307. subMeshes: submeshes,
  44308. checkCollisions: mesh.checkCollisions
  44309. };
  44310. };
  44311. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  44312. return {
  44313. id: geometry.id,
  44314. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  44315. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  44316. indices: new Uint32Array(geometry.getIndices() || []),
  44317. };
  44318. };
  44319. return CollisionCoordinatorWorker;
  44320. }());
  44321. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  44322. var CollisionCoordinatorLegacy = /** @class */ (function () {
  44323. function CollisionCoordinatorLegacy() {
  44324. this._scaledPosition = BABYLON.Vector3.Zero();
  44325. this._scaledVelocity = BABYLON.Vector3.Zero();
  44326. this._finalPosition = BABYLON.Vector3.Zero();
  44327. }
  44328. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  44329. position.divideToRef(collider.radius, this._scaledPosition);
  44330. displacement.divideToRef(collider.radius, this._scaledVelocity);
  44331. collider.collidedMesh = null;
  44332. collider.retry = 0;
  44333. collider.initialVelocity = this._scaledVelocity;
  44334. collider.initialPosition = this._scaledPosition;
  44335. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  44336. this._finalPosition.multiplyInPlace(collider.radius);
  44337. //run the callback
  44338. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  44339. };
  44340. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  44341. this._scene = scene;
  44342. };
  44343. CollisionCoordinatorLegacy.prototype.destroy = function () {
  44344. //Legacy need no destruction method.
  44345. };
  44346. //No update in legacy mode
  44347. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  44348. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  44349. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  44350. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  44351. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  44352. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  44353. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  44354. if (excludedMesh === void 0) { excludedMesh = null; }
  44355. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  44356. if (collider.retry >= maximumRetry) {
  44357. finalPosition.copyFrom(position);
  44358. return;
  44359. }
  44360. // Check if this is a mesh else camera or -1
  44361. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  44362. collider._initialize(position, velocity, closeDistance);
  44363. // Check all meshes
  44364. for (var index = 0; index < this._scene.meshes.length; index++) {
  44365. var mesh = this._scene.meshes[index];
  44366. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  44367. mesh._checkCollision(collider);
  44368. }
  44369. }
  44370. if (!collider.collisionFound) {
  44371. position.addToRef(velocity, finalPosition);
  44372. return;
  44373. }
  44374. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  44375. collider._getResponse(position, velocity);
  44376. }
  44377. if (velocity.length() <= closeDistance) {
  44378. finalPosition.copyFrom(position);
  44379. return;
  44380. }
  44381. collider.retry++;
  44382. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  44383. };
  44384. return CollisionCoordinatorLegacy;
  44385. }());
  44386. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  44387. })(BABYLON || (BABYLON = {}));
  44388. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  44389. var BABYLON;
  44390. (function (BABYLON) {
  44391. var Particle = /** @class */ (function () {
  44392. function Particle(particleSystem) {
  44393. this.particleSystem = particleSystem;
  44394. this.position = BABYLON.Vector3.Zero();
  44395. this.direction = BABYLON.Vector3.Zero();
  44396. this.color = new BABYLON.Color4(0, 0, 0, 0);
  44397. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  44398. this.lifeTime = 1.0;
  44399. this.age = 0;
  44400. this.size = 0;
  44401. this.angle = 0;
  44402. this.angularSpeed = 0;
  44403. this._currentFrameCounter = 0;
  44404. this.cellIndex = 0;
  44405. if (!this.particleSystem.isAnimationSheetEnabled) {
  44406. return;
  44407. }
  44408. this.cellIndex = this.particleSystem.startSpriteCellID;
  44409. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  44410. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  44411. }
  44412. else {
  44413. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  44414. }
  44415. }
  44416. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  44417. // (ageOffset / scaledUpdateSpeed) / available cells
  44418. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  44419. this._currentFrameCounter += scaledUpdateSpeed;
  44420. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  44421. this._currentFrameCounter = 0;
  44422. this.cellIndex++;
  44423. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  44424. this.cellIndex = this.particleSystem.endSpriteCellID;
  44425. }
  44426. }
  44427. };
  44428. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  44429. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  44430. this.cellIndex++;
  44431. this._currentFrameCounter = 0;
  44432. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  44433. if (this.particleSystem.spriteCellLoop) {
  44434. this.cellIndex = this.particleSystem.startSpriteCellID;
  44435. }
  44436. else {
  44437. this.cellIndex = this.particleSystem.endSpriteCellID;
  44438. }
  44439. }
  44440. }
  44441. else {
  44442. this._currentFrameCounter++;
  44443. }
  44444. };
  44445. Particle.prototype.copyTo = function (other) {
  44446. other.position.copyFrom(this.position);
  44447. other.direction.copyFrom(this.direction);
  44448. other.color.copyFrom(this.color);
  44449. other.colorStep.copyFrom(this.colorStep);
  44450. other.lifeTime = this.lifeTime;
  44451. other.age = this.age;
  44452. other.size = this.size;
  44453. other.angle = this.angle;
  44454. other.angularSpeed = this.angularSpeed;
  44455. other.particleSystem = this.particleSystem;
  44456. other.cellIndex = this.cellIndex;
  44457. };
  44458. return Particle;
  44459. }());
  44460. BABYLON.Particle = Particle;
  44461. })(BABYLON || (BABYLON = {}));
  44462. //# sourceMappingURL=babylon.particle.js.map
  44463. var BABYLON;
  44464. (function (BABYLON) {
  44465. var randomNumber = function (min, max) {
  44466. if (min === max) {
  44467. return (min);
  44468. }
  44469. var random = Math.random();
  44470. return ((random * (max - min)) + min);
  44471. };
  44472. var ParticleSystem = /** @class */ (function () {
  44473. // end of sheet animation
  44474. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  44475. if (customEffect === void 0) { customEffect = null; }
  44476. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  44477. if (epsilon === void 0) { epsilon = 0.01; }
  44478. var _this = this;
  44479. this.name = name;
  44480. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  44481. // Members
  44482. this.animations = [];
  44483. this.renderingGroupId = 0;
  44484. this.emitter = null;
  44485. this.emitRate = 10;
  44486. this.manualEmitCount = -1;
  44487. this.updateSpeed = 0.01;
  44488. this.targetStopDuration = 0;
  44489. this.disposeOnStop = false;
  44490. this.minEmitPower = 1;
  44491. this.maxEmitPower = 1;
  44492. this.minLifeTime = 1;
  44493. this.maxLifeTime = 1;
  44494. this.minSize = 1;
  44495. this.maxSize = 1;
  44496. this.minAngularSpeed = 0;
  44497. this.maxAngularSpeed = 0;
  44498. this.layerMask = 0x0FFFFFFF;
  44499. this.customShader = null;
  44500. this.preventAutoStart = false;
  44501. /**
  44502. * An event triggered when the system is disposed.
  44503. * @type {BABYLON.Observable}
  44504. */
  44505. this.onDisposeObservable = new BABYLON.Observable();
  44506. this.onAnimationEnd = null;
  44507. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  44508. this.forceDepthWrite = false;
  44509. this.gravity = BABYLON.Vector3.Zero();
  44510. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  44511. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  44512. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  44513. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44514. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44515. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44516. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  44517. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44518. this.particles = new Array();
  44519. this._stockParticles = new Array();
  44520. this._newPartsExcess = 0;
  44521. this._vertexBuffers = {};
  44522. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  44523. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  44524. this._scaledDirection = BABYLON.Vector3.Zero();
  44525. this._scaledGravity = BABYLON.Vector3.Zero();
  44526. this._currentRenderId = -1;
  44527. this._started = false;
  44528. this._stopped = false;
  44529. this._actualFrame = 0;
  44530. // sheet animation
  44531. this.startSpriteCellID = 0;
  44532. this.endSpriteCellID = 0;
  44533. this.spriteCellLoop = true;
  44534. this.spriteCellChangeSpeed = 0;
  44535. this.spriteCellWidth = 0;
  44536. this.spriteCellHeight = 0;
  44537. this._vertexBufferSize = 11;
  44538. this.appendParticleVertexes = null;
  44539. this.id = name;
  44540. this._capacity = capacity;
  44541. this._epsilon = epsilon;
  44542. if (_isAnimationSheetEnabled) {
  44543. this._vertexBufferSize = 12;
  44544. }
  44545. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44546. this._customEffect = customEffect;
  44547. scene.particleSystems.push(this);
  44548. this._createIndexBuffer();
  44549. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  44550. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  44551. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  44552. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  44553. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  44554. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  44555. if (this._isAnimationSheetEnabled) {
  44556. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  44557. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  44558. }
  44559. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44560. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44561. this._vertexBuffers["options"] = options;
  44562. // Default behaviors
  44563. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  44564. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  44565. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  44566. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  44567. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  44568. };
  44569. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  44570. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  44571. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  44572. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  44573. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  44574. };
  44575. this.updateFunction = function (particles) {
  44576. for (var index = 0; index < particles.length; index++) {
  44577. var particle = particles[index];
  44578. particle.age += _this._scaledUpdateSpeed;
  44579. if (particle.age >= particle.lifeTime) {
  44580. _this.recycleParticle(particle);
  44581. index--;
  44582. continue;
  44583. }
  44584. else {
  44585. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  44586. particle.color.addInPlace(_this._scaledColorStep);
  44587. if (particle.color.a < 0)
  44588. particle.color.a = 0;
  44589. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  44590. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  44591. particle.position.addInPlace(_this._scaledDirection);
  44592. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  44593. particle.direction.addInPlace(_this._scaledGravity);
  44594. if (_this._isAnimationSheetEnabled) {
  44595. particle.updateCellIndex(_this._scaledUpdateSpeed);
  44596. }
  44597. }
  44598. }
  44599. };
  44600. }
  44601. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  44602. set: function (callback) {
  44603. if (this._onDisposeObserver) {
  44604. this.onDisposeObservable.remove(this._onDisposeObserver);
  44605. }
  44606. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44607. },
  44608. enumerable: true,
  44609. configurable: true
  44610. });
  44611. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  44612. get: function () {
  44613. return this._isAnimationSheetEnabled;
  44614. },
  44615. enumerable: true,
  44616. configurable: true
  44617. });
  44618. ParticleSystem.prototype._createIndexBuffer = function () {
  44619. var indices = [];
  44620. var index = 0;
  44621. for (var count = 0; count < this._capacity; count++) {
  44622. indices.push(index);
  44623. indices.push(index + 1);
  44624. indices.push(index + 2);
  44625. indices.push(index);
  44626. indices.push(index + 2);
  44627. indices.push(index + 3);
  44628. index += 4;
  44629. }
  44630. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  44631. };
  44632. ParticleSystem.prototype.recycleParticle = function (particle) {
  44633. var lastParticle = this.particles.pop();
  44634. if (lastParticle !== particle) {
  44635. lastParticle.copyTo(particle);
  44636. this._stockParticles.push(lastParticle);
  44637. }
  44638. };
  44639. ParticleSystem.prototype.getCapacity = function () {
  44640. return this._capacity;
  44641. };
  44642. ParticleSystem.prototype.isAlive = function () {
  44643. return this._alive;
  44644. };
  44645. ParticleSystem.prototype.isStarted = function () {
  44646. return this._started;
  44647. };
  44648. ParticleSystem.prototype.start = function () {
  44649. this._started = true;
  44650. this._stopped = false;
  44651. this._actualFrame = 0;
  44652. };
  44653. ParticleSystem.prototype.stop = function () {
  44654. this._stopped = true;
  44655. };
  44656. // animation sheet
  44657. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  44658. var offset = index * this._vertexBufferSize;
  44659. this._vertexData[offset] = particle.position.x;
  44660. this._vertexData[offset + 1] = particle.position.y;
  44661. this._vertexData[offset + 2] = particle.position.z;
  44662. this._vertexData[offset + 3] = particle.color.r;
  44663. this._vertexData[offset + 4] = particle.color.g;
  44664. this._vertexData[offset + 5] = particle.color.b;
  44665. this._vertexData[offset + 6] = particle.color.a;
  44666. this._vertexData[offset + 7] = particle.angle;
  44667. this._vertexData[offset + 8] = particle.size;
  44668. this._vertexData[offset + 9] = offsetX;
  44669. this._vertexData[offset + 10] = offsetY;
  44670. };
  44671. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  44672. if (offsetX === 0)
  44673. offsetX = this._epsilon;
  44674. else if (offsetX === 1)
  44675. offsetX = 1 - this._epsilon;
  44676. if (offsetY === 0)
  44677. offsetY = this._epsilon;
  44678. else if (offsetY === 1)
  44679. offsetY = 1 - this._epsilon;
  44680. var offset = index * this._vertexBufferSize;
  44681. this._vertexData[offset] = particle.position.x;
  44682. this._vertexData[offset + 1] = particle.position.y;
  44683. this._vertexData[offset + 2] = particle.position.z;
  44684. this._vertexData[offset + 3] = particle.color.r;
  44685. this._vertexData[offset + 4] = particle.color.g;
  44686. this._vertexData[offset + 5] = particle.color.b;
  44687. this._vertexData[offset + 6] = particle.color.a;
  44688. this._vertexData[offset + 7] = particle.angle;
  44689. this._vertexData[offset + 8] = particle.size;
  44690. this._vertexData[offset + 9] = offsetX;
  44691. this._vertexData[offset + 10] = offsetY;
  44692. this._vertexData[offset + 11] = particle.cellIndex;
  44693. };
  44694. ParticleSystem.prototype._update = function (newParticles) {
  44695. // Update current
  44696. this._alive = this.particles.length > 0;
  44697. this.updateFunction(this.particles);
  44698. // Add new ones
  44699. var worldMatrix;
  44700. if (this.emitter.position) {
  44701. var emitterMesh = this.emitter;
  44702. worldMatrix = emitterMesh.getWorldMatrix();
  44703. }
  44704. else {
  44705. var emitterPosition = this.emitter;
  44706. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44707. }
  44708. var particle;
  44709. for (var index = 0; index < newParticles; index++) {
  44710. if (this.particles.length === this._capacity) {
  44711. break;
  44712. }
  44713. if (this._stockParticles.length !== 0) {
  44714. particle = this._stockParticles.pop();
  44715. particle.age = 0;
  44716. particle.cellIndex = this.startSpriteCellID;
  44717. }
  44718. else {
  44719. particle = new BABYLON.Particle(this);
  44720. }
  44721. this.particles.push(particle);
  44722. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44723. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44724. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44725. particle.size = randomNumber(this.minSize, this.maxSize);
  44726. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44727. this.startPositionFunction(worldMatrix, particle.position, particle);
  44728. var step = randomNumber(0, 1.0);
  44729. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44730. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44731. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44732. }
  44733. };
  44734. ParticleSystem.prototype._getEffect = function () {
  44735. if (this._customEffect) {
  44736. return this._customEffect;
  44737. }
  44738. ;
  44739. var defines = [];
  44740. if (this._scene.clipPlane) {
  44741. defines.push("#define CLIPPLANE");
  44742. }
  44743. if (this._isAnimationSheetEnabled) {
  44744. defines.push("#define ANIMATESHEET");
  44745. }
  44746. // Effect
  44747. var join = defines.join("\n");
  44748. if (this._cachedDefines !== join) {
  44749. this._cachedDefines = join;
  44750. var attributesNamesOrOptions;
  44751. var effectCreationOption;
  44752. if (this._isAnimationSheetEnabled) {
  44753. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  44754. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  44755. }
  44756. else {
  44757. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  44758. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  44759. }
  44760. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  44761. }
  44762. return this._effect;
  44763. };
  44764. ParticleSystem.prototype.animate = function () {
  44765. if (!this._started)
  44766. return;
  44767. var effect = this._getEffect();
  44768. // Check
  44769. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  44770. return;
  44771. if (this._currentRenderId === this._scene.getRenderId()) {
  44772. return;
  44773. }
  44774. this._currentRenderId = this._scene.getRenderId();
  44775. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  44776. // determine the number of particles we need to create
  44777. var newParticles;
  44778. if (this.manualEmitCount > -1) {
  44779. newParticles = this.manualEmitCount;
  44780. this._newPartsExcess = 0;
  44781. this.manualEmitCount = 0;
  44782. }
  44783. else {
  44784. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  44785. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  44786. }
  44787. if (this._newPartsExcess > 1.0) {
  44788. newParticles += this._newPartsExcess >> 0;
  44789. this._newPartsExcess -= this._newPartsExcess >> 0;
  44790. }
  44791. this._alive = false;
  44792. if (!this._stopped) {
  44793. this._actualFrame += this._scaledUpdateSpeed;
  44794. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  44795. this.stop();
  44796. }
  44797. else {
  44798. newParticles = 0;
  44799. }
  44800. this._update(newParticles);
  44801. // Stopped?
  44802. if (this._stopped) {
  44803. if (!this._alive) {
  44804. this._started = false;
  44805. if (this.onAnimationEnd) {
  44806. this.onAnimationEnd();
  44807. }
  44808. if (this.disposeOnStop) {
  44809. this._scene._toBeDisposed.push(this);
  44810. }
  44811. }
  44812. }
  44813. // Animation sheet
  44814. if (this._isAnimationSheetEnabled) {
  44815. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  44816. }
  44817. else {
  44818. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  44819. }
  44820. // Update VBO
  44821. var offset = 0;
  44822. for (var index = 0; index < this.particles.length; index++) {
  44823. var particle = this.particles[index];
  44824. this.appendParticleVertexes(offset, particle);
  44825. offset += 4;
  44826. }
  44827. if (this._vertexBuffer) {
  44828. this._vertexBuffer.update(this._vertexData);
  44829. }
  44830. };
  44831. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  44832. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  44833. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  44834. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  44835. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  44836. };
  44837. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  44838. this._appendParticleVertex(offset++, particle, 0, 0);
  44839. this._appendParticleVertex(offset++, particle, 1, 0);
  44840. this._appendParticleVertex(offset++, particle, 1, 1);
  44841. this._appendParticleVertex(offset++, particle, 0, 1);
  44842. };
  44843. ParticleSystem.prototype.rebuild = function () {
  44844. this._createIndexBuffer();
  44845. if (this._vertexBuffer) {
  44846. this._vertexBuffer._rebuild();
  44847. }
  44848. };
  44849. ParticleSystem.prototype.render = function () {
  44850. var effect = this._getEffect();
  44851. // Check
  44852. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  44853. return 0;
  44854. var engine = this._scene.getEngine();
  44855. // Render
  44856. engine.enableEffect(effect);
  44857. engine.setState(false);
  44858. var viewMatrix = this._scene.getViewMatrix();
  44859. effect.setTexture("diffuseSampler", this.particleTexture);
  44860. effect.setMatrix("view", viewMatrix);
  44861. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44862. if (this._isAnimationSheetEnabled) {
  44863. var baseSize = this.particleTexture.getBaseSize();
  44864. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  44865. }
  44866. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  44867. if (this._scene.clipPlane) {
  44868. var clipPlane = this._scene.clipPlane;
  44869. var invView = viewMatrix.clone();
  44870. invView.invert();
  44871. effect.setMatrix("invView", invView);
  44872. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  44873. }
  44874. // VBOs
  44875. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44876. // Draw order
  44877. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  44878. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44879. }
  44880. else {
  44881. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44882. }
  44883. if (this.forceDepthWrite) {
  44884. engine.setDepthWrite(true);
  44885. }
  44886. engine.draw(true, 0, this.particles.length * 6);
  44887. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44888. return this.particles.length;
  44889. };
  44890. ParticleSystem.prototype.dispose = function () {
  44891. if (this._vertexBuffer) {
  44892. this._vertexBuffer.dispose();
  44893. this._vertexBuffer = null;
  44894. }
  44895. if (this._indexBuffer) {
  44896. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44897. this._indexBuffer = null;
  44898. }
  44899. if (this.particleTexture) {
  44900. this.particleTexture.dispose();
  44901. this.particleTexture = null;
  44902. }
  44903. // Remove from scene
  44904. var index = this._scene.particleSystems.indexOf(this);
  44905. if (index > -1) {
  44906. this._scene.particleSystems.splice(index, 1);
  44907. }
  44908. // Callback
  44909. this.onDisposeObservable.notifyObservers(this);
  44910. this.onDisposeObservable.clear();
  44911. };
  44912. // Clone
  44913. ParticleSystem.prototype.clone = function (name, newEmitter) {
  44914. var custom = null;
  44915. var program = null;
  44916. if (this.customShader != null) {
  44917. program = this.customShader;
  44918. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44919. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44920. }
  44921. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  44922. result.customShader = program;
  44923. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  44924. if (newEmitter === undefined) {
  44925. newEmitter = this.emitter;
  44926. }
  44927. result.emitter = newEmitter;
  44928. if (this.particleTexture) {
  44929. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  44930. }
  44931. if (!this.preventAutoStart) {
  44932. result.start();
  44933. }
  44934. return result;
  44935. };
  44936. ParticleSystem.prototype.serialize = function () {
  44937. var serializationObject = {};
  44938. serializationObject.name = this.name;
  44939. serializationObject.id = this.id;
  44940. // Emitter
  44941. if (this.emitter.position) {
  44942. var emitterMesh = this.emitter;
  44943. serializationObject.emitterId = emitterMesh.id;
  44944. }
  44945. else {
  44946. var emitterPosition = this.emitter;
  44947. serializationObject.emitter = emitterPosition.asArray();
  44948. }
  44949. serializationObject.capacity = this.getCapacity();
  44950. if (this.particleTexture) {
  44951. serializationObject.textureName = this.particleTexture.name;
  44952. }
  44953. // Animations
  44954. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  44955. // Particle system
  44956. serializationObject.minAngularSpeed = this.minAngularSpeed;
  44957. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  44958. serializationObject.minSize = this.minSize;
  44959. serializationObject.maxSize = this.maxSize;
  44960. serializationObject.minEmitPower = this.minEmitPower;
  44961. serializationObject.maxEmitPower = this.maxEmitPower;
  44962. serializationObject.minLifeTime = this.minLifeTime;
  44963. serializationObject.maxLifeTime = this.maxLifeTime;
  44964. serializationObject.emitRate = this.emitRate;
  44965. serializationObject.minEmitBox = this.minEmitBox.asArray();
  44966. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  44967. serializationObject.gravity = this.gravity.asArray();
  44968. serializationObject.direction1 = this.direction1.asArray();
  44969. serializationObject.direction2 = this.direction2.asArray();
  44970. serializationObject.color1 = this.color1.asArray();
  44971. serializationObject.color2 = this.color2.asArray();
  44972. serializationObject.colorDead = this.colorDead.asArray();
  44973. serializationObject.updateSpeed = this.updateSpeed;
  44974. serializationObject.targetStopDuration = this.targetStopDuration;
  44975. serializationObject.textureMask = this.textureMask.asArray();
  44976. serializationObject.blendMode = this.blendMode;
  44977. serializationObject.customShader = this.customShader;
  44978. serializationObject.preventAutoStart = this.preventAutoStart;
  44979. return serializationObject;
  44980. };
  44981. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  44982. var name = parsedParticleSystem.name;
  44983. var custom = null;
  44984. var program = null;
  44985. if (parsedParticleSystem.customShader) {
  44986. program = parsedParticleSystem.customShader;
  44987. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44988. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44989. }
  44990. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  44991. particleSystem.customShader = program;
  44992. if (parsedParticleSystem.id) {
  44993. particleSystem.id = parsedParticleSystem.id;
  44994. }
  44995. // Auto start
  44996. if (parsedParticleSystem.preventAutoStart) {
  44997. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  44998. }
  44999. // Texture
  45000. if (parsedParticleSystem.textureName) {
  45001. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  45002. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  45003. }
  45004. // Emitter
  45005. if (parsedParticleSystem.emitterId) {
  45006. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  45007. }
  45008. else {
  45009. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  45010. }
  45011. // Animations
  45012. if (parsedParticleSystem.animations) {
  45013. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  45014. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  45015. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45016. }
  45017. }
  45018. if (parsedParticleSystem.autoAnimate) {
  45019. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  45020. }
  45021. // Particle system
  45022. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  45023. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  45024. particleSystem.minSize = parsedParticleSystem.minSize;
  45025. particleSystem.maxSize = parsedParticleSystem.maxSize;
  45026. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  45027. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  45028. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  45029. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  45030. particleSystem.emitRate = parsedParticleSystem.emitRate;
  45031. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  45032. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  45033. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  45034. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  45035. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  45036. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  45037. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  45038. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  45039. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  45040. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  45041. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  45042. particleSystem.blendMode = parsedParticleSystem.blendMode;
  45043. if (!particleSystem.preventAutoStart) {
  45044. particleSystem.start();
  45045. }
  45046. return particleSystem;
  45047. };
  45048. // Statics
  45049. ParticleSystem.BLENDMODE_ONEONE = 0;
  45050. ParticleSystem.BLENDMODE_STANDARD = 1;
  45051. return ParticleSystem;
  45052. }());
  45053. BABYLON.ParticleSystem = ParticleSystem;
  45054. })(BABYLON || (BABYLON = {}));
  45055. //# sourceMappingURL=babylon.particleSystem.js.map
  45056. var BABYLON;
  45057. (function (BABYLON) {
  45058. var GPUParticleSystem = /** @class */ (function () {
  45059. function GPUParticleSystem(name, capacity, scene) {
  45060. this.name = name;
  45061. this.emitter = null;
  45062. this.renderingGroupId = 0;
  45063. this.layerMask = 0x0FFFFFFF; // TODO
  45064. this._updateVertexBuffers = {};
  45065. this._renderVertexBuffers = {};
  45066. this._currentRenderId = -1;
  45067. this._started = true;
  45068. /**
  45069. * An event triggered when the system is disposed.
  45070. * @type {BABYLON.Observable}
  45071. */
  45072. this.onDisposeObservable = new BABYLON.Observable();
  45073. this.id = name;
  45074. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45075. this._capacity = capacity;
  45076. this._engine = this._scene.getEngine();
  45077. this._scene.particleSystems.push(this);
  45078. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  45079. var updateEffectOptions = {
  45080. attributes: ["position", "age", "life", "velocity"],
  45081. uniformsNames: [],
  45082. uniformBuffersNames: [],
  45083. samplers: [],
  45084. defines: "",
  45085. fallbacks: null,
  45086. onCompiled: null,
  45087. onError: null,
  45088. indexParameters: null,
  45089. maxSimultaneousLights: 0,
  45090. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  45091. };
  45092. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  45093. }
  45094. GPUParticleSystem.prototype.isStarted = function () {
  45095. return this._started;
  45096. };
  45097. GPUParticleSystem.prototype.start = function () {
  45098. this._started = true;
  45099. };
  45100. GPUParticleSystem.prototype.stop = function () {
  45101. this._started = false;
  45102. };
  45103. GPUParticleSystem.prototype.animate = function () {
  45104. // Do nothing
  45105. };
  45106. GPUParticleSystem.prototype._initialize = function () {
  45107. if (this._renderVAO) {
  45108. return;
  45109. }
  45110. var data = new Array();
  45111. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  45112. // position
  45113. data.push(0.0);
  45114. data.push(0.0);
  45115. data.push(0.0);
  45116. var life = 1 + Math.random() * 10; // TODO: var
  45117. data.push(life + 1); // create the particle as a dead one to create a new one at start
  45118. data.push(life);
  45119. // velocity
  45120. data.push(0.0);
  45121. data.push(0.0);
  45122. data.push(0.0);
  45123. }
  45124. // Update VAO
  45125. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  45126. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  45127. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  45128. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  45129. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  45130. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  45131. this._engine.bindArrayBuffer(null);
  45132. // Render VAO
  45133. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  45134. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  45135. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  45136. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  45137. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  45138. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  45139. this._engine.bindArrayBuffer(null);
  45140. // Links
  45141. this._sourceVAO = this._updateVAO;
  45142. this._targetVAO = this._renderVAO;
  45143. this._sourceBuffer = this._updateBuffer;
  45144. this._targetBuffer = this._renderBuffer;
  45145. };
  45146. GPUParticleSystem.prototype.render = function () {
  45147. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  45148. return 0;
  45149. }
  45150. // Get everything ready to render
  45151. this._initialize();
  45152. if (this._currentRenderId === this._scene.getRenderId()) {
  45153. return 0;
  45154. }
  45155. this._currentRenderId = this._scene.getRenderId();
  45156. // Enable update effect
  45157. this._engine.enableEffect(this._updateEffect);
  45158. this._engine.setState(false);
  45159. // Bind source VAO
  45160. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  45161. // Update
  45162. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  45163. this._engine.setRasterizerState(false);
  45164. this._engine.beginTransformFeedback();
  45165. this._engine.drawPointClouds(0, this._capacity);
  45166. this._engine.endTransformFeedback();
  45167. this._engine.setRasterizerState(true);
  45168. this._engine.bindTransformFeedbackBuffer(null);
  45169. // Enable render effect
  45170. this._engine.enableEffect(this._renderEffect);
  45171. // Bind source VAO
  45172. this._engine.bindVertexArrayObject(this._targetVAO, null);
  45173. // Render
  45174. this._engine.drawPointClouds(0, this._capacity);
  45175. // Switch VAOs
  45176. var tmpVAO = this._sourceVAO;
  45177. this._sourceVAO = this._targetVAO;
  45178. this._targetVAO = tmpVAO;
  45179. // Switch buffers
  45180. var tmpBuffer = this._sourceBuffer;
  45181. this._sourceBuffer = this._targetBuffer;
  45182. this._targetBuffer = tmpBuffer;
  45183. return 0;
  45184. };
  45185. GPUParticleSystem.prototype.rebuild = function () {
  45186. };
  45187. GPUParticleSystem.prototype.dispose = function () {
  45188. var index = this._scene.particleSystems.indexOf(this);
  45189. if (index > -1) {
  45190. this._scene.particleSystems.splice(index, 1);
  45191. }
  45192. //TODO: this._dataBuffer.dispose();
  45193. // Callback
  45194. this.onDisposeObservable.notifyObservers(this);
  45195. this.onDisposeObservable.clear();
  45196. };
  45197. //TODO: Clone / Parse / serialize
  45198. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  45199. return null;
  45200. };
  45201. GPUParticleSystem.prototype.serialize = function () {
  45202. };
  45203. return GPUParticleSystem;
  45204. }());
  45205. BABYLON.GPUParticleSystem = GPUParticleSystem;
  45206. })(BABYLON || (BABYLON = {}));
  45207. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  45208. var BABYLON;
  45209. (function (BABYLON) {
  45210. var SolidParticle = /** @class */ (function () {
  45211. /**
  45212. * Creates a Solid Particle object.
  45213. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  45214. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  45215. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  45216. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  45217. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  45218. * `shapeId` (integer) is the model shape identifier in the SPS.
  45219. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  45220. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  45221. */
  45222. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  45223. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  45224. this.idx = 0; // particle global index
  45225. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  45226. this.position = BABYLON.Vector3.Zero(); // position
  45227. this.rotation = BABYLON.Vector3.Zero(); // rotation
  45228. this.scaling = BABYLON.Vector3.One(); // scaling
  45229. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  45230. this.velocity = BABYLON.Vector3.Zero(); // velocity
  45231. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  45232. this.alive = true; // alive
  45233. this.isVisible = true; // visibility
  45234. this._pos = 0; // index of this particle in the global "positions" array
  45235. this._ind = 0; // index of this particle in the global "indices" array
  45236. this.shapeId = 0; // model shape id
  45237. this.idxInShape = 0; // index of the particle in its shape id
  45238. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  45239. this.idx = particleIndex;
  45240. this._pos = positionIndex;
  45241. this._ind = indiceIndex;
  45242. this._model = model;
  45243. this.shapeId = shapeId;
  45244. this.idxInShape = idxInShape;
  45245. this._sps = sps;
  45246. if (modelBoundingInfo) {
  45247. this._modelBoundingInfo = modelBoundingInfo;
  45248. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  45249. }
  45250. }
  45251. Object.defineProperty(SolidParticle.prototype, "scale", {
  45252. /**
  45253. * legacy support, changed scale to scaling
  45254. */
  45255. get: function () {
  45256. return this.scaling;
  45257. },
  45258. set: function (scale) {
  45259. this.scaling = scale;
  45260. },
  45261. enumerable: true,
  45262. configurable: true
  45263. });
  45264. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  45265. /**
  45266. * legacy support, changed quaternion to rotationQuaternion
  45267. */
  45268. get: function () {
  45269. return this.rotationQuaternion;
  45270. },
  45271. set: function (q) {
  45272. this.rotationQuaternion = q;
  45273. },
  45274. enumerable: true,
  45275. configurable: true
  45276. });
  45277. /**
  45278. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  45279. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  45280. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  45281. */
  45282. SolidParticle.prototype.intersectsMesh = function (target) {
  45283. if (!this._boundingInfo || !target._boundingInfo) {
  45284. return false;
  45285. }
  45286. if (this._sps._bSphereOnly) {
  45287. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  45288. }
  45289. return this._boundingInfo.intersects(target._boundingInfo, false);
  45290. };
  45291. return SolidParticle;
  45292. }());
  45293. BABYLON.SolidParticle = SolidParticle;
  45294. var ModelShape = /** @class */ (function () {
  45295. /**
  45296. * 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.
  45297. * SPS internal tool, don't use it manually.
  45298. */
  45299. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  45300. this._indicesLength = 0; // length of the shape in the model indices array
  45301. this.shapeID = id;
  45302. this._shape = shape;
  45303. this._indicesLength = indicesLength;
  45304. this._shapeUV = shapeUV;
  45305. this._positionFunction = posFunction;
  45306. this._vertexFunction = vtxFunction;
  45307. }
  45308. return ModelShape;
  45309. }());
  45310. BABYLON.ModelShape = ModelShape;
  45311. var DepthSortedParticle = /** @class */ (function () {
  45312. function DepthSortedParticle() {
  45313. this.ind = 0; // index of the particle in the "indices" array
  45314. this.indicesLength = 0; // length of the particle shape in the "indices" array
  45315. this.sqDistance = 0.0; // squared distance from the particle to the camera
  45316. }
  45317. return DepthSortedParticle;
  45318. }());
  45319. BABYLON.DepthSortedParticle = DepthSortedParticle;
  45320. })(BABYLON || (BABYLON = {}));
  45321. //# sourceMappingURL=babylon.solidParticle.js.map
  45322. var BABYLON;
  45323. (function (BABYLON) {
  45324. /**
  45325. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  45326. */
  45327. var SolidParticleSystem = /** @class */ (function () {
  45328. /**
  45329. * Creates a SPS (Solid Particle System) object.
  45330. * `name` (String) is the SPS name, this will be the underlying mesh name.
  45331. * `scene` (Scene) is the scene in which the SPS is added.
  45332. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  45333. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  45334. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  45335. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  45336. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  45337. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  45338. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  45339. */
  45340. function SolidParticleSystem(name, scene, options) {
  45341. // public members
  45342. /**
  45343. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  45344. * Example : var p = SPS.particles[i];
  45345. */
  45346. this.particles = new Array();
  45347. /**
  45348. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  45349. */
  45350. this.nbParticles = 0;
  45351. /**
  45352. * If the particles must ever face the camera (default false). Useful for planar particles.
  45353. */
  45354. this.billboard = false;
  45355. /**
  45356. * Recompute normals when adding a shape
  45357. */
  45358. this.recomputeNormals = true;
  45359. /**
  45360. * This a counter ofr your own usage. It's not set by any SPS functions.
  45361. */
  45362. this.counter = 0;
  45363. /**
  45364. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  45365. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  45366. */
  45367. this.vars = {};
  45368. this._positions = new Array();
  45369. this._indices = new Array();
  45370. this._normals = new Array();
  45371. this._colors = new Array();
  45372. this._uvs = new Array();
  45373. this._index = 0; // indices index
  45374. this._updatable = true;
  45375. this._pickable = false;
  45376. this._isVisibilityBoxLocked = false;
  45377. this._alwaysVisible = false;
  45378. this._depthSort = false;
  45379. this._shapeCounter = 0;
  45380. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  45381. this._color = new BABYLON.Color4(0, 0, 0, 0);
  45382. this._computeParticleColor = true;
  45383. this._computeParticleTexture = true;
  45384. this._computeParticleRotation = true;
  45385. this._computeParticleVertex = false;
  45386. this._computeBoundingBox = false;
  45387. this._depthSortParticles = true;
  45388. this._cam_axisZ = BABYLON.Vector3.Zero();
  45389. this._cam_axisY = BABYLON.Vector3.Zero();
  45390. this._cam_axisX = BABYLON.Vector3.Zero();
  45391. this._axisZ = BABYLON.Axis.Z;
  45392. this._camDir = BABYLON.Vector3.Zero();
  45393. this._camInvertedPosition = BABYLON.Vector3.Zero();
  45394. this._rotMatrix = new BABYLON.Matrix();
  45395. this._invertMatrix = new BABYLON.Matrix();
  45396. this._rotated = BABYLON.Vector3.Zero();
  45397. this._quaternion = new BABYLON.Quaternion();
  45398. this._vertex = BABYLON.Vector3.Zero();
  45399. this._normal = BABYLON.Vector3.Zero();
  45400. this._yaw = 0.0;
  45401. this._pitch = 0.0;
  45402. this._roll = 0.0;
  45403. this._halfroll = 0.0;
  45404. this._halfpitch = 0.0;
  45405. this._halfyaw = 0.0;
  45406. this._sinRoll = 0.0;
  45407. this._cosRoll = 0.0;
  45408. this._sinPitch = 0.0;
  45409. this._cosPitch = 0.0;
  45410. this._sinYaw = 0.0;
  45411. this._cosYaw = 0.0;
  45412. this._mustUnrotateFixedNormals = false;
  45413. this._minimum = BABYLON.Tmp.Vector3[0];
  45414. this._maximum = BABYLON.Tmp.Vector3[1];
  45415. this._minBbox = BABYLON.Tmp.Vector3[4];
  45416. this._maxBbox = BABYLON.Tmp.Vector3[5];
  45417. this._particlesIntersect = false;
  45418. this._depthSortFunction = function (p1, p2) {
  45419. return (p2.sqDistance - p1.sqDistance);
  45420. };
  45421. this._needs32Bits = false;
  45422. this._bSphereOnly = false;
  45423. this._bSphereRadiusFactor = 1.0;
  45424. this.name = name;
  45425. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45426. this._camera = scene.activeCamera;
  45427. this._pickable = options ? options.isPickable : false;
  45428. this._depthSort = options ? options.enableDepthSort : false;
  45429. this._particlesIntersect = options ? options.particleIntersection : false;
  45430. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  45431. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  45432. if (options && options.updatable) {
  45433. this._updatable = options.updatable;
  45434. }
  45435. else {
  45436. this._updatable = true;
  45437. }
  45438. if (this._pickable) {
  45439. this.pickedParticles = [];
  45440. }
  45441. if (this._depthSort) {
  45442. this.depthSortedParticles = [];
  45443. }
  45444. }
  45445. /**
  45446. * Builds the SPS underlying mesh. Returns a standard Mesh.
  45447. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  45448. */
  45449. SolidParticleSystem.prototype.buildMesh = function () {
  45450. if (this.nbParticles === 0) {
  45451. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  45452. this.addShape(triangle, 1);
  45453. triangle.dispose();
  45454. }
  45455. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  45456. this._positions32 = new Float32Array(this._positions);
  45457. this._uvs32 = new Float32Array(this._uvs);
  45458. this._colors32 = new Float32Array(this._colors);
  45459. if (this.recomputeNormals) {
  45460. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  45461. }
  45462. this._normals32 = new Float32Array(this._normals);
  45463. this._fixedNormal32 = new Float32Array(this._normals);
  45464. if (this._mustUnrotateFixedNormals) {
  45465. this._unrotateFixedNormals();
  45466. }
  45467. var vertexData = new BABYLON.VertexData();
  45468. vertexData.indices = this._indices32;
  45469. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  45470. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  45471. if (this._uvs32) {
  45472. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  45473. ;
  45474. }
  45475. if (this._colors32) {
  45476. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  45477. }
  45478. var mesh = new BABYLON.Mesh(this.name, this._scene);
  45479. vertexData.applyToMesh(mesh, this._updatable);
  45480. this.mesh = mesh;
  45481. this.mesh.isPickable = this._pickable;
  45482. // free memory
  45483. if (!this._depthSort) {
  45484. this._indices = null;
  45485. }
  45486. this._positions = null;
  45487. this._normals = null;
  45488. this._uvs = null;
  45489. this._colors = null;
  45490. if (!this._updatable) {
  45491. this.particles.length = 0;
  45492. }
  45493. return mesh;
  45494. };
  45495. /**
  45496. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  45497. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  45498. * Thus the particles generated from `digest()` have their property `position` set yet.
  45499. * `mesh` ( Mesh ) is the mesh to be digested
  45500. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  45501. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  45502. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  45503. */
  45504. SolidParticleSystem.prototype.digest = function (mesh, options) {
  45505. var size = (options && options.facetNb) || 1;
  45506. var number = (options && options.number) || 0;
  45507. var delta = (options && options.delta) || 0;
  45508. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45509. var meshInd = mesh.getIndices();
  45510. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45511. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45512. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45513. var f = 0; // facet counter
  45514. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  45515. // compute size from number
  45516. if (number) {
  45517. number = (number > totalFacets) ? totalFacets : number;
  45518. size = Math.round(totalFacets / number);
  45519. delta = 0;
  45520. }
  45521. else {
  45522. size = (size > totalFacets) ? totalFacets : size;
  45523. }
  45524. var facetPos = []; // submesh positions
  45525. var facetInd = []; // submesh indices
  45526. var facetUV = []; // submesh UV
  45527. var facetCol = []; // submesh colors
  45528. var barycenter = BABYLON.Tmp.Vector3[0];
  45529. var sizeO = size;
  45530. while (f < totalFacets) {
  45531. size = sizeO + Math.floor((1 + delta) * Math.random());
  45532. if (f > totalFacets - size) {
  45533. size = totalFacets - f;
  45534. }
  45535. // reset temp arrays
  45536. facetPos.length = 0;
  45537. facetInd.length = 0;
  45538. facetUV.length = 0;
  45539. facetCol.length = 0;
  45540. // iterate over "size" facets
  45541. var fi = 0;
  45542. for (var j = f * 3; j < (f + size) * 3; j++) {
  45543. facetInd.push(fi);
  45544. var i = meshInd[j];
  45545. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  45546. if (meshUV) {
  45547. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  45548. }
  45549. if (meshCol) {
  45550. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  45551. }
  45552. fi++;
  45553. }
  45554. // create a model shape for each single particle
  45555. var idx = this.nbParticles;
  45556. var shape = this._posToShape(facetPos);
  45557. var shapeUV = this._uvsToShapeUV(facetUV);
  45558. // compute the barycenter of the shape
  45559. var v;
  45560. for (v = 0; v < shape.length; v++) {
  45561. barycenter.addInPlace(shape[v]);
  45562. }
  45563. barycenter.scaleInPlace(1 / shape.length);
  45564. // shift the shape from its barycenter to the origin
  45565. for (v = 0; v < shape.length; v++) {
  45566. shape[v].subtractInPlace(barycenter);
  45567. }
  45568. var bInfo;
  45569. if (this._particlesIntersect) {
  45570. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  45571. }
  45572. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  45573. // add the particle in the SPS
  45574. var currentPos = this._positions.length;
  45575. var currentInd = this._indices.length;
  45576. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  45577. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  45578. // initialize the particle position
  45579. this.particles[this.nbParticles].position.addInPlace(barycenter);
  45580. this._index += shape.length;
  45581. idx++;
  45582. this.nbParticles++;
  45583. this._shapeCounter++;
  45584. f += size;
  45585. }
  45586. return this;
  45587. };
  45588. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  45589. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  45590. var index = 0;
  45591. var idx = 0;
  45592. for (var p = 0; p < this.particles.length; p++) {
  45593. this._particle = this.particles[p];
  45594. this._shape = this._particle._model._shape;
  45595. if (this._particle.rotationQuaternion) {
  45596. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45597. }
  45598. else {
  45599. this._yaw = this._particle.rotation.y;
  45600. this._pitch = this._particle.rotation.x;
  45601. this._roll = this._particle.rotation.z;
  45602. this._quaternionRotationYPR();
  45603. }
  45604. this._quaternionToRotationMatrix();
  45605. this._rotMatrix.invertToRef(this._invertMatrix);
  45606. for (var pt = 0; pt < this._shape.length; pt++) {
  45607. idx = index + pt * 3;
  45608. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  45609. this._fixedNormal32[idx] = this._normal.x;
  45610. this._fixedNormal32[idx + 1] = this._normal.y;
  45611. this._fixedNormal32[idx + 2] = this._normal.z;
  45612. }
  45613. index = idx + 3;
  45614. }
  45615. };
  45616. //reset copy
  45617. SolidParticleSystem.prototype._resetCopy = function () {
  45618. this._copy.position.x = 0;
  45619. this._copy.position.y = 0;
  45620. this._copy.position.z = 0;
  45621. this._copy.rotation.x = 0;
  45622. this._copy.rotation.y = 0;
  45623. this._copy.rotation.z = 0;
  45624. this._copy.rotationQuaternion = null;
  45625. this._copy.scaling.x = 1.0;
  45626. this._copy.scaling.y = 1.0;
  45627. this._copy.scaling.z = 1.0;
  45628. this._copy.uvs.x = 0;
  45629. this._copy.uvs.y = 0;
  45630. this._copy.uvs.z = 1.0;
  45631. this._copy.uvs.w = 1.0;
  45632. this._copy.color = null;
  45633. };
  45634. // _meshBuilder : inserts the shape model in the global SPS mesh
  45635. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  45636. var i;
  45637. var u = 0;
  45638. var c = 0;
  45639. var n = 0;
  45640. this._resetCopy();
  45641. if (options && options.positionFunction) {
  45642. options.positionFunction(this._copy, idx, idxInShape);
  45643. this._mustUnrotateFixedNormals = true;
  45644. }
  45645. if (this._copy.rotationQuaternion) {
  45646. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45647. }
  45648. else {
  45649. this._yaw = this._copy.rotation.y;
  45650. this._pitch = this._copy.rotation.x;
  45651. this._roll = this._copy.rotation.z;
  45652. this._quaternionRotationYPR();
  45653. }
  45654. this._quaternionToRotationMatrix();
  45655. for (i = 0; i < shape.length; i++) {
  45656. this._vertex.x = shape[i].x;
  45657. this._vertex.y = shape[i].y;
  45658. this._vertex.z = shape[i].z;
  45659. if (options && options.vertexFunction) {
  45660. options.vertexFunction(this._copy, this._vertex, i);
  45661. }
  45662. this._vertex.x *= this._copy.scaling.x;
  45663. this._vertex.y *= this._copy.scaling.y;
  45664. this._vertex.z *= this._copy.scaling.z;
  45665. this._vertex.x += this._copy.pivot.x;
  45666. this._vertex.y += this._copy.pivot.y;
  45667. this._vertex.z += this._copy.pivot.z;
  45668. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45669. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  45670. if (meshUV) {
  45671. 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);
  45672. u += 2;
  45673. }
  45674. if (this._copy.color) {
  45675. this._color = this._copy.color;
  45676. }
  45677. else if (meshCol && meshCol[c] !== undefined) {
  45678. this._color.r = meshCol[c];
  45679. this._color.g = meshCol[c + 1];
  45680. this._color.b = meshCol[c + 2];
  45681. this._color.a = meshCol[c + 3];
  45682. }
  45683. else {
  45684. this._color.r = 1.0;
  45685. this._color.g = 1.0;
  45686. this._color.b = 1.0;
  45687. this._color.a = 1.0;
  45688. }
  45689. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  45690. c += 4;
  45691. if (!this.recomputeNormals && meshNor) {
  45692. this._normal.x = meshNor[n];
  45693. this._normal.y = meshNor[n + 1];
  45694. this._normal.z = meshNor[n + 2];
  45695. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  45696. normals.push(this._normal.x, this._normal.y, this._normal.z);
  45697. n += 3;
  45698. }
  45699. }
  45700. for (i = 0; i < meshInd.length; i++) {
  45701. var current_ind = p + meshInd[i];
  45702. indices.push(current_ind);
  45703. if (current_ind > 65535) {
  45704. this._needs32Bits = true;
  45705. }
  45706. }
  45707. if (this._pickable) {
  45708. var nbfaces = meshInd.length / 3;
  45709. for (i = 0; i < nbfaces; i++) {
  45710. this.pickedParticles.push({ idx: idx, faceId: i });
  45711. }
  45712. }
  45713. if (this._depthSort) {
  45714. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  45715. }
  45716. return this._copy;
  45717. };
  45718. // returns a shape array from positions array
  45719. SolidParticleSystem.prototype._posToShape = function (positions) {
  45720. var shape = [];
  45721. for (var i = 0; i < positions.length; i += 3) {
  45722. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  45723. }
  45724. return shape;
  45725. };
  45726. // returns a shapeUV array from a Vector4 uvs
  45727. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  45728. var shapeUV = [];
  45729. if (uvs) {
  45730. for (var i = 0; i < uvs.length; i++)
  45731. shapeUV.push(uvs[i]);
  45732. }
  45733. return shapeUV;
  45734. };
  45735. // adds a new particle object in the particles array
  45736. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  45737. if (bInfo === void 0) { bInfo = null; }
  45738. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  45739. this.particles.push(sp);
  45740. return sp;
  45741. };
  45742. /**
  45743. * Adds some particles to the SPS from the model shape. Returns the shape id.
  45744. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  45745. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  45746. * `nb` (positive integer) the number of particles to be created from this model
  45747. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  45748. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  45749. */
  45750. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  45751. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45752. var meshInd = mesh.getIndices();
  45753. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45754. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45755. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45756. var bbInfo;
  45757. if (this._particlesIntersect) {
  45758. bbInfo = mesh.getBoundingInfo();
  45759. }
  45760. var shape = this._posToShape(meshPos);
  45761. var shapeUV = this._uvsToShapeUV(meshUV);
  45762. var posfunc = options ? options.positionFunction : null;
  45763. var vtxfunc = options ? options.vertexFunction : null;
  45764. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  45765. // particles
  45766. var sp;
  45767. var currentCopy;
  45768. var idx = this.nbParticles;
  45769. for (var i = 0; i < nb; i++) {
  45770. var currentPos = this._positions.length;
  45771. var currentInd = this._indices.length;
  45772. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  45773. if (this._updatable) {
  45774. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  45775. sp.position.copyFrom(currentCopy.position);
  45776. sp.rotation.copyFrom(currentCopy.rotation);
  45777. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  45778. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  45779. }
  45780. if (currentCopy.color && sp.color) {
  45781. sp.color.copyFrom(currentCopy.color);
  45782. }
  45783. sp.scaling.copyFrom(currentCopy.scaling);
  45784. sp.uvs.copyFrom(currentCopy.uvs);
  45785. }
  45786. this._index += shape.length;
  45787. idx++;
  45788. }
  45789. this.nbParticles += nb;
  45790. this._shapeCounter++;
  45791. return this._shapeCounter - 1;
  45792. };
  45793. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  45794. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  45795. this._resetCopy();
  45796. if (particle._model._positionFunction) {
  45797. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  45798. }
  45799. if (this._copy.rotationQuaternion) {
  45800. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45801. }
  45802. else {
  45803. this._yaw = this._copy.rotation.y;
  45804. this._pitch = this._copy.rotation.x;
  45805. this._roll = this._copy.rotation.z;
  45806. this._quaternionRotationYPR();
  45807. }
  45808. this._quaternionToRotationMatrix();
  45809. this._shape = particle._model._shape;
  45810. for (var pt = 0; pt < this._shape.length; pt++) {
  45811. this._vertex.x = this._shape[pt].x;
  45812. this._vertex.y = this._shape[pt].y;
  45813. this._vertex.z = this._shape[pt].z;
  45814. if (particle._model._vertexFunction) {
  45815. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  45816. }
  45817. this._vertex.x *= this._copy.scaling.x;
  45818. this._vertex.y *= this._copy.scaling.y;
  45819. this._vertex.z *= this._copy.scaling.z;
  45820. this._vertex.x += this._copy.pivot.x;
  45821. this._vertex.y += this._copy.pivot.y;
  45822. this._vertex.z += this._copy.pivot.z;
  45823. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45824. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  45825. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  45826. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  45827. }
  45828. particle.position.x = 0.0;
  45829. particle.position.y = 0.0;
  45830. particle.position.z = 0.0;
  45831. particle.rotation.x = 0.0;
  45832. particle.rotation.y = 0.0;
  45833. particle.rotation.z = 0.0;
  45834. particle.rotationQuaternion = null;
  45835. particle.scaling.x = 1.0;
  45836. particle.scaling.y = 1.0;
  45837. particle.scaling.z = 1.0;
  45838. };
  45839. /**
  45840. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45841. * Returns the SPS.
  45842. */
  45843. SolidParticleSystem.prototype.rebuildMesh = function () {
  45844. for (var p = 0; p < this.particles.length; p++) {
  45845. this._rebuildParticle(this.particles[p]);
  45846. }
  45847. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45848. return this;
  45849. };
  45850. /**
  45851. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45852. * This method calls `updateParticle()` for each particle of the SPS.
  45853. * For an animated SPS, it is usually called within the render loop.
  45854. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45855. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45856. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45857. * Returns the SPS.
  45858. */
  45859. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  45860. if (start === void 0) { start = 0; }
  45861. if (end === void 0) { end = this.nbParticles - 1; }
  45862. if (update === void 0) { update = true; }
  45863. if (!this._updatable) {
  45864. return this;
  45865. }
  45866. // custom beforeUpdate
  45867. this.beforeUpdateParticles(start, end, update);
  45868. this._cam_axisX.x = 1.0;
  45869. this._cam_axisX.y = 0.0;
  45870. this._cam_axisX.z = 0.0;
  45871. this._cam_axisY.x = 0.0;
  45872. this._cam_axisY.y = 1.0;
  45873. this._cam_axisY.z = 0.0;
  45874. this._cam_axisZ.x = 0.0;
  45875. this._cam_axisZ.y = 0.0;
  45876. this._cam_axisZ.z = 1.0;
  45877. // cases when the World Matrix is to be computed first
  45878. if (this.billboard || this._depthSort) {
  45879. this.mesh.computeWorldMatrix(true);
  45880. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  45881. }
  45882. // if the particles will always face the camera
  45883. if (this.billboard) {
  45884. // compute the camera position and un-rotate it by the current mesh rotation
  45885. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  45886. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  45887. this._cam_axisZ.normalize();
  45888. // same for camera up vector extracted from the cam view matrix
  45889. var view = this._camera.getViewMatrix(true);
  45890. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  45891. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  45892. this._cam_axisY.normalize();
  45893. this._cam_axisX.normalize();
  45894. }
  45895. // if depthSort, compute the camera global position in the mesh local system
  45896. if (this._depthSort) {
  45897. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  45898. }
  45899. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  45900. var idx = 0; // current position index in the global array positions32
  45901. var index = 0; // position start index in the global array positions32 of the current particle
  45902. var colidx = 0; // current color index in the global array colors32
  45903. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  45904. var uvidx = 0; // current uv index in the global array uvs32
  45905. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  45906. var pt = 0; // current index in the particle model shape
  45907. if (this.mesh.isFacetDataEnabled) {
  45908. this._computeBoundingBox = true;
  45909. }
  45910. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  45911. if (this._computeBoundingBox) {
  45912. if (start == 0 && end == this.nbParticles - 1) {
  45913. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  45914. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  45915. }
  45916. else {
  45917. if (this.mesh._boundingInfo) {
  45918. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  45919. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  45920. }
  45921. }
  45922. }
  45923. // particle loop
  45924. index = this.particles[start]._pos;
  45925. var vpos = (index / 3) | 0;
  45926. colorIndex = vpos * 4;
  45927. uvIndex = vpos * 2;
  45928. for (var p = start; p <= end; p++) {
  45929. this._particle = this.particles[p];
  45930. this._shape = this._particle._model._shape;
  45931. this._shapeUV = this._particle._model._shapeUV;
  45932. // call to custom user function to update the particle properties
  45933. this.updateParticle(this._particle);
  45934. // camera-particle distance for depth sorting
  45935. if (this._depthSort && this._depthSortParticles) {
  45936. var dsp = this.depthSortedParticles[p];
  45937. dsp.ind = this._particle._ind;
  45938. dsp.indicesLength = this._particle._model._indicesLength;
  45939. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  45940. }
  45941. // skip the computations for inactive or already invisible particles
  45942. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  45943. // increment indexes for the next particle
  45944. pt = this._shape.length;
  45945. index += pt * 3;
  45946. colorIndex += pt * 4;
  45947. uvIndex += pt * 2;
  45948. continue;
  45949. }
  45950. if (this._particle.isVisible) {
  45951. this._particle._stillInvisible = false; // un-mark permanent invisibility
  45952. // particle rotation matrix
  45953. if (this.billboard) {
  45954. this._particle.rotation.x = 0.0;
  45955. this._particle.rotation.y = 0.0;
  45956. }
  45957. if (this._computeParticleRotation || this.billboard) {
  45958. if (this._particle.rotationQuaternion) {
  45959. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45960. }
  45961. else {
  45962. this._yaw = this._particle.rotation.y;
  45963. this._pitch = this._particle.rotation.x;
  45964. this._roll = this._particle.rotation.z;
  45965. this._quaternionRotationYPR();
  45966. }
  45967. this._quaternionToRotationMatrix();
  45968. }
  45969. // particle vertex loop
  45970. for (pt = 0; pt < this._shape.length; pt++) {
  45971. idx = index + pt * 3;
  45972. colidx = colorIndex + pt * 4;
  45973. uvidx = uvIndex + pt * 2;
  45974. this._vertex.x = this._shape[pt].x;
  45975. this._vertex.y = this._shape[pt].y;
  45976. this._vertex.z = this._shape[pt].z;
  45977. if (this._computeParticleVertex) {
  45978. this.updateParticleVertex(this._particle, this._vertex, pt);
  45979. }
  45980. // positions
  45981. this._vertex.x *= this._particle.scaling.x;
  45982. this._vertex.y *= this._particle.scaling.y;
  45983. this._vertex.z *= this._particle.scaling.z;
  45984. this._vertex.x += this._particle.pivot.x;
  45985. this._vertex.y += this._particle.pivot.y;
  45986. this._vertex.z += this._particle.pivot.z;
  45987. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45988. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45989. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45990. this._positions32[idx] = 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;
  45991. this._positions32[idx + 1] = 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;
  45992. this._positions32[idx + 2] = 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;
  45993. if (this._computeBoundingBox) {
  45994. if (this._positions32[idx] < this._minimum.x) {
  45995. this._minimum.x = this._positions32[idx];
  45996. }
  45997. if (this._positions32[idx] > this._maximum.x) {
  45998. this._maximum.x = this._positions32[idx];
  45999. }
  46000. if (this._positions32[idx + 1] < this._minimum.y) {
  46001. this._minimum.y = this._positions32[idx + 1];
  46002. }
  46003. if (this._positions32[idx + 1] > this._maximum.y) {
  46004. this._maximum.y = this._positions32[idx + 1];
  46005. }
  46006. if (this._positions32[idx + 2] < this._minimum.z) {
  46007. this._minimum.z = this._positions32[idx + 2];
  46008. }
  46009. if (this._positions32[idx + 2] > this._maximum.z) {
  46010. this._maximum.z = this._positions32[idx + 2];
  46011. }
  46012. }
  46013. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  46014. if (!this._computeParticleVertex) {
  46015. this._normal.x = this._fixedNormal32[idx];
  46016. this._normal.y = this._fixedNormal32[idx + 1];
  46017. this._normal.z = this._fixedNormal32[idx + 2];
  46018. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  46019. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  46020. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  46021. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  46022. 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;
  46023. 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;
  46024. }
  46025. if (this._computeParticleColor && this._particle.color) {
  46026. this._colors32[colidx] = this._particle.color.r;
  46027. this._colors32[colidx + 1] = this._particle.color.g;
  46028. this._colors32[colidx + 2] = this._particle.color.b;
  46029. this._colors32[colidx + 3] = this._particle.color.a;
  46030. }
  46031. if (this._computeParticleTexture) {
  46032. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46033. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46034. }
  46035. }
  46036. }
  46037. else {
  46038. this._particle._stillInvisible = true; // mark the particle as invisible
  46039. for (pt = 0; pt < this._shape.length; pt++) {
  46040. idx = index + pt * 3;
  46041. colidx = colorIndex + pt * 4;
  46042. uvidx = uvIndex + pt * 2;
  46043. this._positions32[idx] = 0.0;
  46044. this._positions32[idx + 1] = 0.0;
  46045. this._positions32[idx + 2] = 0.0;
  46046. this._normals32[idx] = 0.0;
  46047. this._normals32[idx + 1] = 0.0;
  46048. this._normals32[idx + 2] = 0.0;
  46049. if (this._computeParticleColor && this._particle.color) {
  46050. this._colors32[colidx] = this._particle.color.r;
  46051. this._colors32[colidx + 1] = this._particle.color.g;
  46052. this._colors32[colidx + 2] = this._particle.color.b;
  46053. this._colors32[colidx + 3] = this._particle.color.a;
  46054. }
  46055. if (this._computeParticleTexture) {
  46056. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  46057. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  46058. }
  46059. }
  46060. }
  46061. // if the particle intersections must be computed : update the bbInfo
  46062. if (this._particlesIntersect) {
  46063. var bInfo = this._particle._boundingInfo;
  46064. var bBox = bInfo.boundingBox;
  46065. var bSphere = bInfo.boundingSphere;
  46066. if (!this._bSphereOnly) {
  46067. // place, scale and rotate the particle bbox within the SPS local system, then update it
  46068. for (var b = 0; b < bBox.vectors.length; b++) {
  46069. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  46070. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  46071. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  46072. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  46073. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  46074. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  46075. 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;
  46076. 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;
  46077. 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;
  46078. }
  46079. bBox._update(this.mesh._worldMatrix);
  46080. }
  46081. // place and scale the particle bouding sphere in the SPS local system, then update it
  46082. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  46083. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  46084. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  46085. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  46086. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  46087. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  46088. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  46089. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  46090. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  46091. 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));
  46092. bSphere._update(this.mesh._worldMatrix);
  46093. }
  46094. // increment indexes for the next particle
  46095. index = idx + 3;
  46096. colorIndex = colidx + 4;
  46097. uvIndex = uvidx + 2;
  46098. }
  46099. // if the VBO must be updated
  46100. if (update) {
  46101. if (this._computeParticleColor) {
  46102. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  46103. }
  46104. if (this._computeParticleTexture) {
  46105. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  46106. }
  46107. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  46108. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  46109. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  46110. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  46111. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  46112. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  46113. for (var i = 0; i < this._normals32.length; i++) {
  46114. this._fixedNormal32[i] = this._normals32[i];
  46115. }
  46116. }
  46117. if (!this.mesh.areNormalsFrozen) {
  46118. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  46119. }
  46120. }
  46121. if (this._depthSort && this._depthSortParticles) {
  46122. this.depthSortedParticles.sort(this._depthSortFunction);
  46123. var dspl = this.depthSortedParticles.length;
  46124. var sorted = 0;
  46125. var lind = 0;
  46126. var sind = 0;
  46127. var sid = 0;
  46128. for (sorted = 0; sorted < dspl; sorted++) {
  46129. lind = this.depthSortedParticles[sorted].indicesLength;
  46130. sind = this.depthSortedParticles[sorted].ind;
  46131. for (var i = 0; i < lind; i++) {
  46132. this._indices32[sid] = this._indices[sind + i];
  46133. sid++;
  46134. }
  46135. }
  46136. this.mesh.updateIndices(this._indices32);
  46137. }
  46138. }
  46139. if (this._computeBoundingBox) {
  46140. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  46141. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  46142. }
  46143. this.afterUpdateParticles(start, end, update);
  46144. return this;
  46145. };
  46146. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  46147. this._halfroll = this._roll * 0.5;
  46148. this._halfpitch = this._pitch * 0.5;
  46149. this._halfyaw = this._yaw * 0.5;
  46150. this._sinRoll = Math.sin(this._halfroll);
  46151. this._cosRoll = Math.cos(this._halfroll);
  46152. this._sinPitch = Math.sin(this._halfpitch);
  46153. this._cosPitch = Math.cos(this._halfpitch);
  46154. this._sinYaw = Math.sin(this._halfyaw);
  46155. this._cosYaw = Math.cos(this._halfyaw);
  46156. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  46157. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  46158. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  46159. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  46160. };
  46161. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  46162. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  46163. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  46164. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  46165. this._rotMatrix.m[3] = 0;
  46166. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  46167. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  46168. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  46169. this._rotMatrix.m[7] = 0;
  46170. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  46171. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  46172. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  46173. this._rotMatrix.m[11] = 0;
  46174. this._rotMatrix.m[12] = 0;
  46175. this._rotMatrix.m[13] = 0;
  46176. this._rotMatrix.m[14] = 0;
  46177. this._rotMatrix.m[15] = 1.0;
  46178. };
  46179. /**
  46180. * Disposes the SPS.
  46181. * Returns nothing.
  46182. */
  46183. SolidParticleSystem.prototype.dispose = function () {
  46184. this.mesh.dispose();
  46185. this.vars = null;
  46186. // drop references to internal big arrays for the GC
  46187. this._positions = null;
  46188. this._indices = null;
  46189. this._normals = null;
  46190. this._uvs = null;
  46191. this._colors = null;
  46192. this._indices32 = null;
  46193. this._positions32 = null;
  46194. this._normals32 = null;
  46195. this._fixedNormal32 = null;
  46196. this._uvs32 = null;
  46197. this._colors32 = null;
  46198. this.pickedParticles = null;
  46199. };
  46200. /**
  46201. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  46202. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46203. * Returns the SPS.
  46204. */
  46205. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  46206. if (!this._isVisibilityBoxLocked) {
  46207. this.mesh.refreshBoundingInfo();
  46208. }
  46209. return this;
  46210. };
  46211. /**
  46212. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  46213. * @param size the size (float) of the visibility box
  46214. * note : this doesn't lock the SPS mesh bounding box.
  46215. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46216. */
  46217. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  46218. var vis = size / 2;
  46219. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  46220. };
  46221. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  46222. // getter and setter
  46223. get: function () {
  46224. return this._alwaysVisible;
  46225. },
  46226. /**
  46227. * Sets the SPS as always visible or not
  46228. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46229. */
  46230. set: function (val) {
  46231. this._alwaysVisible = val;
  46232. this.mesh.alwaysSelectAsActiveMesh = val;
  46233. },
  46234. enumerable: true,
  46235. configurable: true
  46236. });
  46237. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  46238. get: function () {
  46239. return this._isVisibilityBoxLocked;
  46240. },
  46241. /**
  46242. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  46243. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  46244. */
  46245. set: function (val) {
  46246. this._isVisibilityBoxLocked = val;
  46247. var boundingInfo = this.mesh.getBoundingInfo();
  46248. if (boundingInfo) {
  46249. boundingInfo.isLocked = val;
  46250. }
  46251. },
  46252. enumerable: true,
  46253. configurable: true
  46254. });
  46255. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  46256. // getters
  46257. get: function () {
  46258. return this._computeParticleRotation;
  46259. },
  46260. // Optimizer setters
  46261. /**
  46262. * Tells to `setParticles()` to compute the particle rotations or not.
  46263. * Default value : true. The SPS is faster when it's set to false.
  46264. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  46265. */
  46266. set: function (val) {
  46267. this._computeParticleRotation = val;
  46268. },
  46269. enumerable: true,
  46270. configurable: true
  46271. });
  46272. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  46273. get: function () {
  46274. return this._computeParticleColor;
  46275. },
  46276. /**
  46277. * Tells to `setParticles()` to compute the particle colors or not.
  46278. * Default value : true. The SPS is faster when it's set to false.
  46279. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  46280. */
  46281. set: function (val) {
  46282. this._computeParticleColor = val;
  46283. },
  46284. enumerable: true,
  46285. configurable: true
  46286. });
  46287. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  46288. get: function () {
  46289. return this._computeParticleTexture;
  46290. },
  46291. /**
  46292. * Tells to `setParticles()` to compute the particle textures or not.
  46293. * Default value : true. The SPS is faster when it's set to false.
  46294. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  46295. */
  46296. set: function (val) {
  46297. this._computeParticleTexture = val;
  46298. },
  46299. enumerable: true,
  46300. configurable: true
  46301. });
  46302. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  46303. get: function () {
  46304. return this._computeParticleVertex;
  46305. },
  46306. /**
  46307. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  46308. * Default value : false. The SPS is faster when it's set to false.
  46309. * Note : the particle custom vertex positions aren't stored values.
  46310. */
  46311. set: function (val) {
  46312. this._computeParticleVertex = val;
  46313. },
  46314. enumerable: true,
  46315. configurable: true
  46316. });
  46317. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  46318. get: function () {
  46319. return this._computeBoundingBox;
  46320. },
  46321. /**
  46322. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  46323. */
  46324. set: function (val) {
  46325. this._computeBoundingBox = val;
  46326. },
  46327. enumerable: true,
  46328. configurable: true
  46329. });
  46330. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  46331. get: function () {
  46332. return this._depthSortParticles;
  46333. },
  46334. /**
  46335. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  46336. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  46337. * Default : `true`
  46338. */
  46339. set: function (val) {
  46340. this._depthSortParticles = val;
  46341. },
  46342. enumerable: true,
  46343. configurable: true
  46344. });
  46345. // =======================================================================
  46346. // Particle behavior logic
  46347. // these following methods may be overwritten by the user to fit his needs
  46348. /**
  46349. * This function does nothing. It may be overwritten to set all the particle first values.
  46350. * The SPS doesn't call this function, you may have to call it by your own.
  46351. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46352. */
  46353. SolidParticleSystem.prototype.initParticles = function () {
  46354. };
  46355. /**
  46356. * This function does nothing. It may be overwritten to recycle a particle.
  46357. * The SPS doesn't call this function, you may have to call it by your own.
  46358. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46359. */
  46360. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  46361. return particle;
  46362. };
  46363. /**
  46364. * Updates a particle : this function should be overwritten by the user.
  46365. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  46366. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  46367. * ex : just set a particle position or velocity and recycle conditions
  46368. */
  46369. SolidParticleSystem.prototype.updateParticle = function (particle) {
  46370. return particle;
  46371. };
  46372. /**
  46373. * Updates a vertex of a particle : it can be overwritten by the user.
  46374. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  46375. * @param particle the current particle
  46376. * @param vertex the current index of the current particle
  46377. * @param pt the index of the current vertex in the particle shape
  46378. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  46379. * ex : just set a vertex particle position
  46380. */
  46381. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  46382. return vertex;
  46383. };
  46384. /**
  46385. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  46386. * This does nothing and may be overwritten by the user.
  46387. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46388. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46389. * @param update the boolean update value actually passed to setParticles()
  46390. */
  46391. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  46392. };
  46393. /**
  46394. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  46395. * This will be passed three parameters.
  46396. * This does nothing and may be overwritten by the user.
  46397. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46398. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  46399. * @param update the boolean update value actually passed to setParticles()
  46400. */
  46401. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  46402. };
  46403. return SolidParticleSystem;
  46404. }());
  46405. BABYLON.SolidParticleSystem = SolidParticleSystem;
  46406. })(BABYLON || (BABYLON = {}));
  46407. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  46408. var BABYLON;
  46409. (function (BABYLON) {
  46410. var GroundMesh = /** @class */ (function (_super) {
  46411. __extends(GroundMesh, _super);
  46412. function GroundMesh(name, scene) {
  46413. var _this = _super.call(this, name, scene) || this;
  46414. _this.generateOctree = false;
  46415. return _this;
  46416. }
  46417. GroundMesh.prototype.getClassName = function () {
  46418. return "GroundMesh";
  46419. };
  46420. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  46421. get: function () {
  46422. return Math.min(this._subdivisionsX, this._subdivisionsY);
  46423. },
  46424. enumerable: true,
  46425. configurable: true
  46426. });
  46427. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  46428. get: function () {
  46429. return this._subdivisionsX;
  46430. },
  46431. enumerable: true,
  46432. configurable: true
  46433. });
  46434. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  46435. get: function () {
  46436. return this._subdivisionsY;
  46437. },
  46438. enumerable: true,
  46439. configurable: true
  46440. });
  46441. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  46442. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  46443. this._subdivisionsX = chunksCount;
  46444. this._subdivisionsY = chunksCount;
  46445. this.subdivide(chunksCount);
  46446. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  46447. };
  46448. /**
  46449. * Returns a height (y) value in the Worl system :
  46450. * the ground altitude at the coordinates (x, z) expressed in the World system.
  46451. * Returns the ground y position if (x, z) are outside the ground surface.
  46452. */
  46453. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  46454. var world = this.getWorldMatrix();
  46455. var invMat = BABYLON.Tmp.Matrix[5];
  46456. world.invertToRef(invMat);
  46457. var tmpVect = BABYLON.Tmp.Vector3[8];
  46458. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  46459. x = tmpVect.x;
  46460. z = tmpVect.z;
  46461. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46462. return this.position.y;
  46463. }
  46464. if (!this._heightQuads || this._heightQuads.length == 0) {
  46465. this._initHeightQuads();
  46466. this._computeHeightQuads();
  46467. }
  46468. var facet = this._getFacetAt(x, z);
  46469. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  46470. // return y in the World system
  46471. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  46472. return tmpVect.y;
  46473. };
  46474. /**
  46475. * Returns a normalized vector (Vector3) orthogonal to the ground
  46476. * at the ground coordinates (x, z) expressed in the World system.
  46477. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  46478. */
  46479. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  46480. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  46481. this.getNormalAtCoordinatesToRef(x, z, normal);
  46482. return normal;
  46483. };
  46484. /**
  46485. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  46486. * at the ground coordinates (x, z) expressed in the World system.
  46487. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  46488. * Returns the GroundMesh.
  46489. */
  46490. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  46491. var world = this.getWorldMatrix();
  46492. var tmpMat = BABYLON.Tmp.Matrix[5];
  46493. world.invertToRef(tmpMat);
  46494. var tmpVect = BABYLON.Tmp.Vector3[8];
  46495. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  46496. x = tmpVect.x;
  46497. z = tmpVect.z;
  46498. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46499. return this;
  46500. }
  46501. if (!this._heightQuads || this._heightQuads.length == 0) {
  46502. this._initHeightQuads();
  46503. this._computeHeightQuads();
  46504. }
  46505. var facet = this._getFacetAt(x, z);
  46506. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  46507. return this;
  46508. };
  46509. /**
  46510. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  46511. * if the ground has been updated.
  46512. * This can be used in the render loop.
  46513. * Returns the GroundMesh.
  46514. */
  46515. GroundMesh.prototype.updateCoordinateHeights = function () {
  46516. if (!this._heightQuads || this._heightQuads.length == 0) {
  46517. this._initHeightQuads();
  46518. }
  46519. this._computeHeightQuads();
  46520. return this;
  46521. };
  46522. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  46523. GroundMesh.prototype._getFacetAt = function (x, z) {
  46524. // retrieve col and row from x, z coordinates in the ground local system
  46525. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  46526. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  46527. var quad = this._heightQuads[row * this._subdivisionsX + col];
  46528. var facet;
  46529. if (z < quad.slope.x * x + quad.slope.y) {
  46530. facet = quad.facet1;
  46531. }
  46532. else {
  46533. facet = quad.facet2;
  46534. }
  46535. return facet;
  46536. };
  46537. // Creates and populates the heightMap array with "facet" elements :
  46538. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  46539. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46540. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46541. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46542. // Returns the GroundMesh.
  46543. GroundMesh.prototype._initHeightQuads = function () {
  46544. var subdivisionsX = this._subdivisionsX;
  46545. var subdivisionsY = this._subdivisionsY;
  46546. this._heightQuads = new Array();
  46547. for (var row = 0; row < subdivisionsY; row++) {
  46548. for (var col = 0; col < subdivisionsX; col++) {
  46549. 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) };
  46550. this._heightQuads[row * subdivisionsX + col] = quad;
  46551. }
  46552. }
  46553. return this;
  46554. };
  46555. // Compute each quad element values and update the the heightMap array :
  46556. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46557. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46558. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46559. // Returns the GroundMesh.
  46560. GroundMesh.prototype._computeHeightQuads = function () {
  46561. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46562. if (!positions) {
  46563. return this;
  46564. }
  46565. var v1 = BABYLON.Tmp.Vector3[3];
  46566. var v2 = BABYLON.Tmp.Vector3[2];
  46567. var v3 = BABYLON.Tmp.Vector3[1];
  46568. var v4 = BABYLON.Tmp.Vector3[0];
  46569. var v1v2 = BABYLON.Tmp.Vector3[4];
  46570. var v1v3 = BABYLON.Tmp.Vector3[5];
  46571. var v1v4 = BABYLON.Tmp.Vector3[6];
  46572. var norm1 = BABYLON.Tmp.Vector3[7];
  46573. var norm2 = BABYLON.Tmp.Vector3[8];
  46574. var i = 0;
  46575. var j = 0;
  46576. var k = 0;
  46577. var cd = 0; // 2D slope coefficient : z = cd * x + h
  46578. var h = 0;
  46579. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  46580. var d2 = 0;
  46581. var subdivisionsX = this._subdivisionsX;
  46582. var subdivisionsY = this._subdivisionsY;
  46583. for (var row = 0; row < subdivisionsY; row++) {
  46584. for (var col = 0; col < subdivisionsX; col++) {
  46585. i = col * 3;
  46586. j = row * (subdivisionsX + 1) * 3;
  46587. k = (row + 1) * (subdivisionsX + 1) * 3;
  46588. v1.x = positions[j + i];
  46589. v1.y = positions[j + i + 1];
  46590. v1.z = positions[j + i + 2];
  46591. v2.x = positions[j + i + 3];
  46592. v2.y = positions[j + i + 4];
  46593. v2.z = positions[j + i + 5];
  46594. v3.x = positions[k + i];
  46595. v3.y = positions[k + i + 1];
  46596. v3.z = positions[k + i + 2];
  46597. v4.x = positions[k + i + 3];
  46598. v4.y = positions[k + i + 4];
  46599. v4.z = positions[k + i + 5];
  46600. // 2D slope V1V4
  46601. cd = (v4.z - v1.z) / (v4.x - v1.x);
  46602. h = v1.z - cd * v1.x; // v1 belongs to the slope
  46603. // facet equations :
  46604. // we compute each facet normal vector
  46605. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  46606. // we compute the value d by applying the equation to v1 which belongs to the plane
  46607. // then we store the facet equation in a Vector4
  46608. v2.subtractToRef(v1, v1v2);
  46609. v3.subtractToRef(v1, v1v3);
  46610. v4.subtractToRef(v1, v1v4);
  46611. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  46612. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  46613. norm1.normalize();
  46614. norm2.normalize();
  46615. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  46616. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  46617. var quad = this._heightQuads[row * subdivisionsX + col];
  46618. quad.slope.copyFromFloats(cd, h);
  46619. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  46620. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  46621. }
  46622. }
  46623. return this;
  46624. };
  46625. GroundMesh.prototype.serialize = function (serializationObject) {
  46626. _super.prototype.serialize.call(this, serializationObject);
  46627. serializationObject.subdivisionsX = this._subdivisionsX;
  46628. serializationObject.subdivisionsY = this._subdivisionsY;
  46629. serializationObject.minX = this._minX;
  46630. serializationObject.maxX = this._maxX;
  46631. serializationObject.minZ = this._minZ;
  46632. serializationObject.maxZ = this._maxZ;
  46633. serializationObject.width = this._width;
  46634. serializationObject.height = this._height;
  46635. };
  46636. GroundMesh.Parse = function (parsedMesh, scene) {
  46637. var result = new GroundMesh(parsedMesh.name, scene);
  46638. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  46639. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  46640. result._minX = parsedMesh.minX;
  46641. result._maxX = parsedMesh.maxX;
  46642. result._minZ = parsedMesh.minZ;
  46643. result._maxZ = parsedMesh.maxZ;
  46644. result._width = parsedMesh.width;
  46645. result._height = parsedMesh.height;
  46646. return result;
  46647. };
  46648. return GroundMesh;
  46649. }(BABYLON.Mesh));
  46650. BABYLON.GroundMesh = GroundMesh;
  46651. })(BABYLON || (BABYLON = {}));
  46652. //# sourceMappingURL=babylon.groundMesh.js.map
  46653. var BABYLON;
  46654. (function (BABYLON) {
  46655. /**
  46656. * Creates an instance based on a source mesh.
  46657. */
  46658. var InstancedMesh = /** @class */ (function (_super) {
  46659. __extends(InstancedMesh, _super);
  46660. function InstancedMesh(name, source) {
  46661. var _this = _super.call(this, name, source.getScene()) || this;
  46662. source.instances.push(_this);
  46663. _this._sourceMesh = source;
  46664. _this.position.copyFrom(source.position);
  46665. _this.rotation.copyFrom(source.rotation);
  46666. _this.scaling.copyFrom(source.scaling);
  46667. if (source.rotationQuaternion) {
  46668. _this.rotationQuaternion = source.rotationQuaternion.clone();
  46669. }
  46670. _this.infiniteDistance = source.infiniteDistance;
  46671. _this.setPivotMatrix(source.getPivotMatrix());
  46672. _this.refreshBoundingInfo();
  46673. _this._syncSubMeshes();
  46674. return _this;
  46675. }
  46676. /**
  46677. * Returns the string "InstancedMesh".
  46678. */
  46679. InstancedMesh.prototype.getClassName = function () {
  46680. return "InstancedMesh";
  46681. };
  46682. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  46683. // Methods
  46684. get: function () {
  46685. return this._sourceMesh.receiveShadows;
  46686. },
  46687. enumerable: true,
  46688. configurable: true
  46689. });
  46690. Object.defineProperty(InstancedMesh.prototype, "material", {
  46691. get: function () {
  46692. return this._sourceMesh.material;
  46693. },
  46694. enumerable: true,
  46695. configurable: true
  46696. });
  46697. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  46698. get: function () {
  46699. return this._sourceMesh.visibility;
  46700. },
  46701. enumerable: true,
  46702. configurable: true
  46703. });
  46704. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  46705. get: function () {
  46706. return this._sourceMesh.skeleton;
  46707. },
  46708. enumerable: true,
  46709. configurable: true
  46710. });
  46711. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  46712. get: function () {
  46713. return this._sourceMesh.renderingGroupId;
  46714. },
  46715. enumerable: true,
  46716. configurable: true
  46717. });
  46718. /**
  46719. * Returns the total number of vertices (integer).
  46720. */
  46721. InstancedMesh.prototype.getTotalVertices = function () {
  46722. return this._sourceMesh.getTotalVertices();
  46723. };
  46724. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  46725. get: function () {
  46726. return this._sourceMesh;
  46727. },
  46728. enumerable: true,
  46729. configurable: true
  46730. });
  46731. /**
  46732. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  46733. */
  46734. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  46735. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  46736. };
  46737. /**
  46738. * Sets the vertex data of the mesh geometry for the requested `kind`.
  46739. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  46740. * The `data` are either a numeric array either a Float32Array.
  46741. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  46742. * 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).
  46743. * Note that a new underlying VertexBuffer object is created each call.
  46744. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  46745. *
  46746. * Possible `kind` values :
  46747. * - BABYLON.VertexBuffer.PositionKind
  46748. * - BABYLON.VertexBuffer.UVKind
  46749. * - BABYLON.VertexBuffer.UV2Kind
  46750. * - BABYLON.VertexBuffer.UV3Kind
  46751. * - BABYLON.VertexBuffer.UV4Kind
  46752. * - BABYLON.VertexBuffer.UV5Kind
  46753. * - BABYLON.VertexBuffer.UV6Kind
  46754. * - BABYLON.VertexBuffer.ColorKind
  46755. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46756. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46757. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46758. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46759. *
  46760. * Returns the Mesh.
  46761. */
  46762. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  46763. if (this.sourceMesh) {
  46764. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  46765. }
  46766. return this.sourceMesh;
  46767. };
  46768. /**
  46769. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  46770. * If the mesh has no geometry, it is simply returned as it is.
  46771. * The `data` are either a numeric array either a Float32Array.
  46772. * No new underlying VertexBuffer object is created.
  46773. * 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.
  46774. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  46775. *
  46776. * Possible `kind` values :
  46777. * - BABYLON.VertexBuffer.PositionKind
  46778. * - BABYLON.VertexBuffer.UVKind
  46779. * - BABYLON.VertexBuffer.UV2Kind
  46780. * - BABYLON.VertexBuffer.UV3Kind
  46781. * - BABYLON.VertexBuffer.UV4Kind
  46782. * - BABYLON.VertexBuffer.UV5Kind
  46783. * - BABYLON.VertexBuffer.UV6Kind
  46784. * - BABYLON.VertexBuffer.ColorKind
  46785. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46786. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46787. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46788. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46789. *
  46790. * Returns the Mesh.
  46791. */
  46792. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  46793. if (this.sourceMesh) {
  46794. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  46795. }
  46796. return this.sourceMesh;
  46797. };
  46798. /**
  46799. * Sets the mesh indices.
  46800. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  46801. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  46802. * This method creates a new index buffer each call.
  46803. * Returns the Mesh.
  46804. */
  46805. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  46806. if (totalVertices === void 0) { totalVertices = null; }
  46807. if (this.sourceMesh) {
  46808. this.sourceMesh.setIndices(indices, totalVertices);
  46809. }
  46810. return this.sourceMesh;
  46811. };
  46812. /**
  46813. * Boolean : True if the mesh owns the requested kind of data.
  46814. */
  46815. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  46816. return this._sourceMesh.isVerticesDataPresent(kind);
  46817. };
  46818. /**
  46819. * Returns an array of indices (IndicesArray).
  46820. */
  46821. InstancedMesh.prototype.getIndices = function () {
  46822. return this._sourceMesh.getIndices();
  46823. };
  46824. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  46825. get: function () {
  46826. return this._sourceMesh._positions;
  46827. },
  46828. enumerable: true,
  46829. configurable: true
  46830. });
  46831. /**
  46832. * Sets a new updated BoundingInfo to the mesh.
  46833. * Returns the mesh.
  46834. */
  46835. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46836. var meshBB = this._sourceMesh.getBoundingInfo();
  46837. if (meshBB) {
  46838. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46839. }
  46840. this._updateBoundingInfo();
  46841. return this;
  46842. };
  46843. InstancedMesh.prototype._preActivate = function () {
  46844. if (this._currentLOD) {
  46845. this._currentLOD._preActivate();
  46846. }
  46847. return this;
  46848. };
  46849. InstancedMesh.prototype._activate = function (renderId) {
  46850. if (this._currentLOD) {
  46851. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46852. }
  46853. return this;
  46854. };
  46855. /**
  46856. * Returns the current associated LOD AbstractMesh.
  46857. */
  46858. InstancedMesh.prototype.getLOD = function (camera) {
  46859. if (!camera) {
  46860. return this;
  46861. }
  46862. var boundingInfo = this.getBoundingInfo();
  46863. if (!boundingInfo) {
  46864. return this;
  46865. }
  46866. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  46867. if (this._currentLOD === this.sourceMesh) {
  46868. return this;
  46869. }
  46870. return this._currentLOD;
  46871. };
  46872. InstancedMesh.prototype._syncSubMeshes = function () {
  46873. this.releaseSubMeshes();
  46874. if (this._sourceMesh.subMeshes) {
  46875. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  46876. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  46877. }
  46878. }
  46879. return this;
  46880. };
  46881. InstancedMesh.prototype._generatePointsArray = function () {
  46882. return this._sourceMesh._generatePointsArray();
  46883. };
  46884. /**
  46885. * Creates a new InstancedMesh from the current mesh.
  46886. * - name (string) : the cloned mesh name
  46887. * - newParent (optional Node) : the optional Node to parent the clone to.
  46888. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  46889. *
  46890. * Returns the clone.
  46891. */
  46892. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46893. var result = this._sourceMesh.createInstance(name);
  46894. // Deep copy
  46895. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  46896. // Bounding info
  46897. this.refreshBoundingInfo();
  46898. // Parent
  46899. if (newParent) {
  46900. result.parent = newParent;
  46901. }
  46902. if (!doNotCloneChildren) {
  46903. // Children
  46904. for (var index = 0; index < this.getScene().meshes.length; index++) {
  46905. var mesh = this.getScene().meshes[index];
  46906. if (mesh.parent === this) {
  46907. mesh.clone(mesh.name, result);
  46908. }
  46909. }
  46910. }
  46911. result.computeWorldMatrix(true);
  46912. return result;
  46913. };
  46914. /**
  46915. * Disposes the InstancedMesh.
  46916. * Returns nothing.
  46917. */
  46918. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  46919. // Remove from mesh
  46920. var index = this._sourceMesh.instances.indexOf(this);
  46921. this._sourceMesh.instances.splice(index, 1);
  46922. _super.prototype.dispose.call(this, doNotRecurse);
  46923. };
  46924. return InstancedMesh;
  46925. }(BABYLON.AbstractMesh));
  46926. BABYLON.InstancedMesh = InstancedMesh;
  46927. })(BABYLON || (BABYLON = {}));
  46928. //# sourceMappingURL=babylon.instancedMesh.js.map
  46929. var BABYLON;
  46930. (function (BABYLON) {
  46931. var LinesMesh = /** @class */ (function (_super) {
  46932. __extends(LinesMesh, _super);
  46933. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  46934. if (scene === void 0) { scene = null; }
  46935. if (parent === void 0) { parent = null; }
  46936. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  46937. _this.useVertexColor = useVertexColor;
  46938. _this.color = new BABYLON.Color3(1, 1, 1);
  46939. _this.alpha = 1;
  46940. if (source) {
  46941. _this.color = source.color.clone();
  46942. _this.alpha = source.alpha;
  46943. _this.useVertexColor = source.useVertexColor;
  46944. }
  46945. _this._intersectionThreshold = 0.1;
  46946. var options = {
  46947. attributes: [BABYLON.VertexBuffer.PositionKind],
  46948. uniforms: ["world", "viewProjection"],
  46949. needAlphaBlending: false,
  46950. };
  46951. if (!useVertexColor) {
  46952. options.uniforms.push("color");
  46953. options.needAlphaBlending = true;
  46954. }
  46955. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  46956. return _this;
  46957. }
  46958. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  46959. /**
  46960. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46961. * This margin is expressed in world space coordinates, so its value may vary.
  46962. * Default value is 0.1
  46963. * @returns the intersection Threshold value.
  46964. */
  46965. get: function () {
  46966. return this._intersectionThreshold;
  46967. },
  46968. /**
  46969. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46970. * This margin is expressed in world space coordinates, so its value may vary.
  46971. * @param value the new threshold to apply
  46972. */
  46973. set: function (value) {
  46974. if (this._intersectionThreshold === value) {
  46975. return;
  46976. }
  46977. this._intersectionThreshold = value;
  46978. if (this.geometry) {
  46979. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  46980. }
  46981. },
  46982. enumerable: true,
  46983. configurable: true
  46984. });
  46985. /**
  46986. * Returns the string "LineMesh"
  46987. */
  46988. LinesMesh.prototype.getClassName = function () {
  46989. return "LinesMesh";
  46990. };
  46991. Object.defineProperty(LinesMesh.prototype, "material", {
  46992. get: function () {
  46993. return this._colorShader;
  46994. },
  46995. set: function (value) {
  46996. // Do nothing
  46997. },
  46998. enumerable: true,
  46999. configurable: true
  47000. });
  47001. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  47002. get: function () {
  47003. return false;
  47004. },
  47005. enumerable: true,
  47006. configurable: true
  47007. });
  47008. LinesMesh.prototype.createInstance = function (name) {
  47009. throw new Error("LinesMeshes do not support createInstance.");
  47010. };
  47011. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  47012. if (!this._geometry) {
  47013. return this;
  47014. }
  47015. // VBOs
  47016. this._geometry._bind(this._colorShader.getEffect());
  47017. // Color
  47018. if (!this.useVertexColor) {
  47019. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  47020. }
  47021. return this;
  47022. };
  47023. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  47024. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  47025. return this;
  47026. }
  47027. var engine = this.getScene().getEngine();
  47028. // Draw order
  47029. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  47030. return this;
  47031. };
  47032. LinesMesh.prototype.dispose = function (doNotRecurse) {
  47033. this._colorShader.dispose();
  47034. _super.prototype.dispose.call(this, doNotRecurse);
  47035. };
  47036. /**
  47037. * Returns a new LineMesh object cloned from the current one.
  47038. */
  47039. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  47040. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  47041. };
  47042. return LinesMesh;
  47043. }(BABYLON.Mesh));
  47044. BABYLON.LinesMesh = LinesMesh;
  47045. })(BABYLON || (BABYLON = {}));
  47046. //# sourceMappingURL=babylon.linesMesh.js.map
  47047. var BABYLON;
  47048. (function (BABYLON) {
  47049. var ShaderMaterial = /** @class */ (function (_super) {
  47050. __extends(ShaderMaterial, _super);
  47051. function ShaderMaterial(name, scene, shaderPath, options) {
  47052. var _this = _super.call(this, name, scene) || this;
  47053. _this._textures = {};
  47054. _this._textureArrays = {};
  47055. _this._floats = {};
  47056. _this._floatsArrays = {};
  47057. _this._colors3 = {};
  47058. _this._colors3Arrays = {};
  47059. _this._colors4 = {};
  47060. _this._vectors2 = {};
  47061. _this._vectors3 = {};
  47062. _this._vectors4 = {};
  47063. _this._matrices = {};
  47064. _this._matrices3x3 = {};
  47065. _this._matrices2x2 = {};
  47066. _this._vectors3Arrays = {};
  47067. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  47068. _this._shaderPath = shaderPath;
  47069. options.needAlphaBlending = options.needAlphaBlending || false;
  47070. options.needAlphaTesting = options.needAlphaTesting || false;
  47071. options.attributes = options.attributes || ["position", "normal", "uv"];
  47072. options.uniforms = options.uniforms || ["worldViewProjection"];
  47073. options.uniformBuffers = options.uniformBuffers || [];
  47074. options.samplers = options.samplers || [];
  47075. options.defines = options.defines || [];
  47076. _this._options = options;
  47077. return _this;
  47078. }
  47079. ShaderMaterial.prototype.getClassName = function () {
  47080. return "ShaderMaterial";
  47081. };
  47082. ShaderMaterial.prototype.needAlphaBlending = function () {
  47083. return this._options.needAlphaBlending;
  47084. };
  47085. ShaderMaterial.prototype.needAlphaTesting = function () {
  47086. return this._options.needAlphaTesting;
  47087. };
  47088. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  47089. if (this._options.uniforms.indexOf(uniformName) === -1) {
  47090. this._options.uniforms.push(uniformName);
  47091. }
  47092. };
  47093. ShaderMaterial.prototype.setTexture = function (name, texture) {
  47094. if (this._options.samplers.indexOf(name) === -1) {
  47095. this._options.samplers.push(name);
  47096. }
  47097. this._textures[name] = texture;
  47098. return this;
  47099. };
  47100. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  47101. if (this._options.samplers.indexOf(name) === -1) {
  47102. this._options.samplers.push(name);
  47103. }
  47104. this._checkUniform(name);
  47105. this._textureArrays[name] = textures;
  47106. return this;
  47107. };
  47108. ShaderMaterial.prototype.setFloat = function (name, value) {
  47109. this._checkUniform(name);
  47110. this._floats[name] = value;
  47111. return this;
  47112. };
  47113. ShaderMaterial.prototype.setFloats = function (name, value) {
  47114. this._checkUniform(name);
  47115. this._floatsArrays[name] = value;
  47116. return this;
  47117. };
  47118. ShaderMaterial.prototype.setColor3 = function (name, value) {
  47119. this._checkUniform(name);
  47120. this._colors3[name] = value;
  47121. return this;
  47122. };
  47123. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  47124. this._checkUniform(name);
  47125. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  47126. color.toArray(arr, arr.length);
  47127. return arr;
  47128. }, []);
  47129. return this;
  47130. };
  47131. ShaderMaterial.prototype.setColor4 = function (name, value) {
  47132. this._checkUniform(name);
  47133. this._colors4[name] = value;
  47134. return this;
  47135. };
  47136. ShaderMaterial.prototype.setVector2 = function (name, value) {
  47137. this._checkUniform(name);
  47138. this._vectors2[name] = value;
  47139. return this;
  47140. };
  47141. ShaderMaterial.prototype.setVector3 = function (name, value) {
  47142. this._checkUniform(name);
  47143. this._vectors3[name] = value;
  47144. return this;
  47145. };
  47146. ShaderMaterial.prototype.setVector4 = function (name, value) {
  47147. this._checkUniform(name);
  47148. this._vectors4[name] = value;
  47149. return this;
  47150. };
  47151. ShaderMaterial.prototype.setMatrix = function (name, value) {
  47152. this._checkUniform(name);
  47153. this._matrices[name] = value;
  47154. return this;
  47155. };
  47156. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  47157. this._checkUniform(name);
  47158. this._matrices3x3[name] = value;
  47159. return this;
  47160. };
  47161. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  47162. this._checkUniform(name);
  47163. this._matrices2x2[name] = value;
  47164. return this;
  47165. };
  47166. ShaderMaterial.prototype.setArray3 = function (name, value) {
  47167. this._checkUniform(name);
  47168. this._vectors3Arrays[name] = value;
  47169. return this;
  47170. };
  47171. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  47172. if (!mesh) {
  47173. return true;
  47174. }
  47175. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  47176. return false;
  47177. }
  47178. return false;
  47179. };
  47180. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  47181. var scene = this.getScene();
  47182. var engine = scene.getEngine();
  47183. if (!this.checkReadyOnEveryCall) {
  47184. if (this._renderId === scene.getRenderId()) {
  47185. if (this._checkCache(scene, mesh, useInstances)) {
  47186. return true;
  47187. }
  47188. }
  47189. }
  47190. // Instances
  47191. var defines = [];
  47192. var attribs = [];
  47193. var fallbacks = new BABYLON.EffectFallbacks();
  47194. if (useInstances) {
  47195. defines.push("#define INSTANCES");
  47196. }
  47197. for (var index = 0; index < this._options.defines.length; index++) {
  47198. defines.push(this._options.defines[index]);
  47199. }
  47200. for (var index = 0; index < this._options.attributes.length; index++) {
  47201. attribs.push(this._options.attributes[index]);
  47202. }
  47203. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  47204. attribs.push(BABYLON.VertexBuffer.ColorKind);
  47205. defines.push("#define VERTEXCOLOR");
  47206. }
  47207. // Bones
  47208. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  47209. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47210. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47211. if (mesh.numBoneInfluencers > 4) {
  47212. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47213. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47214. }
  47215. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47216. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47217. fallbacks.addCPUSkinningFallback(0, mesh);
  47218. if (this._options.uniforms.indexOf("mBones") === -1) {
  47219. this._options.uniforms.push("mBones");
  47220. }
  47221. }
  47222. else {
  47223. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47224. }
  47225. // Textures
  47226. for (var name in this._textures) {
  47227. if (!this._textures[name].isReady()) {
  47228. return false;
  47229. }
  47230. }
  47231. // Alpha test
  47232. if (engine.getAlphaTesting()) {
  47233. defines.push("#define ALPHATEST");
  47234. }
  47235. var previousEffect = this._effect;
  47236. var join = defines.join("\n");
  47237. this._effect = engine.createEffect(this._shaderPath, {
  47238. attributes: attribs,
  47239. uniformsNames: this._options.uniforms,
  47240. uniformBuffersNames: this._options.uniformBuffers,
  47241. samplers: this._options.samplers,
  47242. defines: join,
  47243. fallbacks: fallbacks,
  47244. onCompiled: this.onCompiled,
  47245. onError: this.onError
  47246. }, engine);
  47247. if (!this._effect.isReady()) {
  47248. return false;
  47249. }
  47250. if (previousEffect !== this._effect) {
  47251. scene.resetCachedMaterial();
  47252. }
  47253. this._renderId = scene.getRenderId();
  47254. return true;
  47255. };
  47256. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  47257. var scene = this.getScene();
  47258. if (!this._effect) {
  47259. return;
  47260. }
  47261. if (this._options.uniforms.indexOf("world") !== -1) {
  47262. this._effect.setMatrix("world", world);
  47263. }
  47264. if (this._options.uniforms.indexOf("worldView") !== -1) {
  47265. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  47266. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  47267. }
  47268. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  47269. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  47270. }
  47271. };
  47272. ShaderMaterial.prototype.bind = function (world, mesh) {
  47273. // Std values
  47274. this.bindOnlyWorldMatrix(world);
  47275. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  47276. if (this._options.uniforms.indexOf("view") !== -1) {
  47277. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  47278. }
  47279. if (this._options.uniforms.indexOf("projection") !== -1) {
  47280. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  47281. }
  47282. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  47283. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  47284. }
  47285. // Bones
  47286. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  47287. var name;
  47288. // Texture
  47289. for (name in this._textures) {
  47290. this._effect.setTexture(name, this._textures[name]);
  47291. }
  47292. // Texture arrays
  47293. for (name in this._textureArrays) {
  47294. this._effect.setTextureArray(name, this._textureArrays[name]);
  47295. }
  47296. // Float
  47297. for (name in this._floats) {
  47298. this._effect.setFloat(name, this._floats[name]);
  47299. }
  47300. // Float s
  47301. for (name in this._floatsArrays) {
  47302. this._effect.setArray(name, this._floatsArrays[name]);
  47303. }
  47304. // Color3
  47305. for (name in this._colors3) {
  47306. this._effect.setColor3(name, this._colors3[name]);
  47307. }
  47308. for (name in this._colors3Arrays) {
  47309. this._effect.setArray3(name, this._colors3Arrays[name]);
  47310. }
  47311. // Color4
  47312. for (name in this._colors4) {
  47313. var color = this._colors4[name];
  47314. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  47315. }
  47316. // Vector2
  47317. for (name in this._vectors2) {
  47318. this._effect.setVector2(name, this._vectors2[name]);
  47319. }
  47320. // Vector3
  47321. for (name in this._vectors3) {
  47322. this._effect.setVector3(name, this._vectors3[name]);
  47323. }
  47324. // Vector4
  47325. for (name in this._vectors4) {
  47326. this._effect.setVector4(name, this._vectors4[name]);
  47327. }
  47328. // Matrix
  47329. for (name in this._matrices) {
  47330. this._effect.setMatrix(name, this._matrices[name]);
  47331. }
  47332. // Matrix 3x3
  47333. for (name in this._matrices3x3) {
  47334. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  47335. }
  47336. // Matrix 2x2
  47337. for (name in this._matrices2x2) {
  47338. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  47339. }
  47340. // Vector3Array
  47341. for (name in this._vectors3Arrays) {
  47342. this._effect.setArray3(name, this._vectors3Arrays[name]);
  47343. }
  47344. }
  47345. this._afterBind(mesh);
  47346. };
  47347. ShaderMaterial.prototype.getActiveTextures = function () {
  47348. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47349. for (var name in this._textures) {
  47350. activeTextures.push(this._textures[name]);
  47351. }
  47352. for (var name in this._textureArrays) {
  47353. var array = this._textureArrays[name];
  47354. for (var index = 0; index < array.length; index++) {
  47355. activeTextures.push(array[index]);
  47356. }
  47357. }
  47358. return activeTextures;
  47359. };
  47360. ShaderMaterial.prototype.hasTexture = function (texture) {
  47361. if (_super.prototype.hasTexture.call(this, texture)) {
  47362. return true;
  47363. }
  47364. for (var name in this._textures) {
  47365. if (this._textures[name] === texture) {
  47366. return true;
  47367. }
  47368. }
  47369. for (var name in this._textureArrays) {
  47370. var array = this._textureArrays[name];
  47371. for (var index = 0; index < array.length; index++) {
  47372. if (array[index] === texture) {
  47373. return true;
  47374. }
  47375. }
  47376. }
  47377. return false;
  47378. };
  47379. ShaderMaterial.prototype.clone = function (name) {
  47380. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  47381. return newShaderMaterial;
  47382. };
  47383. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  47384. if (forceDisposeTextures) {
  47385. var name;
  47386. for (name in this._textures) {
  47387. this._textures[name].dispose();
  47388. }
  47389. for (name in this._textureArrays) {
  47390. var array = this._textureArrays[name];
  47391. for (var index = 0; index < array.length; index++) {
  47392. array[index].dispose();
  47393. }
  47394. }
  47395. }
  47396. this._textures = {};
  47397. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  47398. };
  47399. ShaderMaterial.prototype.serialize = function () {
  47400. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47401. serializationObject.customType = "BABYLON.ShaderMaterial";
  47402. serializationObject.options = this._options;
  47403. serializationObject.shaderPath = this._shaderPath;
  47404. var name;
  47405. // Texture
  47406. serializationObject.textures = {};
  47407. for (name in this._textures) {
  47408. serializationObject.textures[name] = this._textures[name].serialize();
  47409. }
  47410. // Texture arrays
  47411. serializationObject.textureArrays = {};
  47412. for (name in this._textureArrays) {
  47413. serializationObject.textureArrays[name] = [];
  47414. var array = this._textureArrays[name];
  47415. for (var index = 0; index < array.length; index++) {
  47416. serializationObject.textureArrays[name].push(array[index].serialize());
  47417. }
  47418. }
  47419. // Float
  47420. serializationObject.floats = {};
  47421. for (name in this._floats) {
  47422. serializationObject.floats[name] = this._floats[name];
  47423. }
  47424. // Float s
  47425. serializationObject.FloatArrays = {};
  47426. for (name in this._floatsArrays) {
  47427. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  47428. }
  47429. // Color3
  47430. serializationObject.colors3 = {};
  47431. for (name in this._colors3) {
  47432. serializationObject.colors3[name] = this._colors3[name].asArray();
  47433. }
  47434. // Color3 array
  47435. serializationObject.colors3Arrays = {};
  47436. for (name in this._colors3Arrays) {
  47437. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  47438. }
  47439. // Color4
  47440. serializationObject.colors4 = {};
  47441. for (name in this._colors4) {
  47442. serializationObject.colors4[name] = this._colors4[name].asArray();
  47443. }
  47444. // Vector2
  47445. serializationObject.vectors2 = {};
  47446. for (name in this._vectors2) {
  47447. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  47448. }
  47449. // Vector3
  47450. serializationObject.vectors3 = {};
  47451. for (name in this._vectors3) {
  47452. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  47453. }
  47454. // Vector4
  47455. serializationObject.vectors4 = {};
  47456. for (name in this._vectors4) {
  47457. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  47458. }
  47459. // Matrix
  47460. serializationObject.matrices = {};
  47461. for (name in this._matrices) {
  47462. serializationObject.matrices[name] = this._matrices[name].asArray();
  47463. }
  47464. // Matrix 3x3
  47465. serializationObject.matrices3x3 = {};
  47466. for (name in this._matrices3x3) {
  47467. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  47468. }
  47469. // Matrix 2x2
  47470. serializationObject.matrices2x2 = {};
  47471. for (name in this._matrices2x2) {
  47472. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  47473. }
  47474. // Vector3Array
  47475. serializationObject.vectors3Arrays = {};
  47476. for (name in this._vectors3Arrays) {
  47477. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  47478. }
  47479. return serializationObject;
  47480. };
  47481. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  47482. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  47483. var name;
  47484. // Texture
  47485. for (name in source.textures) {
  47486. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  47487. }
  47488. // Texture arrays
  47489. for (name in source.textureArrays) {
  47490. var array = source.textureArrays[name];
  47491. var textureArray = new Array();
  47492. for (var index = 0; index < array.length; index++) {
  47493. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  47494. }
  47495. material.setTextureArray(name, textureArray);
  47496. }
  47497. // Float
  47498. for (name in source.floats) {
  47499. material.setFloat(name, source.floats[name]);
  47500. }
  47501. // Float s
  47502. for (name in source.floatsArrays) {
  47503. material.setFloats(name, source.floatsArrays[name]);
  47504. }
  47505. // Color3
  47506. for (name in source.colors3) {
  47507. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  47508. }
  47509. // Color3 arrays
  47510. for (name in source.colors3Arrays) {
  47511. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  47512. if (i % 3 === 0) {
  47513. arr.push([num]);
  47514. }
  47515. else {
  47516. arr[arr.length - 1].push(num);
  47517. }
  47518. return arr;
  47519. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  47520. material.setColor3Array(name, colors);
  47521. }
  47522. // Color4
  47523. for (name in source.colors4) {
  47524. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  47525. }
  47526. // Vector2
  47527. for (name in source.vectors2) {
  47528. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  47529. }
  47530. // Vector3
  47531. for (name in source.vectors3) {
  47532. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  47533. }
  47534. // Vector4
  47535. for (name in source.vectors4) {
  47536. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  47537. }
  47538. // Matrix
  47539. for (name in source.matrices) {
  47540. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  47541. }
  47542. // Matrix 3x3
  47543. for (name in source.matrices3x3) {
  47544. material.setMatrix3x3(name, source.matrices3x3[name]);
  47545. }
  47546. // Matrix 2x2
  47547. for (name in source.matrices2x2) {
  47548. material.setMatrix2x2(name, source.matrices2x2[name]);
  47549. }
  47550. // Vector3Array
  47551. for (name in source.vectors3Arrays) {
  47552. material.setArray3(name, source.vectors3Arrays[name]);
  47553. }
  47554. return material;
  47555. };
  47556. return ShaderMaterial;
  47557. }(BABYLON.Material));
  47558. BABYLON.ShaderMaterial = ShaderMaterial;
  47559. })(BABYLON || (BABYLON = {}));
  47560. //# sourceMappingURL=babylon.shaderMaterial.js.map
  47561. var BABYLON;
  47562. (function (BABYLON) {
  47563. var MeshBuilder = /** @class */ (function () {
  47564. function MeshBuilder() {
  47565. }
  47566. MeshBuilder.updateSideOrientation = function (orientation) {
  47567. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  47568. return BABYLON.Mesh.DOUBLESIDE;
  47569. }
  47570. if (orientation === undefined || orientation === null) {
  47571. return BABYLON.Mesh.FRONTSIDE;
  47572. }
  47573. return orientation;
  47574. };
  47575. /**
  47576. * Creates a box mesh.
  47577. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  47578. * The parameter `size` sets the size (float) of each box side (default 1).
  47579. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  47580. * 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).
  47581. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47582. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47583. * 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).
  47584. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47586. */
  47587. MeshBuilder.CreateBox = function (name, options, scene) {
  47588. if (scene === void 0) { scene = null; }
  47589. var box = new BABYLON.Mesh(name, scene);
  47590. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47591. box._originalBuilderSideOrientation = options.sideOrientation;
  47592. var vertexData = BABYLON.VertexData.CreateBox(options);
  47593. vertexData.applyToMesh(box, options.updatable);
  47594. return box;
  47595. };
  47596. /**
  47597. * Creates a sphere mesh.
  47598. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  47599. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  47600. * 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`).
  47601. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  47602. * 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
  47603. * 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).
  47604. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47605. * 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).
  47606. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47607. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47608. */
  47609. MeshBuilder.CreateSphere = function (name, options, scene) {
  47610. var sphere = new BABYLON.Mesh(name, scene);
  47611. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47612. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47613. var vertexData = BABYLON.VertexData.CreateSphere(options);
  47614. vertexData.applyToMesh(sphere, options.updatable);
  47615. return sphere;
  47616. };
  47617. /**
  47618. * Creates a plane polygonal mesh. By default, this is a disc.
  47619. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  47620. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  47621. * 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.
  47622. * 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
  47623. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47624. * 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).
  47625. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47626. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47627. */
  47628. MeshBuilder.CreateDisc = function (name, options, scene) {
  47629. if (scene === void 0) { scene = null; }
  47630. var disc = new BABYLON.Mesh(name, scene);
  47631. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47632. disc._originalBuilderSideOrientation = options.sideOrientation;
  47633. var vertexData = BABYLON.VertexData.CreateDisc(options);
  47634. vertexData.applyToMesh(disc, options.updatable);
  47635. return disc;
  47636. };
  47637. /**
  47638. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  47639. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  47640. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  47641. * 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`).
  47642. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  47643. * 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.
  47644. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47645. * 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).
  47646. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47648. */
  47649. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  47650. var sphere = new BABYLON.Mesh(name, scene);
  47651. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47652. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47653. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  47654. vertexData.applyToMesh(sphere, options.updatable);
  47655. return sphere;
  47656. };
  47657. ;
  47658. /**
  47659. * Creates a ribbon mesh.
  47660. * 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.
  47661. *
  47662. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  47663. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  47664. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  47665. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  47666. * 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.
  47667. * 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.
  47668. * 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
  47669. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47670. * 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).
  47671. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47672. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47673. * 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.
  47674. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  47675. * 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
  47676. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  47677. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  47678. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47679. */
  47680. MeshBuilder.CreateRibbon = function (name, options, scene) {
  47681. if (scene === void 0) { scene = null; }
  47682. var pathArray = options.pathArray;
  47683. var closeArray = options.closeArray;
  47684. var closePath = options.closePath;
  47685. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47686. var instance = options.instance;
  47687. var updatable = options.updatable;
  47688. if (instance) {
  47689. // positionFunction : ribbon case
  47690. // only pathArray and sideOrientation parameters are taken into account for positions update
  47691. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  47692. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  47693. var positionFunction = function (positions) {
  47694. var minlg = pathArray[0].length;
  47695. var i = 0;
  47696. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  47697. for (var si = 1; si <= ns; si++) {
  47698. for (var p = 0; p < pathArray.length; p++) {
  47699. var path = pathArray[p];
  47700. var l = path.length;
  47701. minlg = (minlg < l) ? minlg : l;
  47702. var j = 0;
  47703. while (j < minlg) {
  47704. positions[i] = path[j].x;
  47705. positions[i + 1] = path[j].y;
  47706. positions[i + 2] = path[j].z;
  47707. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  47708. BABYLON.Tmp.Vector3[0].x = path[j].x;
  47709. }
  47710. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  47711. BABYLON.Tmp.Vector3[1].x = path[j].x;
  47712. }
  47713. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  47714. BABYLON.Tmp.Vector3[0].y = path[j].y;
  47715. }
  47716. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  47717. BABYLON.Tmp.Vector3[1].y = path[j].y;
  47718. }
  47719. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  47720. BABYLON.Tmp.Vector3[0].z = path[j].z;
  47721. }
  47722. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  47723. BABYLON.Tmp.Vector3[1].z = path[j].z;
  47724. }
  47725. j++;
  47726. i += 3;
  47727. }
  47728. if (instance._closePath) {
  47729. positions[i] = path[0].x;
  47730. positions[i + 1] = path[0].y;
  47731. positions[i + 2] = path[0].z;
  47732. i += 3;
  47733. }
  47734. }
  47735. }
  47736. };
  47737. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47738. positionFunction(positions);
  47739. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  47740. instance._boundingInfo.update(instance._worldMatrix);
  47741. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  47742. if (options.colors) {
  47743. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47744. for (var c = 0; c < options.colors.length; c++) {
  47745. colors[c * 4] = options.colors[c].r;
  47746. colors[c * 4 + 1] = options.colors[c].g;
  47747. colors[c * 4 + 2] = options.colors[c].b;
  47748. colors[c * 4 + 3] = options.colors[c].a;
  47749. }
  47750. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  47751. }
  47752. if (options.uvs) {
  47753. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47754. for (var i = 0; i < options.uvs.length; i++) {
  47755. uvs[i * 2] = options.uvs[i].x;
  47756. uvs[i * 2 + 1] = options.uvs[i].y;
  47757. }
  47758. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  47759. }
  47760. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  47761. var indices = instance.getIndices();
  47762. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47763. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  47764. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  47765. if (instance._closePath) {
  47766. var indexFirst = 0;
  47767. var indexLast = 0;
  47768. for (var p = 0; p < pathArray.length; p++) {
  47769. indexFirst = instance._idx[p] * 3;
  47770. if (p + 1 < pathArray.length) {
  47771. indexLast = (instance._idx[p + 1] - 1) * 3;
  47772. }
  47773. else {
  47774. indexLast = normals.length - 3;
  47775. }
  47776. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  47777. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  47778. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  47779. normals[indexLast] = normals[indexFirst];
  47780. normals[indexLast + 1] = normals[indexFirst + 1];
  47781. normals[indexLast + 2] = normals[indexFirst + 2];
  47782. }
  47783. }
  47784. if (!(instance.areNormalsFrozen)) {
  47785. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  47786. }
  47787. }
  47788. return instance;
  47789. }
  47790. else {
  47791. var ribbon = new BABYLON.Mesh(name, scene);
  47792. ribbon._originalBuilderSideOrientation = sideOrientation;
  47793. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  47794. if (closePath) {
  47795. ribbon._idx = vertexData._idx;
  47796. }
  47797. ribbon._closePath = closePath;
  47798. ribbon._closeArray = closeArray;
  47799. vertexData.applyToMesh(ribbon, updatable);
  47800. return ribbon;
  47801. }
  47802. };
  47803. /**
  47804. * Creates a cylinder or a cone mesh.
  47805. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  47806. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  47807. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  47808. * 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.
  47809. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  47810. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  47811. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  47812. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  47813. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  47814. * 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).
  47815. * 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
  47816. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  47817. * 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
  47818. * 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.
  47819. * If `enclose` is false, a ring surface is one element.
  47820. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  47821. * 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
  47822. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47823. * 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).
  47824. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47825. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47826. */
  47827. MeshBuilder.CreateCylinder = function (name, options, scene) {
  47828. var cylinder = new BABYLON.Mesh(name, scene);
  47829. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47830. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  47831. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  47832. vertexData.applyToMesh(cylinder, options.updatable);
  47833. return cylinder;
  47834. };
  47835. /**
  47836. * Creates a torus mesh.
  47837. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  47838. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  47839. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  47840. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  47841. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47842. * 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).
  47843. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47844. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47845. */
  47846. MeshBuilder.CreateTorus = function (name, options, scene) {
  47847. var torus = new BABYLON.Mesh(name, scene);
  47848. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47849. torus._originalBuilderSideOrientation = options.sideOrientation;
  47850. var vertexData = BABYLON.VertexData.CreateTorus(options);
  47851. vertexData.applyToMesh(torus, options.updatable);
  47852. return torus;
  47853. };
  47854. /**
  47855. * Creates a torus knot mesh.
  47856. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  47857. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  47858. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  47859. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  47860. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  47861. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47862. * 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).
  47863. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47864. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47865. */
  47866. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  47867. var torusKnot = new BABYLON.Mesh(name, scene);
  47868. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47869. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  47870. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  47871. vertexData.applyToMesh(torusKnot, options.updatable);
  47872. return torusKnot;
  47873. };
  47874. /**
  47875. * Creates a line system mesh.
  47876. * A line system is a pool of many lines gathered in a single mesh.
  47877. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  47878. * 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.
  47879. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  47880. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  47881. * 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
  47882. * 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
  47883. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  47884. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47885. */
  47886. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  47887. var instance = options.instance;
  47888. var lines = options.lines;
  47889. if (instance) {
  47890. var positionFunction = function (positions) {
  47891. var i = 0;
  47892. for (var l = 0; l < lines.length; l++) {
  47893. var points = lines[l];
  47894. for (var p = 0; p < points.length; p++) {
  47895. positions[i] = points[p].x;
  47896. positions[i + 1] = points[p].y;
  47897. positions[i + 2] = points[p].z;
  47898. i += 3;
  47899. }
  47900. }
  47901. };
  47902. instance.updateMeshPositions(positionFunction, false);
  47903. return instance;
  47904. }
  47905. // line system creation
  47906. var lineSystem = new BABYLON.LinesMesh(name, scene);
  47907. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  47908. vertexData.applyToMesh(lineSystem, options.updatable);
  47909. return lineSystem;
  47910. };
  47911. /**
  47912. * Creates a line mesh.
  47913. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  47914. * 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.
  47915. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47916. * The parameter `points` is an array successive Vector3.
  47917. * 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
  47918. * When updating an instance, remember that only point positions can change, not the number of points.
  47919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47920. */
  47921. MeshBuilder.CreateLines = function (name, options, scene) {
  47922. if (scene === void 0) { scene = null; }
  47923. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  47924. return lines;
  47925. };
  47926. /**
  47927. * Creates a dashed line mesh.
  47928. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  47929. * 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.
  47930. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47931. * The parameter `points` is an array successive Vector3.
  47932. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  47933. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  47934. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  47935. * 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
  47936. * When updating an instance, remember that only point positions can change, not the number of points.
  47937. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47938. */
  47939. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  47940. if (scene === void 0) { scene = null; }
  47941. var points = options.points;
  47942. var instance = options.instance;
  47943. var gapSize = options.gapSize || 1;
  47944. var dashSize = options.dashSize || 3;
  47945. if (instance) {
  47946. var positionFunction = function (positions) {
  47947. var curvect = BABYLON.Vector3.Zero();
  47948. var nbSeg = positions.length / 6;
  47949. var lg = 0;
  47950. var nb = 0;
  47951. var shft = 0;
  47952. var dashshft = 0;
  47953. var curshft = 0;
  47954. var p = 0;
  47955. var i = 0;
  47956. var j = 0;
  47957. for (i = 0; i < points.length - 1; i++) {
  47958. points[i + 1].subtractToRef(points[i], curvect);
  47959. lg += curvect.length();
  47960. }
  47961. shft = lg / nbSeg;
  47962. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  47963. for (i = 0; i < points.length - 1; i++) {
  47964. points[i + 1].subtractToRef(points[i], curvect);
  47965. nb = Math.floor(curvect.length() / shft);
  47966. curvect.normalize();
  47967. j = 0;
  47968. while (j < nb && p < positions.length) {
  47969. curshft = shft * j;
  47970. positions[p] = points[i].x + curshft * curvect.x;
  47971. positions[p + 1] = points[i].y + curshft * curvect.y;
  47972. positions[p + 2] = points[i].z + curshft * curvect.z;
  47973. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  47974. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  47975. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  47976. p += 6;
  47977. j++;
  47978. }
  47979. }
  47980. while (p < positions.length) {
  47981. positions[p] = points[i].x;
  47982. positions[p + 1] = points[i].y;
  47983. positions[p + 2] = points[i].z;
  47984. p += 3;
  47985. }
  47986. };
  47987. instance.updateMeshPositions(positionFunction, false);
  47988. return instance;
  47989. }
  47990. // dashed lines creation
  47991. var dashedLines = new BABYLON.LinesMesh(name, scene);
  47992. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  47993. vertexData.applyToMesh(dashedLines, options.updatable);
  47994. dashedLines.dashSize = dashSize;
  47995. dashedLines.gapSize = gapSize;
  47996. return dashedLines;
  47997. };
  47998. /**
  47999. * Creates an extruded shape mesh.
  48000. * 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.
  48001. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  48002. *
  48003. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48004. * 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
  48005. * extruded along the Z axis.
  48006. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48007. * 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.
  48008. * The parameter `scale` (float, default 1) is the value to scale the shape.
  48009. * 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
  48010. * 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
  48011. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48012. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48013. * 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).
  48014. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48015. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48016. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48017. */
  48018. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  48019. if (scene === void 0) { scene = null; }
  48020. var path = options.path;
  48021. var shape = options.shape;
  48022. var scale = options.scale || 1;
  48023. var rotation = options.rotation || 0;
  48024. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48025. var updatable = options.updatable;
  48026. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48027. var instance = options.instance || null;
  48028. var invertUV = options.invertUV || false;
  48029. 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);
  48030. };
  48031. /**
  48032. * Creates an custom extruded shape mesh.
  48033. * 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.
  48034. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  48035. *
  48036. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  48037. * 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
  48038. * extruded along the Z axis.
  48039. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  48040. * 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
  48041. * and the distance of this point from the begining of the path :
  48042. * ```javascript
  48043. * var rotationFunction = function(i, distance) {
  48044. * // do things
  48045. * return rotationValue; }
  48046. * ```
  48047. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  48048. * 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
  48049. * and the distance of this point from the begining of the path :
  48050. * ```javascript
  48051. * var scaleFunction = function(i, distance) {
  48052. * // do things
  48053. * return scaleValue;}
  48054. * ```
  48055. * It must returns a float value that will be the scale value applied to the shape on each path point.
  48056. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  48057. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  48058. * 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
  48059. * 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
  48060. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  48061. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48062. * 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).
  48063. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48064. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48065. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48066. */
  48067. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  48068. var path = options.path;
  48069. var shape = options.shape;
  48070. var scaleFunction = options.scaleFunction || (function () { return 1; });
  48071. var rotationFunction = options.rotationFunction || (function () { return 0; });
  48072. var ribbonCloseArray = options.ribbonCloseArray || false;
  48073. var ribbonClosePath = options.ribbonClosePath || false;
  48074. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  48075. var updatable = options.updatable;
  48076. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48077. var instance = options.instance;
  48078. var invertUV = options.invertUV || false;
  48079. 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);
  48080. };
  48081. /**
  48082. * Creates lathe mesh.
  48083. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  48084. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  48085. *
  48086. * 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
  48087. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  48088. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  48089. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  48090. * 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.
  48091. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  48092. * 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
  48093. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48094. * 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).
  48095. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48096. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48097. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48098. */
  48099. MeshBuilder.CreateLathe = function (name, options, scene) {
  48100. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  48101. var closed = (options.closed === undefined) ? true : options.closed;
  48102. var shape = options.shape;
  48103. var radius = options.radius || 1;
  48104. var tessellation = options.tessellation || 64;
  48105. var updatable = options.updatable;
  48106. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48107. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48108. var pi2 = Math.PI * 2;
  48109. var paths = new Array();
  48110. var invertUV = options.invertUV || false;
  48111. var i = 0;
  48112. var p = 0;
  48113. var step = pi2 / tessellation * arc;
  48114. var rotated;
  48115. var path = new Array();
  48116. ;
  48117. for (i = 0; i <= tessellation; i++) {
  48118. var path = [];
  48119. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  48120. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  48121. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  48122. }
  48123. for (p = 0; p < shape.length; p++) {
  48124. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  48125. path.push(rotated);
  48126. }
  48127. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  48128. 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));
  48129. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  48130. }
  48131. paths.push(path);
  48132. }
  48133. // lathe ribbon
  48134. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48135. return lathe;
  48136. };
  48137. /**
  48138. * Creates a plane mesh.
  48139. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48140. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  48141. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  48142. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  48143. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48144. * 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).
  48145. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48146. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48147. */
  48148. MeshBuilder.CreatePlane = function (name, options, scene) {
  48149. var plane = new BABYLON.Mesh(name, scene);
  48150. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48151. plane._originalBuilderSideOrientation = options.sideOrientation;
  48152. var vertexData = BABYLON.VertexData.CreatePlane(options);
  48153. vertexData.applyToMesh(plane, options.updatable);
  48154. if (options.sourcePlane) {
  48155. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  48156. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  48157. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  48158. plane.rotate(vectorProduct, product);
  48159. }
  48160. return plane;
  48161. };
  48162. /**
  48163. * Creates a ground mesh.
  48164. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  48165. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  48166. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  48167. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48168. */
  48169. MeshBuilder.CreateGround = function (name, options, scene) {
  48170. var ground = new BABYLON.GroundMesh(name, scene);
  48171. ground._setReady(false);
  48172. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  48173. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  48174. ground._width = options.width || 1;
  48175. ground._height = options.height || 1;
  48176. ground._maxX = ground._width / 2;
  48177. ground._maxZ = ground._height / 2;
  48178. ground._minX = -ground._maxX;
  48179. ground._minZ = -ground._maxZ;
  48180. var vertexData = BABYLON.VertexData.CreateGround(options);
  48181. vertexData.applyToMesh(ground, options.updatable);
  48182. ground._setReady(true);
  48183. return ground;
  48184. };
  48185. /**
  48186. * Creates a tiled ground mesh.
  48187. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  48188. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  48189. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  48190. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  48191. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  48192. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  48193. * numbers of subdivisions on the ground width and height of each tile.
  48194. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48195. */
  48196. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  48197. var tiledGround = new BABYLON.Mesh(name, scene);
  48198. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  48199. vertexData.applyToMesh(tiledGround, options.updatable);
  48200. return tiledGround;
  48201. };
  48202. /**
  48203. * Creates a ground mesh from a height map.
  48204. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  48205. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  48206. * The parameter `url` sets the URL of the height map image resource.
  48207. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  48208. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  48209. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  48210. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  48211. * 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.
  48212. * 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).
  48213. * This function is passed the newly built mesh :
  48214. * ```javascript
  48215. * function(mesh) { // do things
  48216. * return; }
  48217. * ```
  48218. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48219. */
  48220. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  48221. var width = options.width || 10.0;
  48222. var height = options.height || 10.0;
  48223. var subdivisions = options.subdivisions || 1 | 0;
  48224. var minHeight = options.minHeight || 0.0;
  48225. var maxHeight = options.maxHeight || 1.0;
  48226. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  48227. var updatable = options.updatable;
  48228. var onReady = options.onReady;
  48229. var ground = new BABYLON.GroundMesh(name, scene);
  48230. ground._subdivisionsX = subdivisions;
  48231. ground._subdivisionsY = subdivisions;
  48232. ground._width = width;
  48233. ground._height = height;
  48234. ground._maxX = ground._width / 2.0;
  48235. ground._maxZ = ground._height / 2.0;
  48236. ground._minX = -ground._maxX;
  48237. ground._minZ = -ground._maxZ;
  48238. ground._setReady(false);
  48239. var onload = function (img) {
  48240. // Getting height map data
  48241. var canvas = document.createElement("canvas");
  48242. var context = canvas.getContext("2d");
  48243. if (!context) {
  48244. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  48245. }
  48246. var bufferWidth = img.width;
  48247. var bufferHeight = img.height;
  48248. canvas.width = bufferWidth;
  48249. canvas.height = bufferHeight;
  48250. context.drawImage(img, 0, 0);
  48251. // Create VertexData from map data
  48252. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  48253. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  48254. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  48255. width: width, height: height,
  48256. subdivisions: subdivisions,
  48257. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  48258. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  48259. });
  48260. vertexData.applyToMesh(ground, updatable);
  48261. ground._setReady(true);
  48262. //execute ready callback, if set
  48263. if (onReady) {
  48264. onReady(ground);
  48265. }
  48266. };
  48267. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  48268. return ground;
  48269. };
  48270. /**
  48271. * Creates a polygon mesh.
  48272. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  48273. * 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.
  48274. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48275. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48276. * 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).
  48277. * Remember you can only change the shape positions, not their number when updating a polygon.
  48278. */
  48279. MeshBuilder.CreatePolygon = function (name, options, scene) {
  48280. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48281. var shape = options.shape;
  48282. var holes = options.holes || [];
  48283. var depth = options.depth || 0;
  48284. var contours = [];
  48285. var hole = [];
  48286. for (var i = 0; i < shape.length; i++) {
  48287. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  48288. }
  48289. var epsilon = 0.00000001;
  48290. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  48291. contours.pop();
  48292. }
  48293. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  48294. for (var hNb = 0; hNb < holes.length; hNb++) {
  48295. hole = [];
  48296. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  48297. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  48298. }
  48299. polygonTriangulation.addHole(hole);
  48300. }
  48301. var polygon = polygonTriangulation.build(options.updatable, depth);
  48302. polygon._originalBuilderSideOrientation = options.sideOrientation;
  48303. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  48304. vertexData.applyToMesh(polygon, options.updatable);
  48305. return polygon;
  48306. };
  48307. ;
  48308. /**
  48309. * Creates an extruded polygon mesh, with depth in the Y direction.
  48310. * 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).
  48311. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  48312. */
  48313. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  48314. return MeshBuilder.CreatePolygon(name, options, scene);
  48315. };
  48316. ;
  48317. /**
  48318. * Creates a tube mesh.
  48319. * 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.
  48320. *
  48321. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  48322. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  48323. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  48324. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  48325. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  48326. * 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.
  48327. * It must return a radius value (positive float) :
  48328. * ```javascript
  48329. * var radiusFunction = function(i, distance) {
  48330. * // do things
  48331. * return radius; }
  48332. * ```
  48333. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  48334. * 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
  48335. * 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
  48336. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48337. * 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).
  48338. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48339. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48341. */
  48342. MeshBuilder.CreateTube = function (name, options, scene) {
  48343. var path = options.path;
  48344. var instance = options.instance;
  48345. var radius = 1.0;
  48346. if (instance) {
  48347. radius = instance.radius;
  48348. }
  48349. if (options.radius !== undefined) {
  48350. radius = options.radius;
  48351. }
  48352. ;
  48353. var tessellation = options.tessellation || 64 | 0;
  48354. var radiusFunction = options.radiusFunction || null;
  48355. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  48356. var invertUV = options.invertUV || false;
  48357. var updatable = options.updatable;
  48358. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48359. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  48360. // tube geometry
  48361. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  48362. var tangents = path3D.getTangents();
  48363. var normals = path3D.getNormals();
  48364. var distances = path3D.getDistances();
  48365. var pi2 = Math.PI * 2;
  48366. var step = pi2 / tessellation * arc;
  48367. var returnRadius = function () { return radius; };
  48368. var radiusFunctionFinal = radiusFunction || returnRadius;
  48369. var circlePath;
  48370. var rad;
  48371. var normal;
  48372. var rotated;
  48373. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48374. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48375. for (var i = 0; i < path.length; i++) {
  48376. rad = radiusFunctionFinal(i, distances[i]); // current radius
  48377. circlePath = Array(); // current circle array
  48378. normal = normals[i]; // current normal
  48379. for (var t = 0; t < tessellation; t++) {
  48380. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  48381. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  48382. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  48383. rotated.scaleInPlace(rad).addInPlace(path[i]);
  48384. circlePath[t] = rotated;
  48385. }
  48386. circlePaths[index] = circlePath;
  48387. index++;
  48388. }
  48389. // cap
  48390. var capPath = function (nbPoints, pathIndex) {
  48391. var pointCap = Array();
  48392. for (var i = 0; i < nbPoints; i++) {
  48393. pointCap.push(path[pathIndex]);
  48394. }
  48395. return pointCap;
  48396. };
  48397. switch (cap) {
  48398. case BABYLON.Mesh.NO_CAP:
  48399. break;
  48400. case BABYLON.Mesh.CAP_START:
  48401. circlePaths[0] = capPath(tessellation, 0);
  48402. circlePaths[1] = circlePaths[2].slice(0);
  48403. break;
  48404. case BABYLON.Mesh.CAP_END:
  48405. circlePaths[index] = circlePaths[index - 1].slice(0);
  48406. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48407. break;
  48408. case BABYLON.Mesh.CAP_ALL:
  48409. circlePaths[0] = capPath(tessellation, 0);
  48410. circlePaths[1] = circlePaths[2].slice(0);
  48411. circlePaths[index] = circlePaths[index - 1].slice(0);
  48412. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  48413. break;
  48414. default:
  48415. break;
  48416. }
  48417. return circlePaths;
  48418. };
  48419. var path3D;
  48420. var pathArray;
  48421. if (instance) {
  48422. var arc = options.arc || instance.arc;
  48423. path3D = (instance.path3D).update(path);
  48424. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  48425. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  48426. instance.path3D = path3D;
  48427. instance.pathArray = pathArray;
  48428. instance.arc = arc;
  48429. instance.radius = radius;
  48430. return instance;
  48431. }
  48432. // tube creation
  48433. path3D = new BABYLON.Path3D(path);
  48434. var newPathArray = new Array();
  48435. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48436. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  48437. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  48438. tube.pathArray = pathArray;
  48439. tube.path3D = path3D;
  48440. tube.tessellation = tessellation;
  48441. tube.cap = cap;
  48442. tube.arc = options.arc;
  48443. tube.radius = radius;
  48444. return tube;
  48445. };
  48446. /**
  48447. * Creates a polyhedron mesh.
  48448. *
  48449. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  48450. * 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
  48451. * to choose the wanted type.
  48452. * The parameter `size` (positive float, default 1) sets the polygon size.
  48453. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  48454. * 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`.
  48455. * 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
  48456. * 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)`).
  48457. * 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
  48458. * 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.
  48459. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48460. * 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).
  48461. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48462. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48463. */
  48464. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  48465. var polyhedron = new BABYLON.Mesh(name, scene);
  48466. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48467. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  48468. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  48469. vertexData.applyToMesh(polyhedron, options.updatable);
  48470. return polyhedron;
  48471. };
  48472. /**
  48473. * Creates a decal mesh.
  48474. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  48475. * 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.
  48476. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  48477. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  48478. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  48479. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  48480. */
  48481. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  48482. var indices = sourceMesh.getIndices();
  48483. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48484. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48485. var position = options.position || BABYLON.Vector3.Zero();
  48486. var normal = options.normal || BABYLON.Vector3.Up();
  48487. var size = options.size || BABYLON.Vector3.One();
  48488. var angle = options.angle || 0;
  48489. // Getting correct rotation
  48490. if (!normal) {
  48491. var target = new BABYLON.Vector3(0, 0, 1);
  48492. var camera = sourceMesh.getScene().activeCamera;
  48493. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  48494. normal = camera.globalPosition.subtract(cameraWorldTarget);
  48495. }
  48496. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  48497. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  48498. var pitch = Math.atan2(normal.y, len);
  48499. // Matrix
  48500. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  48501. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  48502. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  48503. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  48504. var vertexData = new BABYLON.VertexData();
  48505. vertexData.indices = [];
  48506. vertexData.positions = [];
  48507. vertexData.normals = [];
  48508. vertexData.uvs = [];
  48509. var currentVertexDataIndex = 0;
  48510. var extractDecalVector3 = function (indexId) {
  48511. var result = new BABYLON.PositionNormalVertex();
  48512. if (!indices || !positions || !normals) {
  48513. return result;
  48514. }
  48515. var vertexId = indices[indexId];
  48516. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  48517. // Send vector to decal local world
  48518. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  48519. // Get normal
  48520. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  48521. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  48522. return result;
  48523. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  48524. var clip = function (vertices, axis) {
  48525. if (vertices.length === 0) {
  48526. return vertices;
  48527. }
  48528. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  48529. var clipVertices = function (v0, v1) {
  48530. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  48531. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  48532. };
  48533. var result = new Array();
  48534. for (var index = 0; index < vertices.length; index += 3) {
  48535. var v1Out;
  48536. var v2Out;
  48537. var v3Out;
  48538. var total = 0;
  48539. var nV1 = null;
  48540. var nV2 = null;
  48541. var nV3 = null;
  48542. var nV4 = null;
  48543. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  48544. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  48545. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  48546. v1Out = d1 > 0;
  48547. v2Out = d2 > 0;
  48548. v3Out = d3 > 0;
  48549. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  48550. switch (total) {
  48551. case 0:
  48552. result.push(vertices[index]);
  48553. result.push(vertices[index + 1]);
  48554. result.push(vertices[index + 2]);
  48555. break;
  48556. case 1:
  48557. if (v1Out) {
  48558. nV1 = vertices[index + 1];
  48559. nV2 = vertices[index + 2];
  48560. nV3 = clipVertices(vertices[index], nV1);
  48561. nV4 = clipVertices(vertices[index], nV2);
  48562. }
  48563. if (v2Out) {
  48564. nV1 = vertices[index];
  48565. nV2 = vertices[index + 2];
  48566. nV3 = clipVertices(vertices[index + 1], nV1);
  48567. nV4 = clipVertices(vertices[index + 1], nV2);
  48568. result.push(nV3);
  48569. result.push(nV2.clone());
  48570. result.push(nV1.clone());
  48571. result.push(nV2.clone());
  48572. result.push(nV3.clone());
  48573. result.push(nV4);
  48574. break;
  48575. }
  48576. if (v3Out) {
  48577. nV1 = vertices[index];
  48578. nV2 = vertices[index + 1];
  48579. nV3 = clipVertices(vertices[index + 2], nV1);
  48580. nV4 = clipVertices(vertices[index + 2], nV2);
  48581. }
  48582. if (nV1 && nV2 && nV3 && nV4) {
  48583. result.push(nV1.clone());
  48584. result.push(nV2.clone());
  48585. result.push(nV3);
  48586. result.push(nV4);
  48587. result.push(nV3.clone());
  48588. result.push(nV2.clone());
  48589. }
  48590. break;
  48591. case 2:
  48592. if (!v1Out) {
  48593. nV1 = vertices[index].clone();
  48594. nV2 = clipVertices(nV1, vertices[index + 1]);
  48595. nV3 = clipVertices(nV1, vertices[index + 2]);
  48596. result.push(nV1);
  48597. result.push(nV2);
  48598. result.push(nV3);
  48599. }
  48600. if (!v2Out) {
  48601. nV1 = vertices[index + 1].clone();
  48602. nV2 = clipVertices(nV1, vertices[index + 2]);
  48603. nV3 = clipVertices(nV1, vertices[index]);
  48604. result.push(nV1);
  48605. result.push(nV2);
  48606. result.push(nV3);
  48607. }
  48608. if (!v3Out) {
  48609. nV1 = vertices[index + 2].clone();
  48610. nV2 = clipVertices(nV1, vertices[index]);
  48611. nV3 = clipVertices(nV1, vertices[index + 1]);
  48612. result.push(nV1);
  48613. result.push(nV2);
  48614. result.push(nV3);
  48615. }
  48616. break;
  48617. case 3:
  48618. break;
  48619. }
  48620. }
  48621. return result;
  48622. };
  48623. for (var index = 0; index < indices.length; index += 3) {
  48624. var faceVertices = new Array();
  48625. faceVertices.push(extractDecalVector3(index));
  48626. faceVertices.push(extractDecalVector3(index + 1));
  48627. faceVertices.push(extractDecalVector3(index + 2));
  48628. // Clip
  48629. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  48630. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  48631. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  48632. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  48633. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  48634. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  48635. if (faceVertices.length === 0) {
  48636. continue;
  48637. }
  48638. // Add UVs and get back to world
  48639. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  48640. var vertex = faceVertices[vIndex];
  48641. //TODO check for Int32Array | Uint32Array | Uint16Array
  48642. vertexData.indices.push(currentVertexDataIndex);
  48643. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  48644. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  48645. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  48646. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  48647. currentVertexDataIndex++;
  48648. }
  48649. }
  48650. // Return mesh
  48651. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  48652. vertexData.applyToMesh(decal);
  48653. decal.position = position.clone();
  48654. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  48655. return decal;
  48656. };
  48657. // Privates
  48658. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  48659. // extrusion geometry
  48660. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  48661. var tangents = path3D.getTangents();
  48662. var normals = path3D.getNormals();
  48663. var binormals = path3D.getBinormals();
  48664. var distances = path3D.getDistances();
  48665. var angle = 0;
  48666. var returnScale = function () { return scale !== null ? scale : 1; };
  48667. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  48668. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  48669. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  48670. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48671. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48672. for (var i = 0; i < curve.length; i++) {
  48673. var shapePath = new Array();
  48674. var angleStep = rotate(i, distances[i]);
  48675. var scaleRatio = scl(i, distances[i]);
  48676. for (var p = 0; p < shape.length; p++) {
  48677. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  48678. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  48679. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  48680. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  48681. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  48682. shapePath[p] = rotated;
  48683. }
  48684. shapePaths[index] = shapePath;
  48685. angle += angleStep;
  48686. index++;
  48687. }
  48688. // cap
  48689. var capPath = function (shapePath) {
  48690. var pointCap = Array();
  48691. var barycenter = BABYLON.Vector3.Zero();
  48692. var i;
  48693. for (i = 0; i < shapePath.length; i++) {
  48694. barycenter.addInPlace(shapePath[i]);
  48695. }
  48696. barycenter.scaleInPlace(1.0 / shapePath.length);
  48697. for (i = 0; i < shapePath.length; i++) {
  48698. pointCap.push(barycenter);
  48699. }
  48700. return pointCap;
  48701. };
  48702. switch (cap) {
  48703. case BABYLON.Mesh.NO_CAP:
  48704. break;
  48705. case BABYLON.Mesh.CAP_START:
  48706. shapePaths[0] = capPath(shapePaths[2]);
  48707. shapePaths[1] = shapePaths[2];
  48708. break;
  48709. case BABYLON.Mesh.CAP_END:
  48710. shapePaths[index] = shapePaths[index - 1];
  48711. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48712. break;
  48713. case BABYLON.Mesh.CAP_ALL:
  48714. shapePaths[0] = capPath(shapePaths[2]);
  48715. shapePaths[1] = shapePaths[2];
  48716. shapePaths[index] = shapePaths[index - 1];
  48717. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48718. break;
  48719. default:
  48720. break;
  48721. }
  48722. return shapePaths;
  48723. };
  48724. var path3D;
  48725. var pathArray;
  48726. if (instance) {
  48727. path3D = (instance.path3D).update(curve);
  48728. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  48729. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  48730. return instance;
  48731. }
  48732. // extruded shape creation
  48733. path3D = new BABYLON.Path3D(curve);
  48734. var newShapePaths = new Array();
  48735. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48736. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  48737. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  48738. extrudedGeneric.pathArray = pathArray;
  48739. extrudedGeneric.path3D = path3D;
  48740. extrudedGeneric.cap = cap;
  48741. return extrudedGeneric;
  48742. };
  48743. return MeshBuilder;
  48744. }());
  48745. BABYLON.MeshBuilder = MeshBuilder;
  48746. })(BABYLON || (BABYLON = {}));
  48747. //# sourceMappingURL=babylon.meshBuilder.js.map
  48748. var BABYLON;
  48749. (function (BABYLON) {
  48750. var AudioEngine = /** @class */ (function () {
  48751. function AudioEngine() {
  48752. this._audioContext = null;
  48753. this._audioContextInitialized = false;
  48754. this.canUseWebAudio = false;
  48755. this.WarnedWebAudioUnsupported = false;
  48756. this.unlocked = false;
  48757. this.isMP3supported = false;
  48758. this.isOGGsupported = false;
  48759. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  48760. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  48761. this.canUseWebAudio = true;
  48762. }
  48763. var audioElem = document.createElement('audio');
  48764. try {
  48765. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  48766. this.isMP3supported = true;
  48767. }
  48768. }
  48769. catch (e) {
  48770. // protect error during capability check.
  48771. }
  48772. try {
  48773. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  48774. this.isOGGsupported = true;
  48775. }
  48776. }
  48777. catch (e) {
  48778. // protect error during capability check.
  48779. }
  48780. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  48781. this._unlockiOSaudio();
  48782. }
  48783. else {
  48784. this.unlocked = true;
  48785. }
  48786. }
  48787. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  48788. get: function () {
  48789. if (!this._audioContextInitialized) {
  48790. this._initializeAudioContext();
  48791. }
  48792. return this._audioContext;
  48793. },
  48794. enumerable: true,
  48795. configurable: true
  48796. });
  48797. AudioEngine.prototype._unlockiOSaudio = function () {
  48798. var _this = this;
  48799. var unlockaudio = function () {
  48800. if (!_this.audioContext) {
  48801. return;
  48802. }
  48803. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  48804. var source = _this.audioContext.createBufferSource();
  48805. source.buffer = buffer;
  48806. source.connect(_this.audioContext.destination);
  48807. source.start(0);
  48808. setTimeout(function () {
  48809. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  48810. _this.unlocked = true;
  48811. window.removeEventListener('touchend', unlockaudio, false);
  48812. if (_this.onAudioUnlocked) {
  48813. _this.onAudioUnlocked();
  48814. }
  48815. }
  48816. }, 0);
  48817. };
  48818. window.addEventListener('touchend', unlockaudio, false);
  48819. };
  48820. AudioEngine.prototype._initializeAudioContext = function () {
  48821. try {
  48822. if (this.canUseWebAudio) {
  48823. this._audioContext = new AudioContext();
  48824. // create a global volume gain node
  48825. this.masterGain = this._audioContext.createGain();
  48826. this.masterGain.gain.value = 1;
  48827. this.masterGain.connect(this._audioContext.destination);
  48828. this._audioContextInitialized = true;
  48829. }
  48830. }
  48831. catch (e) {
  48832. this.canUseWebAudio = false;
  48833. BABYLON.Tools.Error("Web Audio: " + e.message);
  48834. }
  48835. };
  48836. AudioEngine.prototype.dispose = function () {
  48837. if (this.canUseWebAudio && this._audioContextInitialized) {
  48838. if (this._connectedAnalyser && this._audioContext) {
  48839. this._connectedAnalyser.stopDebugCanvas();
  48840. this._connectedAnalyser.dispose();
  48841. this.masterGain.disconnect();
  48842. this.masterGain.connect(this._audioContext.destination);
  48843. this._connectedAnalyser = null;
  48844. }
  48845. this.masterGain.gain.value = 1;
  48846. }
  48847. this.WarnedWebAudioUnsupported = false;
  48848. };
  48849. AudioEngine.prototype.getGlobalVolume = function () {
  48850. if (this.canUseWebAudio && this._audioContextInitialized) {
  48851. return this.masterGain.gain.value;
  48852. }
  48853. else {
  48854. return -1;
  48855. }
  48856. };
  48857. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  48858. if (this.canUseWebAudio && this._audioContextInitialized) {
  48859. this.masterGain.gain.value = newVolume;
  48860. }
  48861. };
  48862. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  48863. if (this._connectedAnalyser) {
  48864. this._connectedAnalyser.stopDebugCanvas();
  48865. }
  48866. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  48867. this._connectedAnalyser = analyser;
  48868. this.masterGain.disconnect();
  48869. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  48870. }
  48871. };
  48872. return AudioEngine;
  48873. }());
  48874. BABYLON.AudioEngine = AudioEngine;
  48875. })(BABYLON || (BABYLON = {}));
  48876. //# sourceMappingURL=babylon.audioEngine.js.map
  48877. var BABYLON;
  48878. (function (BABYLON) {
  48879. var Sound = /** @class */ (function () {
  48880. /**
  48881. * Create a sound and attach it to a scene
  48882. * @param name Name of your sound
  48883. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  48884. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  48885. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  48886. */
  48887. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  48888. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  48889. var _this = this;
  48890. this.autoplay = false;
  48891. this.loop = false;
  48892. this.useCustomAttenuation = false;
  48893. this.spatialSound = false;
  48894. this.refDistance = 1;
  48895. this.rolloffFactor = 1;
  48896. this.maxDistance = 100;
  48897. this.distanceModel = "linear";
  48898. this._panningModel = "equalpower";
  48899. this._playbackRate = 1;
  48900. this._streaming = false;
  48901. this._startTime = 0;
  48902. this._startOffset = 0;
  48903. this._position = BABYLON.Vector3.Zero();
  48904. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  48905. this._volume = 1;
  48906. this._isLoaded = false;
  48907. this._isReadyToPlay = false;
  48908. this.isPlaying = false;
  48909. this.isPaused = false;
  48910. this._isDirectional = false;
  48911. // Used if you'd like to create a directional sound.
  48912. // If not set, the sound will be omnidirectional
  48913. this._coneInnerAngle = 360;
  48914. this._coneOuterAngle = 360;
  48915. this._coneOuterGain = 0;
  48916. this._isOutputConnected = false;
  48917. this._urlType = "Unknown";
  48918. this.name = name;
  48919. this._scene = scene;
  48920. this._readyToPlayCallback = readyToPlayCallback;
  48921. // Default custom attenuation function is a linear attenuation
  48922. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  48923. if (currentDistance < maxDistance) {
  48924. return currentVolume * (1 - currentDistance / maxDistance);
  48925. }
  48926. else {
  48927. return 0;
  48928. }
  48929. };
  48930. if (options) {
  48931. this.autoplay = options.autoplay || false;
  48932. this.loop = options.loop || false;
  48933. // if volume === 0, we need another way to check this option
  48934. if (options.volume !== undefined) {
  48935. this._volume = options.volume;
  48936. }
  48937. this.spatialSound = options.spatialSound || false;
  48938. this.maxDistance = options.maxDistance || 100;
  48939. this.useCustomAttenuation = options.useCustomAttenuation || false;
  48940. this.rolloffFactor = options.rolloffFactor || 1;
  48941. this.refDistance = options.refDistance || 1;
  48942. this.distanceModel = options.distanceModel || "linear";
  48943. this._playbackRate = options.playbackRate || 1;
  48944. this._streaming = options.streaming || false;
  48945. }
  48946. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48947. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  48948. this._soundGain.gain.value = this._volume;
  48949. this._inputAudioNode = this._soundGain;
  48950. this._ouputAudioNode = this._soundGain;
  48951. if (this.spatialSound) {
  48952. this._createSpatialParameters();
  48953. }
  48954. this._scene.mainSoundTrack.AddSound(this);
  48955. var validParameter = true;
  48956. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  48957. if (urlOrArrayBuffer) {
  48958. if (typeof (urlOrArrayBuffer) === "string")
  48959. this._urlType = "String";
  48960. if (Array.isArray(urlOrArrayBuffer))
  48961. this._urlType = "Array";
  48962. if (urlOrArrayBuffer instanceof ArrayBuffer)
  48963. this._urlType = "ArrayBuffer";
  48964. var urls = [];
  48965. var codecSupportedFound = false;
  48966. switch (this._urlType) {
  48967. case "ArrayBuffer":
  48968. if (urlOrArrayBuffer.byteLength > 0) {
  48969. codecSupportedFound = true;
  48970. this._soundLoaded(urlOrArrayBuffer);
  48971. }
  48972. break;
  48973. case "String":
  48974. urls.push(urlOrArrayBuffer);
  48975. case "Array":
  48976. if (urls.length === 0)
  48977. urls = urlOrArrayBuffer;
  48978. // If we found a supported format, we load it immediately and stop the loop
  48979. for (var i = 0; i < urls.length; i++) {
  48980. var url = urls[i];
  48981. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  48982. codecSupportedFound = true;
  48983. }
  48984. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  48985. codecSupportedFound = true;
  48986. }
  48987. if (url.indexOf(".wav", url.length - 4) !== -1) {
  48988. codecSupportedFound = true;
  48989. }
  48990. if (url.indexOf("blob:") !== -1) {
  48991. codecSupportedFound = true;
  48992. }
  48993. if (codecSupportedFound) {
  48994. // Loading sound using XHR2
  48995. if (!this._streaming) {
  48996. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  48997. }
  48998. else {
  48999. this._htmlAudioElement = new Audio(url);
  49000. this._htmlAudioElement.controls = false;
  49001. this._htmlAudioElement.loop = this.loop;
  49002. this._htmlAudioElement.crossOrigin = "anonymous";
  49003. this._htmlAudioElement.preload = "auto";
  49004. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  49005. _this._isReadyToPlay = true;
  49006. if (_this.autoplay) {
  49007. _this.play();
  49008. }
  49009. if (_this._readyToPlayCallback) {
  49010. _this._readyToPlayCallback();
  49011. }
  49012. });
  49013. document.body.appendChild(this._htmlAudioElement);
  49014. }
  49015. break;
  49016. }
  49017. }
  49018. break;
  49019. default:
  49020. validParameter = false;
  49021. break;
  49022. }
  49023. if (!validParameter) {
  49024. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  49025. }
  49026. else {
  49027. if (!codecSupportedFound) {
  49028. this._isReadyToPlay = true;
  49029. // Simulating a ready to play event to avoid breaking code path
  49030. if (this._readyToPlayCallback) {
  49031. window.setTimeout(function () {
  49032. if (_this._readyToPlayCallback) {
  49033. _this._readyToPlayCallback();
  49034. }
  49035. }, 1000);
  49036. }
  49037. }
  49038. }
  49039. }
  49040. }
  49041. else {
  49042. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  49043. this._scene.mainSoundTrack.AddSound(this);
  49044. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  49045. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  49046. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  49047. }
  49048. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  49049. if (this._readyToPlayCallback) {
  49050. window.setTimeout(function () {
  49051. if (_this._readyToPlayCallback) {
  49052. _this._readyToPlayCallback();
  49053. }
  49054. }, 1000);
  49055. }
  49056. }
  49057. }
  49058. Sound.prototype.dispose = function () {
  49059. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  49060. if (this.isPlaying) {
  49061. this.stop();
  49062. }
  49063. this._isReadyToPlay = false;
  49064. if (this.soundTrackId === -1) {
  49065. this._scene.mainSoundTrack.RemoveSound(this);
  49066. }
  49067. else {
  49068. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  49069. }
  49070. if (this._soundGain) {
  49071. this._soundGain.disconnect();
  49072. this._soundGain = null;
  49073. }
  49074. if (this._soundPanner) {
  49075. this._soundPanner.disconnect();
  49076. this._soundPanner = null;
  49077. }
  49078. if (this._soundSource) {
  49079. this._soundSource.disconnect();
  49080. this._soundSource = null;
  49081. }
  49082. this._audioBuffer = null;
  49083. if (this._htmlAudioElement) {
  49084. this._htmlAudioElement.pause();
  49085. this._htmlAudioElement.src = "";
  49086. document.body.removeChild(this._htmlAudioElement);
  49087. }
  49088. if (this._connectedMesh && this._registerFunc) {
  49089. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49090. this._connectedMesh = null;
  49091. }
  49092. }
  49093. };
  49094. Sound.prototype.isReady = function () {
  49095. return this._isReadyToPlay;
  49096. };
  49097. Sound.prototype._soundLoaded = function (audioData) {
  49098. var _this = this;
  49099. this._isLoaded = true;
  49100. if (!BABYLON.Engine.audioEngine.audioContext) {
  49101. return;
  49102. }
  49103. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  49104. _this._audioBuffer = buffer;
  49105. _this._isReadyToPlay = true;
  49106. if (_this.autoplay) {
  49107. _this.play();
  49108. }
  49109. if (_this._readyToPlayCallback) {
  49110. _this._readyToPlayCallback();
  49111. }
  49112. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  49113. };
  49114. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  49115. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49116. this._audioBuffer = audioBuffer;
  49117. this._isReadyToPlay = true;
  49118. }
  49119. };
  49120. Sound.prototype.updateOptions = function (options) {
  49121. if (options) {
  49122. this.loop = options.loop || this.loop;
  49123. this.maxDistance = options.maxDistance || this.maxDistance;
  49124. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  49125. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  49126. this.refDistance = options.refDistance || this.refDistance;
  49127. this.distanceModel = options.distanceModel || this.distanceModel;
  49128. this._playbackRate = options.playbackRate || this._playbackRate;
  49129. this._updateSpatialParameters();
  49130. if (this.isPlaying) {
  49131. if (this._streaming) {
  49132. this._htmlAudioElement.playbackRate = this._playbackRate;
  49133. }
  49134. else {
  49135. if (this._soundSource) {
  49136. this._soundSource.playbackRate.value = this._playbackRate;
  49137. }
  49138. }
  49139. }
  49140. }
  49141. };
  49142. Sound.prototype._createSpatialParameters = function () {
  49143. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49144. if (this._scene.headphone) {
  49145. this._panningModel = "HRTF";
  49146. }
  49147. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  49148. this._updateSpatialParameters();
  49149. this._soundPanner.connect(this._ouputAudioNode);
  49150. this._inputAudioNode = this._soundPanner;
  49151. }
  49152. };
  49153. Sound.prototype._updateSpatialParameters = function () {
  49154. if (this.spatialSound && this._soundPanner) {
  49155. if (this.useCustomAttenuation) {
  49156. // Tricks to disable in a way embedded Web Audio attenuation
  49157. this._soundPanner.distanceModel = "linear";
  49158. this._soundPanner.maxDistance = Number.MAX_VALUE;
  49159. this._soundPanner.refDistance = 1;
  49160. this._soundPanner.rolloffFactor = 1;
  49161. this._soundPanner.panningModel = this._panningModel;
  49162. }
  49163. else {
  49164. this._soundPanner.distanceModel = this.distanceModel;
  49165. this._soundPanner.maxDistance = this.maxDistance;
  49166. this._soundPanner.refDistance = this.refDistance;
  49167. this._soundPanner.rolloffFactor = this.rolloffFactor;
  49168. this._soundPanner.panningModel = this._panningModel;
  49169. }
  49170. }
  49171. };
  49172. Sound.prototype.switchPanningModelToHRTF = function () {
  49173. this._panningModel = "HRTF";
  49174. this._switchPanningModel();
  49175. };
  49176. Sound.prototype.switchPanningModelToEqualPower = function () {
  49177. this._panningModel = "equalpower";
  49178. this._switchPanningModel();
  49179. };
  49180. Sound.prototype._switchPanningModel = function () {
  49181. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49182. this._soundPanner.panningModel = this._panningModel;
  49183. }
  49184. };
  49185. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  49186. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49187. if (this._isOutputConnected) {
  49188. this._ouputAudioNode.disconnect();
  49189. }
  49190. this._ouputAudioNode.connect(soundTrackAudioNode);
  49191. this._isOutputConnected = true;
  49192. }
  49193. };
  49194. /**
  49195. * Transform this sound into a directional source
  49196. * @param coneInnerAngle Size of the inner cone in degree
  49197. * @param coneOuterAngle Size of the outer cone in degree
  49198. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  49199. */
  49200. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  49201. if (coneOuterAngle < coneInnerAngle) {
  49202. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  49203. return;
  49204. }
  49205. this._coneInnerAngle = coneInnerAngle;
  49206. this._coneOuterAngle = coneOuterAngle;
  49207. this._coneOuterGain = coneOuterGain;
  49208. this._isDirectional = true;
  49209. if (this.isPlaying && this.loop) {
  49210. this.stop();
  49211. this.play();
  49212. }
  49213. };
  49214. Sound.prototype.setPosition = function (newPosition) {
  49215. this._position = newPosition;
  49216. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  49217. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49218. }
  49219. };
  49220. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  49221. this._localDirection = newLocalDirection;
  49222. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  49223. this._updateDirection();
  49224. }
  49225. };
  49226. Sound.prototype._updateDirection = function () {
  49227. if (!this._connectedMesh || !this._soundPanner) {
  49228. return;
  49229. }
  49230. var mat = this._connectedMesh.getWorldMatrix();
  49231. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  49232. direction.normalize();
  49233. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  49234. };
  49235. Sound.prototype.updateDistanceFromListener = function () {
  49236. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  49237. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  49238. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  49239. }
  49240. };
  49241. Sound.prototype.setAttenuationFunction = function (callback) {
  49242. this._customAttenuationFunction = callback;
  49243. };
  49244. /**
  49245. * Play the sound
  49246. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  49247. * @param offset (optional) Start the sound setting it at a specific time
  49248. */
  49249. Sound.prototype.play = function (time, offset) {
  49250. var _this = this;
  49251. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  49252. try {
  49253. if (this._startOffset < 0) {
  49254. time = -this._startOffset;
  49255. this._startOffset = 0;
  49256. }
  49257. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49258. if (!this._soundSource || !this._streamingSource) {
  49259. if (this.spatialSound && this._soundPanner) {
  49260. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  49261. if (this._isDirectional) {
  49262. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  49263. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  49264. this._soundPanner.coneOuterGain = this._coneOuterGain;
  49265. if (this._connectedMesh) {
  49266. this._updateDirection();
  49267. }
  49268. else {
  49269. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  49270. }
  49271. }
  49272. }
  49273. }
  49274. if (this._streaming) {
  49275. if (!this._streamingSource) {
  49276. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  49277. this._htmlAudioElement.onended = function () { _this._onended(); };
  49278. this._htmlAudioElement.playbackRate = this._playbackRate;
  49279. }
  49280. this._streamingSource.disconnect();
  49281. this._streamingSource.connect(this._inputAudioNode);
  49282. this._htmlAudioElement.play();
  49283. }
  49284. else {
  49285. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  49286. this._soundSource.buffer = this._audioBuffer;
  49287. this._soundSource.connect(this._inputAudioNode);
  49288. this._soundSource.loop = this.loop;
  49289. this._soundSource.playbackRate.value = this._playbackRate;
  49290. this._soundSource.onended = function () { _this._onended(); };
  49291. if (this._soundSource.buffer) {
  49292. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  49293. }
  49294. }
  49295. this._startTime = startTime;
  49296. this.isPlaying = true;
  49297. this.isPaused = false;
  49298. }
  49299. catch (ex) {
  49300. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  49301. }
  49302. }
  49303. };
  49304. Sound.prototype._onended = function () {
  49305. this.isPlaying = false;
  49306. if (this.onended) {
  49307. this.onended();
  49308. }
  49309. };
  49310. /**
  49311. * Stop the sound
  49312. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  49313. */
  49314. Sound.prototype.stop = function (time) {
  49315. if (this.isPlaying) {
  49316. if (this._streaming) {
  49317. this._htmlAudioElement.pause();
  49318. // Test needed for Firefox or it will generate an Invalid State Error
  49319. if (this._htmlAudioElement.currentTime > 0) {
  49320. this._htmlAudioElement.currentTime = 0;
  49321. }
  49322. }
  49323. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  49324. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  49325. this._soundSource.stop(stopTime);
  49326. this._soundSource.onended = function () { };
  49327. if (!this.isPaused) {
  49328. this._startOffset = 0;
  49329. }
  49330. }
  49331. this.isPlaying = false;
  49332. }
  49333. };
  49334. Sound.prototype.pause = function () {
  49335. if (this.isPlaying) {
  49336. this.isPaused = true;
  49337. if (this._streaming) {
  49338. this._htmlAudioElement.pause();
  49339. }
  49340. else if (BABYLON.Engine.audioEngine.audioContext) {
  49341. this.stop(0);
  49342. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  49343. }
  49344. }
  49345. };
  49346. Sound.prototype.setVolume = function (newVolume, time) {
  49347. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  49348. if (time && BABYLON.Engine.audioEngine.audioContext) {
  49349. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  49350. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  49351. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  49352. }
  49353. else {
  49354. this._soundGain.gain.value = newVolume;
  49355. }
  49356. }
  49357. this._volume = newVolume;
  49358. };
  49359. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  49360. this._playbackRate = newPlaybackRate;
  49361. if (this.isPlaying) {
  49362. if (this._streaming) {
  49363. this._htmlAudioElement.playbackRate = this._playbackRate;
  49364. }
  49365. else if (this._soundSource) {
  49366. this._soundSource.playbackRate.value = this._playbackRate;
  49367. }
  49368. }
  49369. };
  49370. Sound.prototype.getVolume = function () {
  49371. return this._volume;
  49372. };
  49373. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  49374. var _this = this;
  49375. if (this._connectedMesh && this._registerFunc) {
  49376. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49377. this._registerFunc = null;
  49378. }
  49379. this._connectedMesh = meshToConnectTo;
  49380. if (!this.spatialSound) {
  49381. this.spatialSound = true;
  49382. this._createSpatialParameters();
  49383. if (this.isPlaying && this.loop) {
  49384. this.stop();
  49385. this.play();
  49386. }
  49387. }
  49388. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  49389. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  49390. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  49391. };
  49392. Sound.prototype.detachFromMesh = function () {
  49393. if (this._connectedMesh && this._registerFunc) {
  49394. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  49395. this._registerFunc = null;
  49396. this._connectedMesh = null;
  49397. }
  49398. };
  49399. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  49400. var boundingInfo = connectedMesh.getBoundingInfo();
  49401. if (!boundingInfo) {
  49402. return;
  49403. }
  49404. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  49405. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  49406. this._updateDirection();
  49407. }
  49408. };
  49409. Sound.prototype.clone = function () {
  49410. var _this = this;
  49411. if (!this._streaming) {
  49412. var setBufferAndRun = function () {
  49413. if (_this._isReadyToPlay) {
  49414. clonedSound._audioBuffer = _this.getAudioBuffer();
  49415. clonedSound._isReadyToPlay = true;
  49416. if (clonedSound.autoplay) {
  49417. clonedSound.play();
  49418. }
  49419. }
  49420. else {
  49421. window.setTimeout(setBufferAndRun, 300);
  49422. }
  49423. };
  49424. var currentOptions = {
  49425. autoplay: this.autoplay, loop: this.loop,
  49426. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  49427. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  49428. refDistance: this.refDistance, distanceModel: this.distanceModel
  49429. };
  49430. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  49431. if (this.useCustomAttenuation) {
  49432. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  49433. }
  49434. clonedSound.setPosition(this._position);
  49435. clonedSound.setPlaybackRate(this._playbackRate);
  49436. setBufferAndRun();
  49437. return clonedSound;
  49438. }
  49439. else {
  49440. return null;
  49441. }
  49442. };
  49443. Sound.prototype.getAudioBuffer = function () {
  49444. return this._audioBuffer;
  49445. };
  49446. Sound.prototype.serialize = function () {
  49447. var serializationObject = {
  49448. name: this.name,
  49449. url: this.name,
  49450. autoplay: this.autoplay,
  49451. loop: this.loop,
  49452. volume: this._volume,
  49453. spatialSound: this.spatialSound,
  49454. maxDistance: this.maxDistance,
  49455. rolloffFactor: this.rolloffFactor,
  49456. refDistance: this.refDistance,
  49457. distanceModel: this.distanceModel,
  49458. playbackRate: this._playbackRate,
  49459. panningModel: this._panningModel,
  49460. soundTrackId: this.soundTrackId
  49461. };
  49462. if (this.spatialSound) {
  49463. if (this._connectedMesh)
  49464. serializationObject.connectedMeshId = this._connectedMesh.id;
  49465. serializationObject.position = this._position.asArray();
  49466. serializationObject.refDistance = this.refDistance;
  49467. serializationObject.distanceModel = this.distanceModel;
  49468. serializationObject.isDirectional = this._isDirectional;
  49469. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  49470. serializationObject.coneInnerAngle = this._coneInnerAngle;
  49471. serializationObject.coneOuterAngle = this._coneOuterAngle;
  49472. serializationObject.coneOuterGain = this._coneOuterGain;
  49473. }
  49474. return serializationObject;
  49475. };
  49476. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  49477. var soundName = parsedSound.name;
  49478. var soundUrl;
  49479. if (parsedSound.url) {
  49480. soundUrl = rootUrl + parsedSound.url;
  49481. }
  49482. else {
  49483. soundUrl = rootUrl + soundName;
  49484. }
  49485. var options = {
  49486. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  49487. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  49488. rolloffFactor: parsedSound.rolloffFactor,
  49489. refDistance: parsedSound.refDistance,
  49490. distanceModel: parsedSound.distanceModel,
  49491. playbackRate: parsedSound.playbackRate
  49492. };
  49493. var newSound;
  49494. if (!sourceSound) {
  49495. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  49496. scene._addPendingData(newSound);
  49497. }
  49498. else {
  49499. var setBufferAndRun = function () {
  49500. if (sourceSound._isReadyToPlay) {
  49501. newSound._audioBuffer = sourceSound.getAudioBuffer();
  49502. newSound._isReadyToPlay = true;
  49503. if (newSound.autoplay) {
  49504. newSound.play();
  49505. }
  49506. }
  49507. else {
  49508. window.setTimeout(setBufferAndRun, 300);
  49509. }
  49510. };
  49511. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  49512. setBufferAndRun();
  49513. }
  49514. if (parsedSound.position) {
  49515. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  49516. newSound.setPosition(soundPosition);
  49517. }
  49518. if (parsedSound.isDirectional) {
  49519. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  49520. if (parsedSound.localDirectionToMesh) {
  49521. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  49522. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  49523. }
  49524. }
  49525. if (parsedSound.connectedMeshId) {
  49526. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  49527. if (connectedMesh) {
  49528. newSound.attachToMesh(connectedMesh);
  49529. }
  49530. }
  49531. return newSound;
  49532. };
  49533. return Sound;
  49534. }());
  49535. BABYLON.Sound = Sound;
  49536. })(BABYLON || (BABYLON = {}));
  49537. //# sourceMappingURL=babylon.sound.js.map
  49538. var BABYLON;
  49539. (function (BABYLON) {
  49540. var SoundTrack = /** @class */ (function () {
  49541. function SoundTrack(scene, options) {
  49542. this.id = -1;
  49543. this._isMainTrack = false;
  49544. this._isInitialized = false;
  49545. this._scene = scene;
  49546. this.soundCollection = new Array();
  49547. this._options = options;
  49548. if (!this._isMainTrack) {
  49549. this._scene.soundTracks.push(this);
  49550. this.id = this._scene.soundTracks.length - 1;
  49551. }
  49552. }
  49553. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  49554. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49555. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  49556. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  49557. if (this._options) {
  49558. if (this._options.volume) {
  49559. this._outputAudioNode.gain.value = this._options.volume;
  49560. }
  49561. if (this._options.mainTrack) {
  49562. this._isMainTrack = this._options.mainTrack;
  49563. }
  49564. }
  49565. this._isInitialized = true;
  49566. }
  49567. };
  49568. SoundTrack.prototype.dispose = function () {
  49569. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49570. if (this._connectedAnalyser) {
  49571. this._connectedAnalyser.stopDebugCanvas();
  49572. }
  49573. while (this.soundCollection.length) {
  49574. this.soundCollection[0].dispose();
  49575. }
  49576. if (this._outputAudioNode) {
  49577. this._outputAudioNode.disconnect();
  49578. }
  49579. this._outputAudioNode = null;
  49580. }
  49581. };
  49582. SoundTrack.prototype.AddSound = function (sound) {
  49583. if (!this._isInitialized) {
  49584. this._initializeSoundTrackAudioGraph();
  49585. }
  49586. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49587. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  49588. }
  49589. if (sound.soundTrackId) {
  49590. if (sound.soundTrackId === -1) {
  49591. this._scene.mainSoundTrack.RemoveSound(sound);
  49592. }
  49593. else {
  49594. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  49595. }
  49596. }
  49597. this.soundCollection.push(sound);
  49598. sound.soundTrackId = this.id;
  49599. };
  49600. SoundTrack.prototype.RemoveSound = function (sound) {
  49601. var index = this.soundCollection.indexOf(sound);
  49602. if (index !== -1) {
  49603. this.soundCollection.splice(index, 1);
  49604. }
  49605. };
  49606. SoundTrack.prototype.setVolume = function (newVolume) {
  49607. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49608. this._outputAudioNode.gain.value = newVolume;
  49609. }
  49610. };
  49611. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  49612. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49613. for (var i = 0; i < this.soundCollection.length; i++) {
  49614. this.soundCollection[i].switchPanningModelToHRTF();
  49615. }
  49616. }
  49617. };
  49618. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  49619. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49620. for (var i = 0; i < this.soundCollection.length; i++) {
  49621. this.soundCollection[i].switchPanningModelToEqualPower();
  49622. }
  49623. }
  49624. };
  49625. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  49626. if (this._connectedAnalyser) {
  49627. this._connectedAnalyser.stopDebugCanvas();
  49628. }
  49629. this._connectedAnalyser = analyser;
  49630. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49631. this._outputAudioNode.disconnect();
  49632. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  49633. }
  49634. };
  49635. return SoundTrack;
  49636. }());
  49637. BABYLON.SoundTrack = SoundTrack;
  49638. })(BABYLON || (BABYLON = {}));
  49639. //# sourceMappingURL=babylon.soundtrack.js.map
  49640. var BABYLON;
  49641. (function (BABYLON) {
  49642. var Analyser = /** @class */ (function () {
  49643. function Analyser(scene) {
  49644. this.SMOOTHING = 0.75;
  49645. this.FFT_SIZE = 512;
  49646. this.BARGRAPHAMPLITUDE = 256;
  49647. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  49648. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  49649. this._scene = scene;
  49650. this._audioEngine = BABYLON.Engine.audioEngine;
  49651. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  49652. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  49653. this._webAudioAnalyser.minDecibels = -140;
  49654. this._webAudioAnalyser.maxDecibels = 0;
  49655. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49656. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49657. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  49658. }
  49659. }
  49660. Analyser.prototype.getFrequencyBinCount = function () {
  49661. if (this._audioEngine.canUseWebAudio) {
  49662. return this._webAudioAnalyser.frequencyBinCount;
  49663. }
  49664. else {
  49665. return 0;
  49666. }
  49667. };
  49668. Analyser.prototype.getByteFrequencyData = function () {
  49669. if (this._audioEngine.canUseWebAudio) {
  49670. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49671. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49672. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  49673. }
  49674. return this._byteFreqs;
  49675. };
  49676. Analyser.prototype.getByteTimeDomainData = function () {
  49677. if (this._audioEngine.canUseWebAudio) {
  49678. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49679. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49680. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  49681. }
  49682. return this._byteTime;
  49683. };
  49684. Analyser.prototype.getFloatFrequencyData = function () {
  49685. if (this._audioEngine.canUseWebAudio) {
  49686. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49687. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49688. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  49689. }
  49690. return this._floatFreqs;
  49691. };
  49692. Analyser.prototype.drawDebugCanvas = function () {
  49693. var _this = this;
  49694. if (this._audioEngine.canUseWebAudio) {
  49695. if (!this._debugCanvas) {
  49696. this._debugCanvas = document.createElement("canvas");
  49697. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  49698. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  49699. this._debugCanvas.style.position = "absolute";
  49700. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  49701. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  49702. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  49703. document.body.appendChild(this._debugCanvas);
  49704. this._registerFunc = function () {
  49705. _this.drawDebugCanvas();
  49706. };
  49707. this._scene.registerBeforeRender(this._registerFunc);
  49708. }
  49709. if (this._registerFunc && this._debugCanvasContext) {
  49710. var workingArray = this.getByteFrequencyData();
  49711. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  49712. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  49713. // Draw the frequency domain chart.
  49714. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  49715. var value = workingArray[i];
  49716. var percent = value / this.BARGRAPHAMPLITUDE;
  49717. var height = this.DEBUGCANVASSIZE.height * percent;
  49718. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  49719. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  49720. var hue = i / this.getFrequencyBinCount() * 360;
  49721. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  49722. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  49723. }
  49724. }
  49725. }
  49726. };
  49727. Analyser.prototype.stopDebugCanvas = function () {
  49728. if (this._debugCanvas) {
  49729. if (this._registerFunc) {
  49730. this._scene.unregisterBeforeRender(this._registerFunc);
  49731. this._registerFunc = null;
  49732. }
  49733. document.body.removeChild(this._debugCanvas);
  49734. this._debugCanvas = null;
  49735. this._debugCanvasContext = null;
  49736. }
  49737. };
  49738. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  49739. if (this._audioEngine.canUseWebAudio) {
  49740. inputAudioNode.connect(this._webAudioAnalyser);
  49741. this._webAudioAnalyser.connect(outputAudioNode);
  49742. }
  49743. };
  49744. Analyser.prototype.dispose = function () {
  49745. if (this._audioEngine.canUseWebAudio) {
  49746. this._webAudioAnalyser.disconnect();
  49747. }
  49748. };
  49749. return Analyser;
  49750. }());
  49751. BABYLON.Analyser = Analyser;
  49752. })(BABYLON || (BABYLON = {}));
  49753. //# sourceMappingURL=babylon.analyser.js.map
  49754. var BABYLON;
  49755. (function (BABYLON) {
  49756. var CubeTexture = /** @class */ (function (_super) {
  49757. __extends(CubeTexture, _super);
  49758. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  49759. if (extensions === void 0) { extensions = null; }
  49760. if (noMipmap === void 0) { noMipmap = false; }
  49761. if (files === void 0) { files = null; }
  49762. if (onLoad === void 0) { onLoad = null; }
  49763. if (onError === void 0) { onError = null; }
  49764. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49765. if (prefiltered === void 0) { prefiltered = false; }
  49766. if (forcedExtension === void 0) { forcedExtension = null; }
  49767. var _this = _super.call(this, scene) || this;
  49768. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49769. _this.name = rootUrl;
  49770. _this.url = rootUrl;
  49771. _this._noMipmap = noMipmap;
  49772. _this.hasAlpha = false;
  49773. _this._format = format;
  49774. _this._prefiltered = prefiltered;
  49775. _this.isCube = true;
  49776. _this._textureMatrix = BABYLON.Matrix.Identity();
  49777. if (prefiltered) {
  49778. _this.gammaSpace = false;
  49779. }
  49780. if (!rootUrl && !files) {
  49781. return _this;
  49782. }
  49783. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  49784. if (!files) {
  49785. if (!extensions) {
  49786. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  49787. }
  49788. files = [];
  49789. for (var index = 0; index < extensions.length; index++) {
  49790. files.push(rootUrl + extensions[index]);
  49791. }
  49792. _this._extensions = extensions;
  49793. }
  49794. _this._files = files;
  49795. if (!_this._texture) {
  49796. if (!scene.useDelayedTextureLoading) {
  49797. if (prefiltered) {
  49798. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  49799. }
  49800. else {
  49801. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  49802. }
  49803. }
  49804. else {
  49805. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49806. }
  49807. }
  49808. else if (onLoad) {
  49809. if (_this._texture.isReady) {
  49810. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  49811. }
  49812. else {
  49813. _this._texture.onLoadedObservable.add(onLoad);
  49814. }
  49815. }
  49816. return _this;
  49817. }
  49818. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  49819. return new CubeTexture("", scene, null, noMipmap, files);
  49820. };
  49821. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  49822. if (forcedExtension === void 0) { forcedExtension = null; }
  49823. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  49824. };
  49825. // Methods
  49826. CubeTexture.prototype.delayLoad = function () {
  49827. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49828. return;
  49829. }
  49830. var scene = this.getScene();
  49831. if (!scene) {
  49832. return;
  49833. }
  49834. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49835. this._texture = this._getFromCache(this.url, this._noMipmap);
  49836. if (!this._texture) {
  49837. if (this._prefiltered) {
  49838. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  49839. }
  49840. else {
  49841. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  49842. }
  49843. }
  49844. };
  49845. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  49846. return this._textureMatrix;
  49847. };
  49848. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49849. this._textureMatrix = value;
  49850. };
  49851. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49852. var texture = BABYLON.SerializationHelper.Parse(function () {
  49853. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  49854. }, parsedTexture, scene);
  49855. // Animations
  49856. if (parsedTexture.animations) {
  49857. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  49858. var parsedAnimation = parsedTexture.animations[animationIndex];
  49859. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49860. }
  49861. }
  49862. return texture;
  49863. };
  49864. CubeTexture.prototype.clone = function () {
  49865. var _this = this;
  49866. return BABYLON.SerializationHelper.Clone(function () {
  49867. var scene = _this.getScene();
  49868. if (!scene) {
  49869. return _this;
  49870. }
  49871. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  49872. }, this);
  49873. };
  49874. return CubeTexture;
  49875. }(BABYLON.BaseTexture));
  49876. BABYLON.CubeTexture = CubeTexture;
  49877. })(BABYLON || (BABYLON = {}));
  49878. //# sourceMappingURL=babylon.cubeTexture.js.map
  49879. var BABYLON;
  49880. (function (BABYLON) {
  49881. var RenderTargetTexture = /** @class */ (function (_super) {
  49882. __extends(RenderTargetTexture, _super);
  49883. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  49884. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  49885. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49886. if (isCube === void 0) { isCube = false; }
  49887. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49888. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49889. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  49890. if (isMulti === void 0) { isMulti = false; }
  49891. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49892. _this.isCube = isCube;
  49893. /**
  49894. * Use this list to define the list of mesh you want to render.
  49895. */
  49896. _this.renderList = new Array();
  49897. _this.renderParticles = true;
  49898. _this.renderSprites = false;
  49899. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  49900. _this.ignoreCameraViewport = false;
  49901. // Events
  49902. /**
  49903. * An event triggered when the texture is unbind.
  49904. * @type {BABYLON.Observable}
  49905. */
  49906. _this.onBeforeBindObservable = new BABYLON.Observable();
  49907. /**
  49908. * An event triggered when the texture is unbind.
  49909. * @type {BABYLON.Observable}
  49910. */
  49911. _this.onAfterUnbindObservable = new BABYLON.Observable();
  49912. /**
  49913. * An event triggered before rendering the texture
  49914. * @type {BABYLON.Observable}
  49915. */
  49916. _this.onBeforeRenderObservable = new BABYLON.Observable();
  49917. /**
  49918. * An event triggered after rendering the texture
  49919. * @type {BABYLON.Observable}
  49920. */
  49921. _this.onAfterRenderObservable = new BABYLON.Observable();
  49922. /**
  49923. * An event triggered after the texture clear
  49924. * @type {BABYLON.Observable}
  49925. */
  49926. _this.onClearObservable = new BABYLON.Observable();
  49927. _this._currentRefreshId = -1;
  49928. _this._refreshRate = 1;
  49929. _this._samples = 1;
  49930. scene = _this.getScene();
  49931. if (!scene) {
  49932. return _this;
  49933. }
  49934. _this._engine = scene.getEngine();
  49935. _this.name = name;
  49936. _this.isRenderTarget = true;
  49937. _this._initialSizeParameter = size;
  49938. _this._processSizeParameter(size);
  49939. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  49940. });
  49941. _this._generateMipMaps = generateMipMaps ? true : false;
  49942. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  49943. // Rendering groups
  49944. _this._renderingManager = new BABYLON.RenderingManager(scene);
  49945. if (isMulti) {
  49946. return _this;
  49947. }
  49948. _this._renderTargetOptions = {
  49949. generateMipMaps: generateMipMaps,
  49950. type: type,
  49951. samplingMode: samplingMode,
  49952. generateDepthBuffer: generateDepthBuffer,
  49953. generateStencilBuffer: generateStencilBuffer
  49954. };
  49955. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  49956. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49957. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49958. }
  49959. if (isCube) {
  49960. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  49961. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  49962. _this._textureMatrix = BABYLON.Matrix.Identity();
  49963. }
  49964. else {
  49965. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  49966. }
  49967. return _this;
  49968. }
  49969. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  49970. get: function () {
  49971. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  49972. },
  49973. enumerable: true,
  49974. configurable: true
  49975. });
  49976. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  49977. get: function () {
  49978. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  49979. },
  49980. enumerable: true,
  49981. configurable: true
  49982. });
  49983. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  49984. get: function () {
  49985. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  49986. },
  49987. enumerable: true,
  49988. configurable: true
  49989. });
  49990. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  49991. set: function (callback) {
  49992. if (this._onAfterUnbindObserver) {
  49993. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  49994. }
  49995. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  49996. },
  49997. enumerable: true,
  49998. configurable: true
  49999. });
  50000. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  50001. set: function (callback) {
  50002. if (this._onBeforeRenderObserver) {
  50003. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50004. }
  50005. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50006. },
  50007. enumerable: true,
  50008. configurable: true
  50009. });
  50010. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  50011. set: function (callback) {
  50012. if (this._onAfterRenderObserver) {
  50013. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50014. }
  50015. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50016. },
  50017. enumerable: true,
  50018. configurable: true
  50019. });
  50020. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  50021. set: function (callback) {
  50022. if (this._onClearObserver) {
  50023. this.onClearObservable.remove(this._onClearObserver);
  50024. }
  50025. this._onClearObserver = this.onClearObservable.add(callback);
  50026. },
  50027. enumerable: true,
  50028. configurable: true
  50029. });
  50030. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  50031. get: function () {
  50032. return this._renderTargetOptions;
  50033. },
  50034. enumerable: true,
  50035. configurable: true
  50036. });
  50037. RenderTargetTexture.prototype._onRatioRescale = function () {
  50038. if (this._sizeRatio) {
  50039. this.resize(this._initialSizeParameter);
  50040. }
  50041. };
  50042. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  50043. if (size.ratio) {
  50044. this._sizeRatio = size.ratio;
  50045. this._size = {
  50046. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  50047. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  50048. };
  50049. }
  50050. else {
  50051. this._size = size;
  50052. }
  50053. };
  50054. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  50055. get: function () {
  50056. return this._samples;
  50057. },
  50058. set: function (value) {
  50059. if (this._samples === value) {
  50060. return;
  50061. }
  50062. var scene = this.getScene();
  50063. if (!scene) {
  50064. return;
  50065. }
  50066. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  50067. },
  50068. enumerable: true,
  50069. configurable: true
  50070. });
  50071. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  50072. this._currentRefreshId = -1;
  50073. };
  50074. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  50075. get: function () {
  50076. return this._refreshRate;
  50077. },
  50078. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  50079. set: function (value) {
  50080. this._refreshRate = value;
  50081. this.resetRefreshCounter();
  50082. },
  50083. enumerable: true,
  50084. configurable: true
  50085. });
  50086. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  50087. if (!this._postProcessManager) {
  50088. var scene = this.getScene();
  50089. if (!scene) {
  50090. return;
  50091. }
  50092. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  50093. this._postProcesses = new Array();
  50094. }
  50095. this._postProcesses.push(postProcess);
  50096. this._postProcesses[0].autoClear = false;
  50097. };
  50098. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  50099. if (!this._postProcesses) {
  50100. return;
  50101. }
  50102. if (dispose) {
  50103. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  50104. var postProcess = _a[_i];
  50105. postProcess.dispose();
  50106. }
  50107. }
  50108. this._postProcesses = [];
  50109. };
  50110. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  50111. if (!this._postProcesses) {
  50112. return;
  50113. }
  50114. var index = this._postProcesses.indexOf(postProcess);
  50115. if (index === -1) {
  50116. return;
  50117. }
  50118. this._postProcesses.splice(index, 1);
  50119. if (this._postProcesses.length > 0) {
  50120. this._postProcesses[0].autoClear = false;
  50121. }
  50122. };
  50123. RenderTargetTexture.prototype._shouldRender = function () {
  50124. if (this._currentRefreshId === -1) {
  50125. this._currentRefreshId = 1;
  50126. return true;
  50127. }
  50128. if (this.refreshRate === this._currentRefreshId) {
  50129. this._currentRefreshId = 1;
  50130. return true;
  50131. }
  50132. this._currentRefreshId++;
  50133. return false;
  50134. };
  50135. RenderTargetTexture.prototype.getRenderSize = function () {
  50136. if (this._size.width) {
  50137. return this._size.width;
  50138. }
  50139. return this._size;
  50140. };
  50141. RenderTargetTexture.prototype.getRenderWidth = function () {
  50142. if (this._size.width) {
  50143. return this._size.width;
  50144. }
  50145. return this._size;
  50146. };
  50147. RenderTargetTexture.prototype.getRenderHeight = function () {
  50148. if (this._size.width) {
  50149. return this._size.height;
  50150. }
  50151. return this._size;
  50152. };
  50153. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  50154. get: function () {
  50155. return true;
  50156. },
  50157. enumerable: true,
  50158. configurable: true
  50159. });
  50160. RenderTargetTexture.prototype.scale = function (ratio) {
  50161. var newSize = this.getRenderSize() * ratio;
  50162. this.resize(newSize);
  50163. };
  50164. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  50165. if (this.isCube) {
  50166. return this._textureMatrix;
  50167. }
  50168. return _super.prototype.getReflectionTextureMatrix.call(this);
  50169. };
  50170. RenderTargetTexture.prototype.resize = function (size) {
  50171. this.releaseInternalTexture();
  50172. var scene = this.getScene();
  50173. if (!scene) {
  50174. return;
  50175. }
  50176. this._processSizeParameter(size);
  50177. if (this.isCube) {
  50178. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  50179. }
  50180. else {
  50181. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  50182. }
  50183. };
  50184. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  50185. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  50186. if (dumpForDebug === void 0) { dumpForDebug = false; }
  50187. var scene = this.getScene();
  50188. if (!scene) {
  50189. return;
  50190. }
  50191. var engine = scene.getEngine();
  50192. if (this.useCameraPostProcesses !== undefined) {
  50193. useCameraPostProcess = this.useCameraPostProcesses;
  50194. }
  50195. if (this._waitingRenderList) {
  50196. this.renderList = [];
  50197. for (var index = 0; index < this._waitingRenderList.length; index++) {
  50198. var id = this._waitingRenderList[index];
  50199. var mesh_1 = scene.getMeshByID(id);
  50200. if (mesh_1) {
  50201. this.renderList.push(mesh_1);
  50202. }
  50203. }
  50204. delete this._waitingRenderList;
  50205. }
  50206. // Is predicate defined?
  50207. if (this.renderListPredicate) {
  50208. if (this.renderList) {
  50209. this.renderList.splice(0); // Clear previous renderList
  50210. }
  50211. else {
  50212. this.renderList = [];
  50213. }
  50214. var scene = this.getScene();
  50215. if (!scene) {
  50216. return;
  50217. }
  50218. var sceneMeshes = scene.meshes;
  50219. for (var index = 0; index < sceneMeshes.length; index++) {
  50220. var mesh = sceneMeshes[index];
  50221. if (this.renderListPredicate(mesh)) {
  50222. this.renderList.push(mesh);
  50223. }
  50224. }
  50225. }
  50226. this.onBeforeBindObservable.notifyObservers(this);
  50227. // Set custom projection.
  50228. // Needs to be before binding to prevent changing the aspect ratio.
  50229. var camera;
  50230. if (this.activeCamera) {
  50231. camera = this.activeCamera;
  50232. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50233. if (this.activeCamera !== scene.activeCamera) {
  50234. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  50235. }
  50236. }
  50237. else {
  50238. camera = scene.activeCamera;
  50239. if (camera) {
  50240. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  50241. }
  50242. }
  50243. // Prepare renderingManager
  50244. this._renderingManager.reset();
  50245. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  50246. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  50247. var sceneRenderId = scene.getRenderId();
  50248. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  50249. var mesh = currentRenderList[meshIndex];
  50250. if (mesh) {
  50251. if (!mesh.isReady()) {
  50252. // Reset _currentRefreshId
  50253. this.resetRefreshCounter();
  50254. continue;
  50255. }
  50256. mesh._preActivateForIntermediateRendering(sceneRenderId);
  50257. var isMasked = void 0;
  50258. if (!this.renderList && camera) {
  50259. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  50260. }
  50261. else {
  50262. isMasked = false;
  50263. }
  50264. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  50265. mesh._activate(sceneRenderId);
  50266. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  50267. var subMesh = mesh.subMeshes[subIndex];
  50268. scene._activeIndices.addCount(subMesh.indexCount, false);
  50269. this._renderingManager.dispatch(subMesh);
  50270. }
  50271. }
  50272. }
  50273. }
  50274. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  50275. var particleSystem = scene.particleSystems[particleIndex];
  50276. var emitter = particleSystem.emitter;
  50277. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  50278. continue;
  50279. }
  50280. if (currentRenderList.indexOf(emitter) >= 0) {
  50281. this._renderingManager.dispatchParticles(particleSystem);
  50282. }
  50283. }
  50284. if (this.isCube) {
  50285. for (var face = 0; face < 6; face++) {
  50286. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50287. scene.incrementRenderId();
  50288. scene.resetCachedMaterial();
  50289. }
  50290. }
  50291. else {
  50292. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  50293. }
  50294. this.onAfterUnbindObservable.notifyObservers(this);
  50295. if (scene.activeCamera) {
  50296. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  50297. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  50298. }
  50299. engine.setViewport(scene.activeCamera.viewport);
  50300. }
  50301. scene.resetCachedMaterial();
  50302. };
  50303. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  50304. var minimum = 128;
  50305. var x = renderDimension * scale;
  50306. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  50307. // Ensure we don't exceed the render dimension (while staying POT)
  50308. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  50309. };
  50310. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  50311. var _this = this;
  50312. var scene = this.getScene();
  50313. if (!scene) {
  50314. return;
  50315. }
  50316. var engine = scene.getEngine();
  50317. if (!this._texture) {
  50318. return;
  50319. }
  50320. // Bind
  50321. if (this._postProcessManager) {
  50322. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  50323. }
  50324. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  50325. if (this._texture) {
  50326. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  50327. }
  50328. }
  50329. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  50330. // Clear
  50331. if (this.onClearObservable.hasObservers()) {
  50332. this.onClearObservable.notifyObservers(engine);
  50333. }
  50334. else {
  50335. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  50336. }
  50337. if (!this._doNotChangeAspectRatio) {
  50338. scene.updateTransformMatrix(true);
  50339. }
  50340. // Render
  50341. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  50342. if (this._postProcessManager) {
  50343. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  50344. }
  50345. else if (useCameraPostProcess) {
  50346. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  50347. }
  50348. if (!this._doNotChangeAspectRatio) {
  50349. scene.updateTransformMatrix(true);
  50350. }
  50351. // Dump ?
  50352. if (dumpForDebug) {
  50353. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  50354. }
  50355. // Unbind
  50356. if (!this.isCube || faceIndex === 5) {
  50357. if (this.isCube) {
  50358. if (faceIndex === 5) {
  50359. engine.generateMipMapsForCubemap(this._texture);
  50360. }
  50361. }
  50362. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  50363. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  50364. });
  50365. }
  50366. else {
  50367. this.onAfterRenderObservable.notifyObservers(faceIndex);
  50368. }
  50369. };
  50370. /**
  50371. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  50372. * This allowed control for front to back rendering or reversly depending of the special needs.
  50373. *
  50374. * @param renderingGroupId The rendering group id corresponding to its index
  50375. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  50376. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  50377. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  50378. */
  50379. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  50380. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  50381. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  50382. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  50383. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  50384. };
  50385. /**
  50386. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  50387. *
  50388. * @param renderingGroupId The rendering group id corresponding to its index
  50389. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  50390. */
  50391. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  50392. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  50393. };
  50394. RenderTargetTexture.prototype.clone = function () {
  50395. var textureSize = this.getSize();
  50396. 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);
  50397. // Base texture
  50398. newTexture.hasAlpha = this.hasAlpha;
  50399. newTexture.level = this.level;
  50400. // RenderTarget Texture
  50401. newTexture.coordinatesMode = this.coordinatesMode;
  50402. if (this.renderList) {
  50403. newTexture.renderList = this.renderList.slice(0);
  50404. }
  50405. return newTexture;
  50406. };
  50407. RenderTargetTexture.prototype.serialize = function () {
  50408. if (!this.name) {
  50409. return null;
  50410. }
  50411. var serializationObject = _super.prototype.serialize.call(this);
  50412. serializationObject.renderTargetSize = this.getRenderSize();
  50413. serializationObject.renderList = [];
  50414. if (this.renderList) {
  50415. for (var index = 0; index < this.renderList.length; index++) {
  50416. serializationObject.renderList.push(this.renderList[index].id);
  50417. }
  50418. }
  50419. return serializationObject;
  50420. };
  50421. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  50422. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  50423. var objBuffer = this.getInternalTexture();
  50424. var scene = this.getScene();
  50425. if (objBuffer && scene) {
  50426. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  50427. }
  50428. };
  50429. RenderTargetTexture.prototype.dispose = function () {
  50430. if (this._postProcessManager) {
  50431. this._postProcessManager.dispose();
  50432. this._postProcessManager = null;
  50433. }
  50434. this.clearPostProcesses(true);
  50435. if (this._resizeObserver) {
  50436. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  50437. this._resizeObserver = null;
  50438. }
  50439. this.renderList = null;
  50440. // Remove from custom render targets
  50441. var scene = this.getScene();
  50442. if (!scene) {
  50443. return;
  50444. }
  50445. var index = scene.customRenderTargets.indexOf(this);
  50446. if (index >= 0) {
  50447. scene.customRenderTargets.splice(index, 1);
  50448. }
  50449. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  50450. var camera = _a[_i];
  50451. index = camera.customRenderTargets.indexOf(this);
  50452. if (index >= 0) {
  50453. camera.customRenderTargets.splice(index, 1);
  50454. }
  50455. }
  50456. _super.prototype.dispose.call(this);
  50457. };
  50458. RenderTargetTexture.prototype._rebuild = function () {
  50459. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  50460. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  50461. }
  50462. if (this._postProcessManager) {
  50463. this._postProcessManager._rebuild();
  50464. }
  50465. };
  50466. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  50467. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  50468. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  50469. return RenderTargetTexture;
  50470. }(BABYLON.Texture));
  50471. BABYLON.RenderTargetTexture = RenderTargetTexture;
  50472. })(BABYLON || (BABYLON = {}));
  50473. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  50474. var BABYLON;
  50475. (function (BABYLON) {
  50476. ;
  50477. var MultiRenderTarget = /** @class */ (function (_super) {
  50478. __extends(MultiRenderTarget, _super);
  50479. function MultiRenderTarget(name, size, count, scene, options) {
  50480. var _this = this;
  50481. options = options || {};
  50482. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  50483. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  50484. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  50485. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  50486. _this._engine = scene.getEngine();
  50487. if (!_this.isSupported) {
  50488. _this.dispose();
  50489. return;
  50490. }
  50491. var types = [];
  50492. var samplingModes = [];
  50493. for (var i = 0; i < count; i++) {
  50494. if (options.types && options.types[i]) {
  50495. types.push(options.types[i]);
  50496. }
  50497. else {
  50498. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  50499. }
  50500. if (options.samplingModes && options.samplingModes[i]) {
  50501. samplingModes.push(options.samplingModes[i]);
  50502. }
  50503. else {
  50504. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50505. }
  50506. }
  50507. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  50508. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  50509. _this._count = count;
  50510. _this._size = size;
  50511. _this._multiRenderTargetOptions = {
  50512. samplingModes: samplingModes,
  50513. generateMipMaps: generateMipMaps,
  50514. generateDepthBuffer: generateDepthBuffer,
  50515. generateStencilBuffer: generateStencilBuffer,
  50516. generateDepthTexture: generateDepthTexture,
  50517. types: types,
  50518. textureCount: count
  50519. };
  50520. _this._createInternalTextures();
  50521. _this._createTextures();
  50522. return _this;
  50523. }
  50524. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  50525. get: function () {
  50526. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  50527. },
  50528. enumerable: true,
  50529. configurable: true
  50530. });
  50531. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  50532. get: function () {
  50533. return this._textures;
  50534. },
  50535. enumerable: true,
  50536. configurable: true
  50537. });
  50538. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  50539. get: function () {
  50540. return this._textures[this._textures.length - 1];
  50541. },
  50542. enumerable: true,
  50543. configurable: true
  50544. });
  50545. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  50546. set: function (wrap) {
  50547. if (this._textures) {
  50548. for (var i = 0; i < this._textures.length; i++) {
  50549. this._textures[i].wrapU = wrap;
  50550. }
  50551. }
  50552. },
  50553. enumerable: true,
  50554. configurable: true
  50555. });
  50556. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  50557. set: function (wrap) {
  50558. if (this._textures) {
  50559. for (var i = 0; i < this._textures.length; i++) {
  50560. this._textures[i].wrapV = wrap;
  50561. }
  50562. }
  50563. },
  50564. enumerable: true,
  50565. configurable: true
  50566. });
  50567. MultiRenderTarget.prototype._rebuild = function () {
  50568. this.releaseInternalTextures();
  50569. this._createInternalTextures();
  50570. for (var i = 0; i < this._internalTextures.length; i++) {
  50571. var texture = this._textures[i];
  50572. texture._texture = this._internalTextures[i];
  50573. }
  50574. // Keeps references to frame buffer and stencil/depth buffer
  50575. this._texture = this._internalTextures[0];
  50576. };
  50577. MultiRenderTarget.prototype._createInternalTextures = function () {
  50578. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  50579. };
  50580. MultiRenderTarget.prototype._createTextures = function () {
  50581. this._textures = [];
  50582. for (var i = 0; i < this._internalTextures.length; i++) {
  50583. var texture = new BABYLON.Texture(null, this.getScene());
  50584. texture._texture = this._internalTextures[i];
  50585. this._textures.push(texture);
  50586. }
  50587. // Keeps references to frame buffer and stencil/depth buffer
  50588. this._texture = this._internalTextures[0];
  50589. };
  50590. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  50591. get: function () {
  50592. return this._samples;
  50593. },
  50594. set: function (value) {
  50595. if (this._samples === value) {
  50596. return;
  50597. }
  50598. for (var i = 0; i < this._internalTextures.length; i++) {
  50599. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  50600. }
  50601. },
  50602. enumerable: true,
  50603. configurable: true
  50604. });
  50605. MultiRenderTarget.prototype.resize = function (size) {
  50606. this.releaseInternalTextures();
  50607. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  50608. this._createInternalTextures();
  50609. };
  50610. MultiRenderTarget.prototype.dispose = function () {
  50611. this.releaseInternalTextures();
  50612. _super.prototype.dispose.call(this);
  50613. };
  50614. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  50615. if (!this._internalTextures) {
  50616. return;
  50617. }
  50618. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  50619. if (this._internalTextures[i] !== undefined) {
  50620. this._internalTextures[i].dispose();
  50621. this._internalTextures.splice(i, 1);
  50622. }
  50623. }
  50624. };
  50625. return MultiRenderTarget;
  50626. }(BABYLON.RenderTargetTexture));
  50627. BABYLON.MultiRenderTarget = MultiRenderTarget;
  50628. })(BABYLON || (BABYLON = {}));
  50629. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  50630. var BABYLON;
  50631. (function (BABYLON) {
  50632. var MirrorTexture = /** @class */ (function (_super) {
  50633. __extends(MirrorTexture, _super);
  50634. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  50635. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50636. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50637. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50638. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  50639. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  50640. _this._transformMatrix = BABYLON.Matrix.Zero();
  50641. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  50642. _this._adaptiveBlurKernel = 0;
  50643. _this._blurKernelX = 0;
  50644. _this._blurKernelY = 0;
  50645. _this._blurRatio = 1.0;
  50646. _this.ignoreCameraViewport = true;
  50647. _this.onBeforeRenderObservable.add(function () {
  50648. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  50649. _this._savedViewMatrix = scene.getViewMatrix();
  50650. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  50651. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  50652. scene.clipPlane = _this.mirrorPlane;
  50653. scene.getEngine().cullBackFaces = false;
  50654. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  50655. });
  50656. _this.onAfterRenderObservable.add(function () {
  50657. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  50658. scene.getEngine().cullBackFaces = true;
  50659. scene._mirroredCameraPosition = null;
  50660. delete scene.clipPlane;
  50661. });
  50662. return _this;
  50663. }
  50664. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  50665. get: function () {
  50666. return this._blurRatio;
  50667. },
  50668. set: function (value) {
  50669. if (this._blurRatio === value) {
  50670. return;
  50671. }
  50672. this._blurRatio = value;
  50673. this._preparePostProcesses();
  50674. },
  50675. enumerable: true,
  50676. configurable: true
  50677. });
  50678. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  50679. set: function (value) {
  50680. this._adaptiveBlurKernel = value;
  50681. this._autoComputeBlurKernel();
  50682. },
  50683. enumerable: true,
  50684. configurable: true
  50685. });
  50686. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  50687. set: function (value) {
  50688. this.blurKernelX = value;
  50689. this.blurKernelY = value;
  50690. },
  50691. enumerable: true,
  50692. configurable: true
  50693. });
  50694. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  50695. get: function () {
  50696. return this._blurKernelX;
  50697. },
  50698. set: function (value) {
  50699. if (this._blurKernelX === value) {
  50700. return;
  50701. }
  50702. this._blurKernelX = value;
  50703. this._preparePostProcesses();
  50704. },
  50705. enumerable: true,
  50706. configurable: true
  50707. });
  50708. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  50709. get: function () {
  50710. return this._blurKernelY;
  50711. },
  50712. set: function (value) {
  50713. if (this._blurKernelY === value) {
  50714. return;
  50715. }
  50716. this._blurKernelY = value;
  50717. this._preparePostProcesses();
  50718. },
  50719. enumerable: true,
  50720. configurable: true
  50721. });
  50722. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  50723. var engine = this.getScene().getEngine();
  50724. var dw = this.getRenderWidth() / engine.getRenderWidth();
  50725. var dh = this.getRenderHeight() / engine.getRenderHeight();
  50726. this.blurKernelX = this._adaptiveBlurKernel * dw;
  50727. this.blurKernelY = this._adaptiveBlurKernel * dh;
  50728. };
  50729. MirrorTexture.prototype._onRatioRescale = function () {
  50730. if (this._sizeRatio) {
  50731. this.resize(this._initialSizeParameter);
  50732. if (!this._adaptiveBlurKernel) {
  50733. this._preparePostProcesses();
  50734. }
  50735. }
  50736. if (this._adaptiveBlurKernel) {
  50737. this._autoComputeBlurKernel();
  50738. }
  50739. };
  50740. MirrorTexture.prototype._preparePostProcesses = function () {
  50741. this.clearPostProcesses(true);
  50742. if (this._blurKernelX && this._blurKernelY) {
  50743. var engine = this.getScene().getEngine();
  50744. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50745. 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);
  50746. this._blurX.autoClear = false;
  50747. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  50748. this._blurX.outputTexture = this._texture;
  50749. }
  50750. else {
  50751. this._blurX.alwaysForcePOT = true;
  50752. }
  50753. 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);
  50754. this._blurY.autoClear = false;
  50755. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  50756. this.addPostProcess(this._blurX);
  50757. this.addPostProcess(this._blurY);
  50758. }
  50759. else {
  50760. if (this._blurY) {
  50761. this.removePostProcess(this._blurY);
  50762. this._blurY.dispose();
  50763. this._blurY = null;
  50764. }
  50765. if (this._blurX) {
  50766. this.removePostProcess(this._blurX);
  50767. this._blurX.dispose();
  50768. this._blurX = null;
  50769. }
  50770. }
  50771. };
  50772. MirrorTexture.prototype.clone = function () {
  50773. var scene = this.getScene();
  50774. if (!scene) {
  50775. return this;
  50776. }
  50777. var textureSize = this.getSize();
  50778. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  50779. // Base texture
  50780. newTexture.hasAlpha = this.hasAlpha;
  50781. newTexture.level = this.level;
  50782. // Mirror Texture
  50783. newTexture.mirrorPlane = this.mirrorPlane.clone();
  50784. if (this.renderList) {
  50785. newTexture.renderList = this.renderList.slice(0);
  50786. }
  50787. return newTexture;
  50788. };
  50789. MirrorTexture.prototype.serialize = function () {
  50790. if (!this.name) {
  50791. return null;
  50792. }
  50793. var serializationObject = _super.prototype.serialize.call(this);
  50794. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  50795. return serializationObject;
  50796. };
  50797. return MirrorTexture;
  50798. }(BABYLON.RenderTargetTexture));
  50799. BABYLON.MirrorTexture = MirrorTexture;
  50800. })(BABYLON || (BABYLON = {}));
  50801. //# sourceMappingURL=babylon.mirrorTexture.js.map
  50802. var BABYLON;
  50803. (function (BABYLON) {
  50804. /**
  50805. * Creates a refraction texture used by refraction channel of the standard material.
  50806. * @param name the texture name
  50807. * @param size size of the underlying texture
  50808. * @param scene root scene
  50809. */
  50810. var RefractionTexture = /** @class */ (function (_super) {
  50811. __extends(RefractionTexture, _super);
  50812. function RefractionTexture(name, size, scene, generateMipMaps) {
  50813. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  50814. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  50815. _this.depth = 2.0;
  50816. _this.onBeforeRenderObservable.add(function () {
  50817. scene.clipPlane = _this.refractionPlane;
  50818. });
  50819. _this.onAfterRenderObservable.add(function () {
  50820. delete scene.clipPlane;
  50821. });
  50822. return _this;
  50823. }
  50824. RefractionTexture.prototype.clone = function () {
  50825. var scene = this.getScene();
  50826. if (!scene) {
  50827. return this;
  50828. }
  50829. var textureSize = this.getSize();
  50830. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  50831. // Base texture
  50832. newTexture.hasAlpha = this.hasAlpha;
  50833. newTexture.level = this.level;
  50834. // Refraction Texture
  50835. newTexture.refractionPlane = this.refractionPlane.clone();
  50836. if (this.renderList) {
  50837. newTexture.renderList = this.renderList.slice(0);
  50838. }
  50839. newTexture.depth = this.depth;
  50840. return newTexture;
  50841. };
  50842. RefractionTexture.prototype.serialize = function () {
  50843. if (!this.name) {
  50844. return null;
  50845. }
  50846. var serializationObject = _super.prototype.serialize.call(this);
  50847. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  50848. serializationObject.depth = this.depth;
  50849. return serializationObject;
  50850. };
  50851. return RefractionTexture;
  50852. }(BABYLON.RenderTargetTexture));
  50853. BABYLON.RefractionTexture = RefractionTexture;
  50854. })(BABYLON || (BABYLON = {}));
  50855. //# sourceMappingURL=babylon.refractionTexture.js.map
  50856. var BABYLON;
  50857. (function (BABYLON) {
  50858. var DynamicTexture = /** @class */ (function (_super) {
  50859. __extends(DynamicTexture, _super);
  50860. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  50861. if (scene === void 0) { scene = null; }
  50862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50863. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50864. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  50865. _this.name = name;
  50866. _this._engine = _this.getScene().getEngine();
  50867. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50868. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50869. _this._generateMipMaps = generateMipMaps;
  50870. if (options.getContext) {
  50871. _this._canvas = options;
  50872. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50873. }
  50874. else {
  50875. _this._canvas = document.createElement("canvas");
  50876. if (options.width) {
  50877. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50878. }
  50879. else {
  50880. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  50881. }
  50882. }
  50883. var textureSize = _this.getSize();
  50884. _this._canvas.width = textureSize.width;
  50885. _this._canvas.height = textureSize.height;
  50886. _this._context = _this._canvas.getContext("2d");
  50887. return _this;
  50888. }
  50889. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  50890. get: function () {
  50891. return true;
  50892. },
  50893. enumerable: true,
  50894. configurable: true
  50895. });
  50896. DynamicTexture.prototype._recreate = function (textureSize) {
  50897. this._canvas.width = textureSize.width;
  50898. this._canvas.height = textureSize.height;
  50899. this.releaseInternalTexture();
  50900. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  50901. };
  50902. DynamicTexture.prototype.scale = function (ratio) {
  50903. var textureSize = this.getSize();
  50904. textureSize.width *= ratio;
  50905. textureSize.height *= ratio;
  50906. this._recreate(textureSize);
  50907. };
  50908. DynamicTexture.prototype.scaleTo = function (width, height) {
  50909. var textureSize = this.getSize();
  50910. textureSize.width = width;
  50911. textureSize.height = height;
  50912. this._recreate(textureSize);
  50913. };
  50914. DynamicTexture.prototype.getContext = function () {
  50915. return this._context;
  50916. };
  50917. DynamicTexture.prototype.clear = function () {
  50918. var size = this.getSize();
  50919. this._context.fillRect(0, 0, size.width, size.height);
  50920. };
  50921. DynamicTexture.prototype.update = function (invertY) {
  50922. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  50923. };
  50924. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  50925. if (update === void 0) { update = true; }
  50926. var size = this.getSize();
  50927. if (clearColor) {
  50928. this._context.fillStyle = clearColor;
  50929. this._context.fillRect(0, 0, size.width, size.height);
  50930. }
  50931. this._context.font = font;
  50932. if (x === null || x === undefined) {
  50933. var textSize = this._context.measureText(text);
  50934. x = (size.width - textSize.width) / 2;
  50935. }
  50936. if (y === null || y === undefined) {
  50937. var fontSize = parseInt((font.replace(/\D/g, '')));
  50938. ;
  50939. y = (size.height / 2) + (fontSize / 3.65);
  50940. }
  50941. this._context.fillStyle = color;
  50942. this._context.fillText(text, x, y);
  50943. if (update) {
  50944. this.update(invertY);
  50945. }
  50946. };
  50947. DynamicTexture.prototype.clone = function () {
  50948. var scene = this.getScene();
  50949. if (!scene) {
  50950. return this;
  50951. }
  50952. var textureSize = this.getSize();
  50953. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  50954. // Base texture
  50955. newTexture.hasAlpha = this.hasAlpha;
  50956. newTexture.level = this.level;
  50957. // Dynamic Texture
  50958. newTexture.wrapU = this.wrapU;
  50959. newTexture.wrapV = this.wrapV;
  50960. return newTexture;
  50961. };
  50962. DynamicTexture.prototype._rebuild = function () {
  50963. this.update();
  50964. };
  50965. return DynamicTexture;
  50966. }(BABYLON.Texture));
  50967. BABYLON.DynamicTexture = DynamicTexture;
  50968. })(BABYLON || (BABYLON = {}));
  50969. //# sourceMappingURL=babylon.dynamicTexture.js.map
  50970. var BABYLON;
  50971. (function (BABYLON) {
  50972. var VideoTexture = /** @class */ (function (_super) {
  50973. __extends(VideoTexture, _super);
  50974. /**
  50975. * Creates a video texture.
  50976. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  50977. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  50978. * @param {BABYLON.Scene} scene is obviously the current scene.
  50979. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  50980. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  50981. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  50982. */
  50983. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  50984. if (generateMipMaps === void 0) { generateMipMaps = false; }
  50985. if (invertY === void 0) { invertY = false; }
  50986. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50987. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50988. _this._autoLaunch = true;
  50989. var urls = null;
  50990. _this.name = name;
  50991. if (urlsOrVideo instanceof HTMLVideoElement) {
  50992. _this.video = urlsOrVideo;
  50993. }
  50994. else {
  50995. urls = urlsOrVideo;
  50996. _this.video = document.createElement("video");
  50997. _this.video.autoplay = false;
  50998. _this.video.loop = true;
  50999. }
  51000. _this._engine = _this.getScene().getEngine();
  51001. _this._generateMipMaps = generateMipMaps;
  51002. _this._samplingMode = samplingMode;
  51003. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  51004. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51005. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51006. }
  51007. else {
  51008. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51009. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51010. _this._generateMipMaps = false;
  51011. }
  51012. if (urls) {
  51013. _this.video.addEventListener("canplay", function () {
  51014. _this._createTexture();
  51015. });
  51016. urls.forEach(function (url) {
  51017. var source = document.createElement("source");
  51018. source.src = url;
  51019. _this.video.appendChild(source);
  51020. });
  51021. }
  51022. else {
  51023. _this._createTexture();
  51024. }
  51025. _this._lastUpdate = BABYLON.Tools.Now;
  51026. return _this;
  51027. }
  51028. VideoTexture.prototype.__setTextureReady = function () {
  51029. if (this._texture) {
  51030. this._texture.isReady = true;
  51031. }
  51032. };
  51033. VideoTexture.prototype._createTexture = function () {
  51034. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  51035. if (this._autoLaunch) {
  51036. this._autoLaunch = false;
  51037. this.video.play();
  51038. }
  51039. this._setTextureReady = this.__setTextureReady.bind(this);
  51040. this.video.addEventListener("playing", this._setTextureReady);
  51041. };
  51042. VideoTexture.prototype._rebuild = function () {
  51043. this.update();
  51044. };
  51045. VideoTexture.prototype.update = function () {
  51046. var now = BABYLON.Tools.Now;
  51047. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  51048. return false;
  51049. }
  51050. this._lastUpdate = now;
  51051. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  51052. return true;
  51053. };
  51054. VideoTexture.prototype.dispose = function () {
  51055. _super.prototype.dispose.call(this);
  51056. this.video.removeEventListener("playing", this._setTextureReady);
  51057. };
  51058. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  51059. var video = document.createElement("video");
  51060. var constraintsDeviceId;
  51061. if (constraints && constraints.deviceId) {
  51062. constraintsDeviceId = {
  51063. exact: constraints.deviceId
  51064. };
  51065. }
  51066. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  51067. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  51068. if (navigator.getUserMedia) {
  51069. navigator.getUserMedia({
  51070. video: {
  51071. deviceId: constraintsDeviceId,
  51072. width: {
  51073. min: (constraints && constraints.minWidth) || 256,
  51074. max: (constraints && constraints.maxWidth) || 640
  51075. },
  51076. height: {
  51077. min: (constraints && constraints.minHeight) || 256,
  51078. max: (constraints && constraints.maxHeight) || 480
  51079. }
  51080. }
  51081. }, function (stream) {
  51082. if (video.mozSrcObject !== undefined) {
  51083. video.mozSrcObject = stream;
  51084. }
  51085. else {
  51086. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  51087. }
  51088. video.play();
  51089. if (onReady) {
  51090. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  51091. }
  51092. }, function (e) {
  51093. BABYLON.Tools.Error(e.name);
  51094. });
  51095. }
  51096. };
  51097. return VideoTexture;
  51098. }(BABYLON.Texture));
  51099. BABYLON.VideoTexture = VideoTexture;
  51100. })(BABYLON || (BABYLON = {}));
  51101. //# sourceMappingURL=babylon.videoTexture.js.map
  51102. var BABYLON;
  51103. (function (BABYLON) {
  51104. var RawTexture = /** @class */ (function (_super) {
  51105. __extends(RawTexture, _super);
  51106. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  51107. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51108. if (invertY === void 0) { invertY = false; }
  51109. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51110. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  51111. _this.format = format;
  51112. _this._engine = scene.getEngine();
  51113. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  51114. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51115. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51116. return _this;
  51117. }
  51118. RawTexture.prototype.update = function (data) {
  51119. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  51120. };
  51121. // Statics
  51122. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51123. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51124. if (invertY === void 0) { invertY = false; }
  51125. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51126. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  51127. };
  51128. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51129. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51130. if (invertY === void 0) { invertY = false; }
  51131. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51132. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51133. };
  51134. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51135. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51136. if (invertY === void 0) { invertY = false; }
  51137. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51138. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  51139. };
  51140. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51141. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51142. if (invertY === void 0) { invertY = false; }
  51143. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51144. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  51145. };
  51146. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  51147. if (generateMipMaps === void 0) { generateMipMaps = true; }
  51148. if (invertY === void 0) { invertY = false; }
  51149. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51150. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  51151. };
  51152. return RawTexture;
  51153. }(BABYLON.Texture));
  51154. BABYLON.RawTexture = RawTexture;
  51155. })(BABYLON || (BABYLON = {}));
  51156. //# sourceMappingURL=babylon.rawTexture.js.map
  51157. var BABYLON;
  51158. (function (BABYLON) {
  51159. var PostProcess = /** @class */ (function () {
  51160. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  51161. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  51162. if (defines === void 0) { defines = null; }
  51163. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51164. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  51165. if (blockCompilation === void 0) { blockCompilation = false; }
  51166. this.name = name;
  51167. this.width = -1;
  51168. this.height = -1;
  51169. this.autoClear = true;
  51170. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  51171. /*
  51172. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  51173. Can only be used on a single postprocess or on the last one of a chain.
  51174. */
  51175. this.enablePixelPerfectMode = false;
  51176. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  51177. this.alwaysForcePOT = false;
  51178. this.samples = 1;
  51179. this.adaptScaleToCurrentViewport = false;
  51180. this._reusable = false;
  51181. this._textures = new BABYLON.SmartArray(2);
  51182. this._currentRenderTextureInd = 0;
  51183. this._scaleRatio = new BABYLON.Vector2(1, 1);
  51184. this._texelSize = BABYLON.Vector2.Zero();
  51185. // Events
  51186. /**
  51187. * An event triggered when the postprocess is activated.
  51188. * @type {BABYLON.Observable}
  51189. */
  51190. this.onActivateObservable = new BABYLON.Observable();
  51191. /**
  51192. * An event triggered when the postprocess changes its size.
  51193. * @type {BABYLON.Observable}
  51194. */
  51195. this.onSizeChangedObservable = new BABYLON.Observable();
  51196. /**
  51197. * An event triggered when the postprocess applies its effect.
  51198. * @type {BABYLON.Observable}
  51199. */
  51200. this.onApplyObservable = new BABYLON.Observable();
  51201. /**
  51202. * An event triggered before rendering the postprocess
  51203. * @type {BABYLON.Observable}
  51204. */
  51205. this.onBeforeRenderObservable = new BABYLON.Observable();
  51206. /**
  51207. * An event triggered after rendering the postprocess
  51208. * @type {BABYLON.Observable}
  51209. */
  51210. this.onAfterRenderObservable = new BABYLON.Observable();
  51211. if (camera != null) {
  51212. this._camera = camera;
  51213. this._scene = camera.getScene();
  51214. camera.attachPostProcess(this);
  51215. this._engine = this._scene.getEngine();
  51216. this._scene.postProcesses.push(this);
  51217. }
  51218. else if (engine) {
  51219. this._engine = engine;
  51220. this._engine.postProcesses.push(this);
  51221. }
  51222. this._options = options;
  51223. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  51224. this._reusable = reusable || false;
  51225. this._textureType = textureType;
  51226. this._samplers = samplers || [];
  51227. this._samplers.push("textureSampler");
  51228. this._fragmentUrl = fragmentUrl;
  51229. this._vertexUrl = vertexUrl;
  51230. this._parameters = parameters || [];
  51231. this._parameters.push("scale");
  51232. this._indexParameters = indexParameters;
  51233. if (!blockCompilation) {
  51234. this.updateEffect(defines);
  51235. }
  51236. }
  51237. Object.defineProperty(PostProcess.prototype, "onActivate", {
  51238. set: function (callback) {
  51239. if (this._onActivateObserver) {
  51240. this.onActivateObservable.remove(this._onActivateObserver);
  51241. }
  51242. if (callback) {
  51243. this._onActivateObserver = this.onActivateObservable.add(callback);
  51244. }
  51245. },
  51246. enumerable: true,
  51247. configurable: true
  51248. });
  51249. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  51250. set: function (callback) {
  51251. if (this._onSizeChangedObserver) {
  51252. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  51253. }
  51254. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  51255. },
  51256. enumerable: true,
  51257. configurable: true
  51258. });
  51259. Object.defineProperty(PostProcess.prototype, "onApply", {
  51260. set: function (callback) {
  51261. if (this._onApplyObserver) {
  51262. this.onApplyObservable.remove(this._onApplyObserver);
  51263. }
  51264. this._onApplyObserver = this.onApplyObservable.add(callback);
  51265. },
  51266. enumerable: true,
  51267. configurable: true
  51268. });
  51269. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  51270. set: function (callback) {
  51271. if (this._onBeforeRenderObserver) {
  51272. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51273. }
  51274. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51275. },
  51276. enumerable: true,
  51277. configurable: true
  51278. });
  51279. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  51280. set: function (callback) {
  51281. if (this._onAfterRenderObserver) {
  51282. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51283. }
  51284. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51285. },
  51286. enumerable: true,
  51287. configurable: true
  51288. });
  51289. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  51290. get: function () {
  51291. return this._textures.data[this._currentRenderTextureInd];
  51292. },
  51293. set: function (value) {
  51294. this._forcedOutputTexture = value;
  51295. },
  51296. enumerable: true,
  51297. configurable: true
  51298. });
  51299. PostProcess.prototype.getCamera = function () {
  51300. return this._camera;
  51301. };
  51302. Object.defineProperty(PostProcess.prototype, "texelSize", {
  51303. get: function () {
  51304. if (this._shareOutputWithPostProcess) {
  51305. return this._shareOutputWithPostProcess.texelSize;
  51306. }
  51307. if (this._forcedOutputTexture) {
  51308. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  51309. }
  51310. return this._texelSize;
  51311. },
  51312. enumerable: true,
  51313. configurable: true
  51314. });
  51315. PostProcess.prototype.getEngine = function () {
  51316. return this._engine;
  51317. };
  51318. PostProcess.prototype.getEffect = function () {
  51319. return this._effect;
  51320. };
  51321. PostProcess.prototype.shareOutputWith = function (postProcess) {
  51322. this._disposeTextures();
  51323. this._shareOutputWithPostProcess = postProcess;
  51324. return this;
  51325. };
  51326. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  51327. if (defines === void 0) { defines = null; }
  51328. if (uniforms === void 0) { uniforms = null; }
  51329. if (samplers === void 0) { samplers = null; }
  51330. 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);
  51331. };
  51332. PostProcess.prototype.isReusable = function () {
  51333. return this._reusable;
  51334. };
  51335. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  51336. PostProcess.prototype.markTextureDirty = function () {
  51337. this.width = -1;
  51338. };
  51339. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  51340. var _this = this;
  51341. if (sourceTexture === void 0) { sourceTexture = null; }
  51342. camera = camera || this._camera;
  51343. var scene = camera.getScene();
  51344. var engine = scene.getEngine();
  51345. var maxSize = engine.getCaps().maxTextureSize;
  51346. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  51347. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  51348. var desiredWidth = (this._options.width || requiredWidth);
  51349. var desiredHeight = this._options.height || requiredHeight;
  51350. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  51351. if (this.adaptScaleToCurrentViewport) {
  51352. var currentViewport = engine.currentViewport;
  51353. if (currentViewport) {
  51354. desiredWidth *= currentViewport.width;
  51355. desiredHeight *= currentViewport.height;
  51356. }
  51357. }
  51358. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  51359. if (!this._options.width) {
  51360. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  51361. }
  51362. if (!this._options.height) {
  51363. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  51364. }
  51365. }
  51366. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  51367. if (this._textures.length > 0) {
  51368. for (var i = 0; i < this._textures.length; i++) {
  51369. this._engine._releaseTexture(this._textures.data[i]);
  51370. }
  51371. this._textures.reset();
  51372. }
  51373. this.width = desiredWidth;
  51374. this.height = desiredHeight;
  51375. var textureSize = { width: this.width, height: this.height };
  51376. var textureOptions = {
  51377. generateMipMaps: false,
  51378. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  51379. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  51380. samplingMode: this.renderTargetSamplingMode,
  51381. type: this._textureType
  51382. };
  51383. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51384. if (this._reusable) {
  51385. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  51386. }
  51387. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  51388. this.onSizeChangedObservable.notifyObservers(this);
  51389. }
  51390. this._textures.forEach(function (texture) {
  51391. if (texture.samples !== _this.samples) {
  51392. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  51393. }
  51394. });
  51395. }
  51396. var target;
  51397. if (this._shareOutputWithPostProcess) {
  51398. target = this._shareOutputWithPostProcess.outputTexture;
  51399. }
  51400. else if (this._forcedOutputTexture) {
  51401. target = this._forcedOutputTexture;
  51402. this.width = this._forcedOutputTexture.width;
  51403. this.height = this._forcedOutputTexture.height;
  51404. }
  51405. else {
  51406. target = this.outputTexture;
  51407. }
  51408. if (this.enablePixelPerfectMode) {
  51409. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  51410. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  51411. }
  51412. else {
  51413. this._scaleRatio.copyFromFloats(1, 1);
  51414. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  51415. }
  51416. this.onActivateObservable.notifyObservers(camera);
  51417. // Clear
  51418. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  51419. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  51420. }
  51421. if (this._reusable) {
  51422. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  51423. }
  51424. };
  51425. Object.defineProperty(PostProcess.prototype, "isSupported", {
  51426. get: function () {
  51427. return this._effect.isSupported;
  51428. },
  51429. enumerable: true,
  51430. configurable: true
  51431. });
  51432. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  51433. get: function () {
  51434. if (this._shareOutputWithPostProcess) {
  51435. return this._shareOutputWithPostProcess.aspectRatio;
  51436. }
  51437. if (this._forcedOutputTexture) {
  51438. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  51439. }
  51440. return this.width / this.height;
  51441. },
  51442. enumerable: true,
  51443. configurable: true
  51444. });
  51445. PostProcess.prototype.apply = function () {
  51446. // Check
  51447. if (!this._effect || !this._effect.isReady())
  51448. return null;
  51449. // States
  51450. this._engine.enableEffect(this._effect);
  51451. this._engine.setState(false);
  51452. this._engine.setDepthBuffer(false);
  51453. this._engine.setDepthWrite(false);
  51454. // Alpha
  51455. this._engine.setAlphaMode(this.alphaMode);
  51456. if (this.alphaConstants) {
  51457. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  51458. }
  51459. // Texture
  51460. var source;
  51461. if (this._shareOutputWithPostProcess) {
  51462. source = this._shareOutputWithPostProcess.outputTexture;
  51463. }
  51464. else if (this._forcedOutputTexture) {
  51465. source = this._forcedOutputTexture;
  51466. }
  51467. else {
  51468. source = this.outputTexture;
  51469. }
  51470. this._effect._bindTexture("textureSampler", source);
  51471. // Parameters
  51472. this._effect.setVector2("scale", this._scaleRatio);
  51473. this.onApplyObservable.notifyObservers(this._effect);
  51474. return this._effect;
  51475. };
  51476. PostProcess.prototype._disposeTextures = function () {
  51477. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  51478. return;
  51479. }
  51480. if (this._textures.length > 0) {
  51481. for (var i = 0; i < this._textures.length; i++) {
  51482. this._engine._releaseTexture(this._textures.data[i]);
  51483. }
  51484. }
  51485. this._textures.dispose();
  51486. };
  51487. PostProcess.prototype.dispose = function (camera) {
  51488. camera = camera || this._camera;
  51489. this._disposeTextures();
  51490. if (this._scene) {
  51491. var index_1 = this._scene.postProcesses.indexOf(this);
  51492. if (index_1 !== -1) {
  51493. this._scene.postProcesses.splice(index_1, 1);
  51494. }
  51495. }
  51496. else {
  51497. var index_2 = this._engine.postProcesses.indexOf(this);
  51498. if (index_2 !== -1) {
  51499. this._engine.postProcesses.splice(index_2, 1);
  51500. }
  51501. }
  51502. if (!camera) {
  51503. return;
  51504. }
  51505. camera.detachPostProcess(this);
  51506. var index = camera._postProcesses.indexOf(this);
  51507. if (index === 0 && camera._postProcesses.length > 0) {
  51508. this._camera._postProcesses[0].markTextureDirty();
  51509. }
  51510. this.onActivateObservable.clear();
  51511. this.onAfterRenderObservable.clear();
  51512. this.onApplyObservable.clear();
  51513. this.onBeforeRenderObservable.clear();
  51514. this.onSizeChangedObservable.clear();
  51515. };
  51516. return PostProcess;
  51517. }());
  51518. BABYLON.PostProcess = PostProcess;
  51519. })(BABYLON || (BABYLON = {}));
  51520. //# sourceMappingURL=babylon.postProcess.js.map
  51521. var BABYLON;
  51522. (function (BABYLON) {
  51523. var PassPostProcess = /** @class */ (function (_super) {
  51524. __extends(PassPostProcess, _super);
  51525. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51526. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51527. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  51528. }
  51529. return PassPostProcess;
  51530. }(BABYLON.PostProcess));
  51531. BABYLON.PassPostProcess = PassPostProcess;
  51532. })(BABYLON || (BABYLON = {}));
  51533. //# sourceMappingURL=babylon.passPostProcess.js.map
  51534. var BABYLON;
  51535. (function (BABYLON) {
  51536. var ShadowGenerator = /** @class */ (function () {
  51537. /**
  51538. * Creates a ShadowGenerator object.
  51539. * A ShadowGenerator is the required tool to use the shadows.
  51540. * Each light casting shadows needs to use its own ShadowGenerator.
  51541. * Required parameters :
  51542. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  51543. * - `light`: the light object generating the shadows.
  51544. * - `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.
  51545. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  51546. */
  51547. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  51548. // Members
  51549. this._bias = 0.00005;
  51550. this._blurBoxOffset = 1;
  51551. this._blurScale = 2;
  51552. this._blurKernel = 1;
  51553. this._useKernelBlur = false;
  51554. this._filter = ShadowGenerator.FILTER_NONE;
  51555. this._darkness = 0;
  51556. this._transparencyShadow = false;
  51557. /**
  51558. * Controls the extent to which the shadows fade out at the edge of the frustum
  51559. * Used only by directionals and spots
  51560. */
  51561. this.frustumEdgeFalloff = 0;
  51562. this.forceBackFacesOnly = false;
  51563. this._lightDirection = BABYLON.Vector3.Zero();
  51564. this._viewMatrix = BABYLON.Matrix.Zero();
  51565. this._projectionMatrix = BABYLON.Matrix.Zero();
  51566. this._transformMatrix = BABYLON.Matrix.Zero();
  51567. this._currentFaceIndex = 0;
  51568. this._currentFaceIndexCache = 0;
  51569. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  51570. this._mapSize = mapSize;
  51571. this._light = light;
  51572. this._scene = light.getScene();
  51573. light._shadowGenerator = this;
  51574. // Texture type fallback from float to int if not supported.
  51575. var caps = this._scene.getEngine().getCaps();
  51576. if (!useFullFloatFirst) {
  51577. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51578. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51579. }
  51580. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51581. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51582. }
  51583. else {
  51584. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51585. }
  51586. }
  51587. else {
  51588. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51589. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51590. }
  51591. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51592. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51593. }
  51594. else {
  51595. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51596. }
  51597. }
  51598. this._initializeGenerator();
  51599. }
  51600. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  51601. // Static
  51602. get: function () {
  51603. return ShadowGenerator._FILTER_NONE;
  51604. },
  51605. enumerable: true,
  51606. configurable: true
  51607. });
  51608. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  51609. get: function () {
  51610. return ShadowGenerator._FILTER_POISSONSAMPLING;
  51611. },
  51612. enumerable: true,
  51613. configurable: true
  51614. });
  51615. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  51616. get: function () {
  51617. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  51618. },
  51619. enumerable: true,
  51620. configurable: true
  51621. });
  51622. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  51623. get: function () {
  51624. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  51625. },
  51626. enumerable: true,
  51627. configurable: true
  51628. });
  51629. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  51630. get: function () {
  51631. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51632. },
  51633. enumerable: true,
  51634. configurable: true
  51635. });
  51636. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  51637. get: function () {
  51638. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51639. },
  51640. enumerable: true,
  51641. configurable: true
  51642. });
  51643. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  51644. get: function () {
  51645. return this._bias;
  51646. },
  51647. set: function (bias) {
  51648. this._bias = bias;
  51649. },
  51650. enumerable: true,
  51651. configurable: true
  51652. });
  51653. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  51654. get: function () {
  51655. return this._blurBoxOffset;
  51656. },
  51657. set: function (value) {
  51658. if (this._blurBoxOffset === value) {
  51659. return;
  51660. }
  51661. this._blurBoxOffset = value;
  51662. this._disposeBlurPostProcesses();
  51663. },
  51664. enumerable: true,
  51665. configurable: true
  51666. });
  51667. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  51668. get: function () {
  51669. return this._blurScale;
  51670. },
  51671. set: function (value) {
  51672. if (this._blurScale === value) {
  51673. return;
  51674. }
  51675. this._blurScale = value;
  51676. this._disposeBlurPostProcesses();
  51677. },
  51678. enumerable: true,
  51679. configurable: true
  51680. });
  51681. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  51682. get: function () {
  51683. return this._blurKernel;
  51684. },
  51685. set: function (value) {
  51686. if (this._blurKernel === value) {
  51687. return;
  51688. }
  51689. this._blurKernel = value;
  51690. this._disposeBlurPostProcesses();
  51691. },
  51692. enumerable: true,
  51693. configurable: true
  51694. });
  51695. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  51696. get: function () {
  51697. return this._useKernelBlur;
  51698. },
  51699. set: function (value) {
  51700. if (this._useKernelBlur === value) {
  51701. return;
  51702. }
  51703. this._useKernelBlur = value;
  51704. this._disposeBlurPostProcesses();
  51705. },
  51706. enumerable: true,
  51707. configurable: true
  51708. });
  51709. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  51710. get: function () {
  51711. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  51712. },
  51713. set: function (value) {
  51714. this._depthScale = value;
  51715. },
  51716. enumerable: true,
  51717. configurable: true
  51718. });
  51719. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  51720. get: function () {
  51721. return this._filter;
  51722. },
  51723. set: function (value) {
  51724. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  51725. if (this._light.needCube()) {
  51726. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51727. this.useExponentialShadowMap = true;
  51728. return;
  51729. }
  51730. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51731. this.useCloseExponentialShadowMap = true;
  51732. return;
  51733. }
  51734. }
  51735. if (this._filter === value) {
  51736. return;
  51737. }
  51738. this._filter = value;
  51739. this._disposeBlurPostProcesses();
  51740. this._applyFilterValues();
  51741. this._light._markMeshesAsLightDirty();
  51742. },
  51743. enumerable: true,
  51744. configurable: true
  51745. });
  51746. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  51747. get: function () {
  51748. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  51749. },
  51750. set: function (value) {
  51751. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  51752. return;
  51753. }
  51754. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  51755. },
  51756. enumerable: true,
  51757. configurable: true
  51758. });
  51759. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  51760. get: function () {
  51761. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51762. return this.useExponentialShadowMap;
  51763. },
  51764. set: function (value) {
  51765. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51766. this.useExponentialShadowMap = value;
  51767. },
  51768. enumerable: true,
  51769. configurable: true
  51770. });
  51771. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  51772. get: function () {
  51773. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51774. return this.useBlurExponentialShadowMap;
  51775. },
  51776. set: function (value) {
  51777. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51778. this.useBlurExponentialShadowMap = value;
  51779. },
  51780. enumerable: true,
  51781. configurable: true
  51782. });
  51783. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  51784. get: function () {
  51785. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  51786. },
  51787. set: function (value) {
  51788. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  51789. return;
  51790. }
  51791. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51792. },
  51793. enumerable: true,
  51794. configurable: true
  51795. });
  51796. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  51797. get: function () {
  51798. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  51799. },
  51800. set: function (value) {
  51801. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51802. return;
  51803. }
  51804. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51805. },
  51806. enumerable: true,
  51807. configurable: true
  51808. });
  51809. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  51810. get: function () {
  51811. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51812. },
  51813. set: function (value) {
  51814. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  51815. return;
  51816. }
  51817. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51818. },
  51819. enumerable: true,
  51820. configurable: true
  51821. });
  51822. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  51823. get: function () {
  51824. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51825. },
  51826. set: function (value) {
  51827. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51828. return;
  51829. }
  51830. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51831. },
  51832. enumerable: true,
  51833. configurable: true
  51834. });
  51835. /**
  51836. * Returns the darkness value (float).
  51837. */
  51838. ShadowGenerator.prototype.getDarkness = function () {
  51839. return this._darkness;
  51840. };
  51841. /**
  51842. * Sets the ShadowGenerator darkness value (float <= 1.0).
  51843. * Returns the ShadowGenerator.
  51844. */
  51845. ShadowGenerator.prototype.setDarkness = function (darkness) {
  51846. if (darkness >= 1.0)
  51847. this._darkness = 1.0;
  51848. else if (darkness <= 0.0)
  51849. this._darkness = 0.0;
  51850. else
  51851. this._darkness = darkness;
  51852. return this;
  51853. };
  51854. /**
  51855. * Sets the ability to have transparent shadow (boolean).
  51856. * Returns the ShadowGenerator.
  51857. */
  51858. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  51859. this._transparencyShadow = hasShadow;
  51860. return this;
  51861. };
  51862. /**
  51863. * Returns a RenderTargetTexture object : the shadow map texture.
  51864. */
  51865. ShadowGenerator.prototype.getShadowMap = function () {
  51866. return this._shadowMap;
  51867. };
  51868. /**
  51869. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  51870. */
  51871. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  51872. if (this._shadowMap2) {
  51873. return this._shadowMap2;
  51874. }
  51875. return this._shadowMap;
  51876. };
  51877. /**
  51878. * Helper function to add a mesh and its descendants to the list of shadow casters
  51879. * @param mesh Mesh to add
  51880. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  51881. */
  51882. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  51883. if (includeDescendants === void 0) { includeDescendants = true; }
  51884. if (!this._shadowMap) {
  51885. return this;
  51886. }
  51887. if (!this._shadowMap.renderList) {
  51888. this._shadowMap.renderList = [];
  51889. }
  51890. this._shadowMap.renderList.push(mesh);
  51891. if (includeDescendants) {
  51892. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  51893. }
  51894. return this;
  51895. var _a;
  51896. };
  51897. /**
  51898. * Helper function to remove a mesh and its descendants from the list of shadow casters
  51899. * @param mesh Mesh to remove
  51900. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  51901. */
  51902. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  51903. if (includeDescendants === void 0) { includeDescendants = true; }
  51904. if (!this._shadowMap || !this._shadowMap.renderList) {
  51905. return this;
  51906. }
  51907. var index = this._shadowMap.renderList.indexOf(mesh);
  51908. if (index !== -1) {
  51909. this._shadowMap.renderList.splice(index, 1);
  51910. }
  51911. if (includeDescendants) {
  51912. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  51913. var child = _a[_i];
  51914. this.removeShadowCaster(child);
  51915. }
  51916. }
  51917. return this;
  51918. };
  51919. /**
  51920. * Returns the associated light object.
  51921. */
  51922. ShadowGenerator.prototype.getLight = function () {
  51923. return this._light;
  51924. };
  51925. ShadowGenerator.prototype._initializeGenerator = function () {
  51926. this._light._markMeshesAsLightDirty();
  51927. this._initializeShadowMap();
  51928. };
  51929. ShadowGenerator.prototype._initializeShadowMap = function () {
  51930. var _this = this;
  51931. // Render target
  51932. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  51933. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51934. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51935. this._shadowMap.anisotropicFilteringLevel = 1;
  51936. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51937. this._shadowMap.renderParticles = false;
  51938. this._shadowMap.ignoreCameraViewport = true;
  51939. // Record Face Index before render.
  51940. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  51941. _this._currentFaceIndex = faceIndex;
  51942. });
  51943. // Custom render function.
  51944. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  51945. // Blur if required afer render.
  51946. this._shadowMap.onAfterUnbindObservable.add(function () {
  51947. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  51948. return;
  51949. }
  51950. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  51951. _this._initializeBlurRTTAndPostProcesses();
  51952. }
  51953. var shadowMap = _this.getShadowMapForRendering();
  51954. if (shadowMap) {
  51955. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  51956. }
  51957. });
  51958. // Clear according to the chosen filter.
  51959. this._shadowMap.onClearObservable.add(function (engine) {
  51960. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  51961. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  51962. }
  51963. else {
  51964. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51965. }
  51966. });
  51967. };
  51968. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  51969. var _this = this;
  51970. var engine = this._scene.getEngine();
  51971. var targetSize = this._mapSize / this.blurScale;
  51972. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  51973. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  51974. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51975. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51976. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51977. }
  51978. if (this.useKernelBlur) {
  51979. 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);
  51980. this._kernelBlurXPostprocess.width = targetSize;
  51981. this._kernelBlurXPostprocess.height = targetSize;
  51982. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  51983. effect.setTexture("textureSampler", _this._shadowMap);
  51984. });
  51985. 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);
  51986. this._kernelBlurXPostprocess.autoClear = false;
  51987. this._kernelBlurYPostprocess.autoClear = false;
  51988. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51989. this._kernelBlurXPostprocess.packedFloat = true;
  51990. this._kernelBlurYPostprocess.packedFloat = true;
  51991. }
  51992. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  51993. }
  51994. else {
  51995. 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);
  51996. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  51997. effect.setFloat2("screenSize", targetSize, targetSize);
  51998. effect.setTexture("textureSampler", _this._shadowMap);
  51999. });
  52000. this._boxBlurPostprocess.autoClear = false;
  52001. this._blurPostProcesses = [this._boxBlurPostprocess];
  52002. }
  52003. };
  52004. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  52005. var index;
  52006. var engine = this._scene.getEngine();
  52007. if (depthOnlySubMeshes.length) {
  52008. engine.setColorWrite(false);
  52009. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  52010. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  52011. }
  52012. engine.setColorWrite(true);
  52013. }
  52014. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52015. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  52016. }
  52017. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52018. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  52019. }
  52020. if (this._transparencyShadow) {
  52021. for (index = 0; index < transparentSubMeshes.length; index++) {
  52022. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  52023. }
  52024. }
  52025. };
  52026. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  52027. var _this = this;
  52028. var mesh = subMesh.getRenderingMesh();
  52029. var scene = this._scene;
  52030. var engine = scene.getEngine();
  52031. var material = subMesh.getMaterial();
  52032. if (!material) {
  52033. return;
  52034. }
  52035. // Culling
  52036. engine.setState(material.backFaceCulling);
  52037. // Managing instances
  52038. var batch = mesh._getInstancesRenderList(subMesh._id);
  52039. if (batch.mustReturn) {
  52040. return;
  52041. }
  52042. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52043. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  52044. engine.enableEffect(this._effect);
  52045. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52046. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  52047. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  52048. this._effect.setVector3("lightPosition", this.getLight().position);
  52049. if (scene.activeCamera) {
  52050. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  52051. }
  52052. // Alpha test
  52053. if (material && material.needAlphaTesting()) {
  52054. var alphaTexture = material.getAlphaTestTexture();
  52055. if (alphaTexture) {
  52056. this._effect.setTexture("diffuseSampler", alphaTexture);
  52057. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  52058. }
  52059. }
  52060. // Bones
  52061. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52062. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  52063. }
  52064. if (this.forceBackFacesOnly) {
  52065. engine.setState(true, 0, false, true);
  52066. }
  52067. // Draw
  52068. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52069. if (this.forceBackFacesOnly) {
  52070. engine.setState(true, 0, false, false);
  52071. }
  52072. }
  52073. else {
  52074. // Need to reset refresh rate of the shadowMap
  52075. if (this._shadowMap) {
  52076. this._shadowMap.resetRefreshCounter();
  52077. }
  52078. }
  52079. };
  52080. ShadowGenerator.prototype._applyFilterValues = function () {
  52081. if (!this._shadowMap) {
  52082. return;
  52083. }
  52084. if (this.filter === ShadowGenerator.FILTER_NONE) {
  52085. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  52086. }
  52087. else {
  52088. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52089. }
  52090. };
  52091. /**
  52092. * Force shader compilation including textures ready check
  52093. */
  52094. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  52095. var _this = this;
  52096. var shadowMap = this.getShadowMap();
  52097. if (!shadowMap) {
  52098. return;
  52099. }
  52100. var subMeshes = new Array();
  52101. var currentIndex = 0;
  52102. var renderList = shadowMap.renderList;
  52103. if (!renderList) {
  52104. return;
  52105. }
  52106. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  52107. var mesh = renderList_1[_i];
  52108. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  52109. }
  52110. var checkReady = function () {
  52111. if (!_this._scene || !_this._scene.getEngine()) {
  52112. return;
  52113. }
  52114. while (_this.isReady(subMeshes[currentIndex], options ? options.useInstances : false)) {
  52115. currentIndex++;
  52116. if (currentIndex >= subMeshes.length) {
  52117. if (onCompiled) {
  52118. onCompiled(_this);
  52119. }
  52120. return;
  52121. }
  52122. }
  52123. setTimeout(checkReady, 16);
  52124. };
  52125. if (subMeshes.length > 0) {
  52126. checkReady();
  52127. }
  52128. };
  52129. /**
  52130. * Boolean : true when the ShadowGenerator is finally computed.
  52131. */
  52132. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  52133. var defines = [];
  52134. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  52135. defines.push("#define FLOAT");
  52136. }
  52137. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52138. defines.push("#define ESM");
  52139. }
  52140. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52141. var mesh = subMesh.getMesh();
  52142. var material = subMesh.getMaterial();
  52143. // Alpha test
  52144. if (material && material.needAlphaTesting()) {
  52145. var alphaTexture = material.getAlphaTestTexture();
  52146. if (alphaTexture) {
  52147. defines.push("#define ALPHATEST");
  52148. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52149. attribs.push(BABYLON.VertexBuffer.UVKind);
  52150. defines.push("#define UV1");
  52151. }
  52152. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52153. if (alphaTexture.coordinatesIndex === 1) {
  52154. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52155. defines.push("#define UV2");
  52156. }
  52157. }
  52158. }
  52159. }
  52160. // Bones
  52161. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52162. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52163. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52164. if (mesh.numBoneInfluencers > 4) {
  52165. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52166. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52167. }
  52168. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52169. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52170. }
  52171. else {
  52172. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52173. }
  52174. // Instances
  52175. if (useInstances) {
  52176. defines.push("#define INSTANCES");
  52177. attribs.push("world0");
  52178. attribs.push("world1");
  52179. attribs.push("world2");
  52180. attribs.push("world3");
  52181. }
  52182. // Get correct effect
  52183. var join = defines.join("\n");
  52184. if (this._cachedDefines !== join) {
  52185. this._cachedDefines = join;
  52186. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  52187. }
  52188. return this._effect.isReady();
  52189. };
  52190. /**
  52191. * This creates the defines related to the standard BJS materials.
  52192. */
  52193. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  52194. var scene = this._scene;
  52195. var light = this._light;
  52196. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52197. return;
  52198. }
  52199. defines["SHADOW" + lightIndex] = true;
  52200. if (this.usePoissonSampling) {
  52201. defines["SHADOWPCF" + lightIndex] = true;
  52202. }
  52203. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  52204. defines["SHADOWESM" + lightIndex] = true;
  52205. }
  52206. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  52207. defines["SHADOWCLOSEESM" + lightIndex] = true;
  52208. }
  52209. if (light.needCube()) {
  52210. defines["SHADOWCUBE" + lightIndex] = true;
  52211. }
  52212. };
  52213. /**
  52214. * This binds shadow lights related to the standard BJS materials.
  52215. * It implies the unifroms available on the materials are the standard BJS ones.
  52216. */
  52217. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  52218. var light = this._light;
  52219. var scene = this._scene;
  52220. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  52221. return;
  52222. }
  52223. var camera = scene.activeCamera;
  52224. if (!camera) {
  52225. return;
  52226. }
  52227. var shadowMap = this.getShadowMap();
  52228. if (!shadowMap) {
  52229. return;
  52230. }
  52231. if (!light.needCube()) {
  52232. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  52233. }
  52234. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  52235. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  52236. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  52237. };
  52238. // Methods
  52239. /**
  52240. * Returns a Matrix object : the updated transformation matrix.
  52241. */
  52242. ShadowGenerator.prototype.getTransformMatrix = function () {
  52243. var scene = this._scene;
  52244. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  52245. return this._transformMatrix;
  52246. }
  52247. this._currentRenderID = scene.getRenderId();
  52248. this._currentFaceIndexCache = this._currentFaceIndex;
  52249. var lightPosition = this._light.position;
  52250. if (this._light.computeTransformedInformation()) {
  52251. lightPosition = this._light.transformedPosition;
  52252. }
  52253. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  52254. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  52255. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  52256. }
  52257. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  52258. this._cachedPosition = lightPosition.clone();
  52259. this._cachedDirection = this._lightDirection.clone();
  52260. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  52261. var shadowMap = this.getShadowMap();
  52262. if (shadowMap) {
  52263. var renderList = shadowMap.renderList;
  52264. if (renderList) {
  52265. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  52266. }
  52267. }
  52268. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  52269. }
  52270. return this._transformMatrix;
  52271. };
  52272. ShadowGenerator.prototype.recreateShadowMap = function () {
  52273. var shadowMap = this._shadowMap;
  52274. if (!shadowMap) {
  52275. return;
  52276. }
  52277. // Track render list.
  52278. var renderList = shadowMap.renderList;
  52279. // Clean up existing data.
  52280. this._disposeRTTandPostProcesses();
  52281. // Reinitializes.
  52282. this._initializeGenerator();
  52283. // Reaffect the filter to ensure a correct fallback if necessary.
  52284. this.filter = this.filter;
  52285. // Reaffect the filter.
  52286. this._applyFilterValues();
  52287. // Reaffect Render List.
  52288. this._shadowMap.renderList = renderList;
  52289. };
  52290. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  52291. if (this._shadowMap2) {
  52292. this._shadowMap2.dispose();
  52293. this._shadowMap2 = null;
  52294. }
  52295. if (this._downSamplePostprocess) {
  52296. this._downSamplePostprocess.dispose();
  52297. this._downSamplePostprocess = null;
  52298. }
  52299. if (this._boxBlurPostprocess) {
  52300. this._boxBlurPostprocess.dispose();
  52301. this._boxBlurPostprocess = null;
  52302. }
  52303. if (this._kernelBlurXPostprocess) {
  52304. this._kernelBlurXPostprocess.dispose();
  52305. this._kernelBlurXPostprocess = null;
  52306. }
  52307. if (this._kernelBlurYPostprocess) {
  52308. this._kernelBlurYPostprocess.dispose();
  52309. this._kernelBlurYPostprocess = null;
  52310. }
  52311. this._blurPostProcesses = [];
  52312. };
  52313. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  52314. if (this._shadowMap) {
  52315. this._shadowMap.dispose();
  52316. this._shadowMap = null;
  52317. }
  52318. this._disposeBlurPostProcesses();
  52319. };
  52320. /**
  52321. * Disposes the ShadowGenerator.
  52322. * Returns nothing.
  52323. */
  52324. ShadowGenerator.prototype.dispose = function () {
  52325. this._disposeRTTandPostProcesses();
  52326. if (this._light) {
  52327. this._light._shadowGenerator = null;
  52328. this._light._markMeshesAsLightDirty();
  52329. }
  52330. };
  52331. /**
  52332. * Serializes the ShadowGenerator and returns a serializationObject.
  52333. */
  52334. ShadowGenerator.prototype.serialize = function () {
  52335. var serializationObject = {};
  52336. var shadowMap = this.getShadowMap();
  52337. if (!shadowMap) {
  52338. return serializationObject;
  52339. }
  52340. serializationObject.lightId = this._light.id;
  52341. serializationObject.mapSize = shadowMap.getRenderSize();
  52342. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  52343. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  52344. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52345. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  52346. serializationObject.usePoissonSampling = this.usePoissonSampling;
  52347. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  52348. serializationObject.depthScale = this.depthScale;
  52349. serializationObject.darkness = this.getDarkness();
  52350. serializationObject.blurBoxOffset = this.blurBoxOffset;
  52351. serializationObject.blurKernel = this.blurKernel;
  52352. serializationObject.blurScale = this.blurScale;
  52353. serializationObject.useKernelBlur = this.useKernelBlur;
  52354. serializationObject.transparencyShadow = this._transparencyShadow;
  52355. serializationObject.renderList = [];
  52356. if (shadowMap.renderList) {
  52357. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  52358. var mesh = shadowMap.renderList[meshIndex];
  52359. serializationObject.renderList.push(mesh.id);
  52360. }
  52361. }
  52362. return serializationObject;
  52363. };
  52364. /**
  52365. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  52366. */
  52367. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  52368. //casting to point light, as light is missing the position attr and typescript complains.
  52369. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  52370. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  52371. var shadowMap = shadowGenerator.getShadowMap();
  52372. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  52373. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  52374. meshes.forEach(function (mesh) {
  52375. if (!shadowMap) {
  52376. return;
  52377. }
  52378. if (!shadowMap.renderList) {
  52379. shadowMap.renderList = [];
  52380. }
  52381. shadowMap.renderList.push(mesh);
  52382. });
  52383. }
  52384. if (parsedShadowGenerator.usePoissonSampling) {
  52385. shadowGenerator.usePoissonSampling = true;
  52386. }
  52387. else if (parsedShadowGenerator.useExponentialShadowMap) {
  52388. shadowGenerator.useExponentialShadowMap = true;
  52389. }
  52390. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  52391. shadowGenerator.useBlurExponentialShadowMap = true;
  52392. }
  52393. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  52394. shadowGenerator.useCloseExponentialShadowMap = true;
  52395. }
  52396. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  52397. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  52398. }
  52399. else if (parsedShadowGenerator.useVarianceShadowMap) {
  52400. shadowGenerator.useExponentialShadowMap = true;
  52401. }
  52402. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  52403. shadowGenerator.useBlurExponentialShadowMap = true;
  52404. }
  52405. if (parsedShadowGenerator.depthScale) {
  52406. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  52407. }
  52408. if (parsedShadowGenerator.blurScale) {
  52409. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  52410. }
  52411. if (parsedShadowGenerator.blurBoxOffset) {
  52412. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  52413. }
  52414. if (parsedShadowGenerator.useKernelBlur) {
  52415. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  52416. }
  52417. if (parsedShadowGenerator.blurKernel) {
  52418. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  52419. }
  52420. if (parsedShadowGenerator.bias !== undefined) {
  52421. shadowGenerator.bias = parsedShadowGenerator.bias;
  52422. }
  52423. if (parsedShadowGenerator.darkness) {
  52424. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  52425. }
  52426. if (parsedShadowGenerator.transparencyShadow) {
  52427. shadowGenerator.setTransparencyShadow(true);
  52428. }
  52429. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  52430. return shadowGenerator;
  52431. };
  52432. ShadowGenerator._FILTER_NONE = 0;
  52433. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  52434. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  52435. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  52436. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  52437. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  52438. return ShadowGenerator;
  52439. }());
  52440. BABYLON.ShadowGenerator = ShadowGenerator;
  52441. })(BABYLON || (BABYLON = {}));
  52442. //# sourceMappingURL=babylon.shadowGenerator.js.map
  52443. var BABYLON;
  52444. (function (BABYLON) {
  52445. var DefaultLoadingScreen = /** @class */ (function () {
  52446. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  52447. if (_loadingText === void 0) { _loadingText = ""; }
  52448. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  52449. var _this = this;
  52450. this._renderingCanvas = _renderingCanvas;
  52451. this._loadingText = _loadingText;
  52452. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  52453. // Resize
  52454. this._resizeLoadingUI = function () {
  52455. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  52456. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  52457. if (!_this._loadingDiv) {
  52458. return;
  52459. }
  52460. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  52461. _this._loadingDiv.style.left = canvasRect.left + "px";
  52462. _this._loadingDiv.style.top = canvasRect.top + "px";
  52463. _this._loadingDiv.style.width = canvasRect.width + "px";
  52464. _this._loadingDiv.style.height = canvasRect.height + "px";
  52465. };
  52466. }
  52467. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  52468. if (this._loadingDiv) {
  52469. // Do not add a loading screen if there is already one
  52470. return;
  52471. }
  52472. this._loadingDiv = document.createElement("div");
  52473. this._loadingDiv.id = "babylonjsLoadingDiv";
  52474. this._loadingDiv.style.opacity = "0";
  52475. this._loadingDiv.style.transition = "opacity 1.5s ease";
  52476. this._loadingDiv.style.pointerEvents = "none";
  52477. // Loading text
  52478. this._loadingTextDiv = document.createElement("div");
  52479. this._loadingTextDiv.style.position = "absolute";
  52480. this._loadingTextDiv.style.left = "0";
  52481. this._loadingTextDiv.style.top = "50%";
  52482. this._loadingTextDiv.style.marginTop = "80px";
  52483. this._loadingTextDiv.style.width = "100%";
  52484. this._loadingTextDiv.style.height = "20px";
  52485. this._loadingTextDiv.style.fontFamily = "Arial";
  52486. this._loadingTextDiv.style.fontSize = "14px";
  52487. this._loadingTextDiv.style.color = "white";
  52488. this._loadingTextDiv.style.textAlign = "center";
  52489. this._loadingTextDiv.innerHTML = "Loading";
  52490. this._loadingDiv.appendChild(this._loadingTextDiv);
  52491. //set the predefined text
  52492. this._loadingTextDiv.innerHTML = this._loadingText;
  52493. // Generating keyframes
  52494. var style = document.createElement('style');
  52495. style.type = 'text/css';
  52496. 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 }";
  52497. style.innerHTML = keyFrames;
  52498. document.getElementsByTagName('head')[0].appendChild(style);
  52499. // Loading img
  52500. var imgBack = new Image();
  52501. 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";
  52502. imgBack.style.position = "absolute";
  52503. imgBack.style.left = "50%";
  52504. imgBack.style.top = "50%";
  52505. imgBack.style.marginLeft = "-60px";
  52506. imgBack.style.marginTop = "-60px";
  52507. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  52508. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  52509. imgBack.style.transformOrigin = "50% 50%";
  52510. imgBack.style.webkitTransformOrigin = "50% 50%";
  52511. this._loadingDiv.appendChild(imgBack);
  52512. this._resizeLoadingUI();
  52513. window.addEventListener("resize", this._resizeLoadingUI);
  52514. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52515. document.body.appendChild(this._loadingDiv);
  52516. this._loadingDiv.style.opacity = "1";
  52517. };
  52518. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  52519. var _this = this;
  52520. if (!this._loadingDiv) {
  52521. return;
  52522. }
  52523. var onTransitionEnd = function () {
  52524. if (!_this._loadingDiv) {
  52525. return;
  52526. }
  52527. document.body.removeChild(_this._loadingDiv);
  52528. window.removeEventListener("resize", _this._resizeLoadingUI);
  52529. _this._loadingDiv = null;
  52530. };
  52531. this._loadingDiv.style.opacity = "0";
  52532. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  52533. };
  52534. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  52535. set: function (text) {
  52536. this._loadingText = text;
  52537. if (this._loadingTextDiv) {
  52538. this._loadingTextDiv.innerHTML = this._loadingText;
  52539. }
  52540. },
  52541. enumerable: true,
  52542. configurable: true
  52543. });
  52544. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  52545. get: function () {
  52546. return this._loadingDivBackgroundColor;
  52547. },
  52548. set: function (color) {
  52549. this._loadingDivBackgroundColor = color;
  52550. if (!this._loadingDiv) {
  52551. return;
  52552. }
  52553. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52554. },
  52555. enumerable: true,
  52556. configurable: true
  52557. });
  52558. return DefaultLoadingScreen;
  52559. }());
  52560. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  52561. })(BABYLON || (BABYLON = {}));
  52562. //# sourceMappingURL=babylon.loadingScreen.js.map
  52563. var BABYLON;
  52564. (function (BABYLON) {
  52565. var SceneLoader = /** @class */ (function () {
  52566. function SceneLoader() {
  52567. }
  52568. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  52569. get: function () {
  52570. return 0;
  52571. },
  52572. enumerable: true,
  52573. configurable: true
  52574. });
  52575. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  52576. get: function () {
  52577. return 1;
  52578. },
  52579. enumerable: true,
  52580. configurable: true
  52581. });
  52582. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  52583. get: function () {
  52584. return 2;
  52585. },
  52586. enumerable: true,
  52587. configurable: true
  52588. });
  52589. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  52590. get: function () {
  52591. return 3;
  52592. },
  52593. enumerable: true,
  52594. configurable: true
  52595. });
  52596. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  52597. get: function () {
  52598. return SceneLoader._ForceFullSceneLoadingForIncremental;
  52599. },
  52600. set: function (value) {
  52601. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  52602. },
  52603. enumerable: true,
  52604. configurable: true
  52605. });
  52606. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  52607. get: function () {
  52608. return SceneLoader._ShowLoadingScreen;
  52609. },
  52610. set: function (value) {
  52611. SceneLoader._ShowLoadingScreen = value;
  52612. },
  52613. enumerable: true,
  52614. configurable: true
  52615. });
  52616. Object.defineProperty(SceneLoader, "loggingLevel", {
  52617. get: function () {
  52618. return SceneLoader._loggingLevel;
  52619. },
  52620. set: function (value) {
  52621. SceneLoader._loggingLevel = value;
  52622. },
  52623. enumerable: true,
  52624. configurable: true
  52625. });
  52626. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  52627. get: function () {
  52628. return SceneLoader._CleanBoneMatrixWeights;
  52629. },
  52630. set: function (value) {
  52631. SceneLoader._CleanBoneMatrixWeights = value;
  52632. },
  52633. enumerable: true,
  52634. configurable: true
  52635. });
  52636. SceneLoader._getDefaultPlugin = function () {
  52637. return SceneLoader._registeredPlugins[".babylon"];
  52638. };
  52639. SceneLoader._getPluginForExtension = function (extension) {
  52640. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  52641. if (registeredPlugin) {
  52642. return registeredPlugin;
  52643. }
  52644. return SceneLoader._getDefaultPlugin();
  52645. };
  52646. SceneLoader._getPluginForDirectLoad = function (data) {
  52647. for (var extension in SceneLoader._registeredPlugins) {
  52648. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  52649. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  52650. return SceneLoader._registeredPlugins[extension];
  52651. }
  52652. }
  52653. return SceneLoader._getDefaultPlugin();
  52654. };
  52655. SceneLoader._getPluginForFilename = function (sceneFilename) {
  52656. if (sceneFilename.name) {
  52657. sceneFilename = sceneFilename.name;
  52658. }
  52659. var dotPosition = sceneFilename.lastIndexOf(".");
  52660. var queryStringPosition = sceneFilename.indexOf("?");
  52661. if (queryStringPosition === -1) {
  52662. queryStringPosition = sceneFilename.length;
  52663. }
  52664. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  52665. return SceneLoader._getPluginForExtension(extension);
  52666. };
  52667. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  52668. SceneLoader._getDirectLoad = function (sceneFilename) {
  52669. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  52670. return sceneFilename.substr(5);
  52671. }
  52672. return null;
  52673. };
  52674. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52675. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  52676. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  52677. var plugin;
  52678. if (registeredPlugin.plugin.createPlugin) {
  52679. plugin = registeredPlugin.plugin.createPlugin();
  52680. }
  52681. else {
  52682. plugin = registeredPlugin.plugin;
  52683. }
  52684. var useArrayBuffer = registeredPlugin.isBinary;
  52685. var database;
  52686. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  52687. var dataCallback = function (data, responseURL) {
  52688. if (scene.isDisposed) {
  52689. onError("Scene has been disposed");
  52690. return;
  52691. }
  52692. scene.database = database;
  52693. try {
  52694. onSuccess(plugin, data, responseURL);
  52695. }
  52696. catch (e) {
  52697. onError(null, e);
  52698. }
  52699. };
  52700. var manifestChecked = function (success) {
  52701. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  52702. if (request) {
  52703. onError(request.status + " " + request.statusText);
  52704. }
  52705. });
  52706. };
  52707. if (directLoad) {
  52708. dataCallback(directLoad);
  52709. return plugin;
  52710. }
  52711. if (rootUrl.indexOf("file:") === -1) {
  52712. if (scene.getEngine().enableOfflineSupport) {
  52713. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  52714. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  52715. }
  52716. else {
  52717. manifestChecked(true);
  52718. }
  52719. }
  52720. else {
  52721. var fileOrString = sceneFilename;
  52722. if (fileOrString.name) {
  52723. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  52724. }
  52725. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  52726. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  52727. }
  52728. else {
  52729. onError("Unable to find file named " + sceneFilename);
  52730. }
  52731. }
  52732. return plugin;
  52733. };
  52734. // Public functions
  52735. SceneLoader.GetPluginForExtension = function (extension) {
  52736. return SceneLoader._getPluginForExtension(extension).plugin;
  52737. };
  52738. SceneLoader.RegisterPlugin = function (plugin) {
  52739. if (typeof plugin.extensions === "string") {
  52740. var extension = plugin.extensions;
  52741. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52742. plugin: plugin,
  52743. isBinary: false
  52744. };
  52745. }
  52746. else {
  52747. var extensions = plugin.extensions;
  52748. Object.keys(extensions).forEach(function (extension) {
  52749. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52750. plugin: plugin,
  52751. isBinary: extensions[extension].isBinary
  52752. };
  52753. });
  52754. }
  52755. };
  52756. /**
  52757. * Import meshes into a scene
  52758. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  52759. * @param rootUrl a string that defines the root url for scene and resources
  52760. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52761. * @param scene the instance of BABYLON.Scene to append to
  52762. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  52763. * @param onProgress a callback with a progress event for each file being loaded
  52764. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52765. */
  52766. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52767. if (onSuccess === void 0) { onSuccess = null; }
  52768. if (onProgress === void 0) { onProgress = null; }
  52769. if (onError === void 0) { onError = null; }
  52770. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52771. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52772. return null;
  52773. }
  52774. var loadingToken = {};
  52775. scene._addPendingData(loadingToken);
  52776. var errorHandler = function (message, exception) {
  52777. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52778. if (onError) {
  52779. onError(scene, errorMessage, exception);
  52780. }
  52781. else {
  52782. BABYLON.Tools.Error(errorMessage);
  52783. // should the exception be thrown?
  52784. }
  52785. scene._removePendingData(loadingToken);
  52786. };
  52787. var progressHandler = function (event) {
  52788. if (onProgress) {
  52789. onProgress(event);
  52790. }
  52791. };
  52792. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  52793. if (plugin.rewriteRootURL) {
  52794. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  52795. }
  52796. if (plugin.importMesh) {
  52797. var syncedPlugin = plugin;
  52798. var meshes = new Array();
  52799. var particleSystems = new Array();
  52800. var skeletons = new Array();
  52801. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  52802. return;
  52803. }
  52804. if (onSuccess) {
  52805. // wrap onSuccess with try-catch to know if something went wrong.
  52806. try {
  52807. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52808. onSuccess(meshes, particleSystems, skeletons);
  52809. scene._removePendingData(loadingToken);
  52810. }
  52811. catch (e) {
  52812. var message = 'Error in onSuccess callback.';
  52813. errorHandler(message, e);
  52814. }
  52815. }
  52816. }
  52817. else {
  52818. var asyncedPlugin = plugin;
  52819. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  52820. if (onSuccess) {
  52821. try {
  52822. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52823. onSuccess(meshes, particleSystems, skeletons);
  52824. scene._removePendingData(loadingToken);
  52825. }
  52826. catch (e) {
  52827. var message = 'Error in onSuccess callback.';
  52828. errorHandler(message, e);
  52829. }
  52830. }
  52831. }, progressHandler, errorHandler);
  52832. }
  52833. }, progressHandler, errorHandler, pluginExtension);
  52834. };
  52835. /**
  52836. * Load a scene
  52837. * @param rootUrl a string that defines the root url for scene and resources
  52838. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52839. * @param engine is the instance of BABYLON.Engine to use to create the scene
  52840. * @param onSuccess a callback with the scene when import succeeds
  52841. * @param onProgress a callback with a progress event for each file being loaded
  52842. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52843. */
  52844. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  52845. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  52846. };
  52847. /**
  52848. * Append a scene
  52849. * @param rootUrl a string that defines the root url for scene and resources
  52850. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52851. * @param scene is the instance of BABYLON.Scene to append to
  52852. * @param onSuccess a callback with the scene when import succeeds
  52853. * @param onProgress a callback with a progress event for each file being loaded
  52854. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52855. */
  52856. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52857. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52858. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52859. return null;
  52860. }
  52861. if (SceneLoader.ShowLoadingScreen) {
  52862. scene.getEngine().displayLoadingUI();
  52863. }
  52864. var loadingToken = {};
  52865. scene._addPendingData(loadingToken);
  52866. var errorHandler = function (message, exception) {
  52867. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52868. if (onError) {
  52869. onError(scene, errorMessage, exception);
  52870. }
  52871. else {
  52872. BABYLON.Tools.Error(errorMessage);
  52873. // should the exception be thrown?
  52874. }
  52875. scene._removePendingData(loadingToken);
  52876. scene.getEngine().hideLoadingUI();
  52877. };
  52878. var progressHandler = function (event) {
  52879. if (onProgress) {
  52880. onProgress(event);
  52881. }
  52882. };
  52883. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  52884. if (plugin.load) {
  52885. var syncedPlugin = plugin;
  52886. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  52887. return;
  52888. }
  52889. if (onSuccess) {
  52890. try {
  52891. onSuccess(scene);
  52892. }
  52893. catch (e) {
  52894. errorHandler("Error in onSuccess callback", e);
  52895. }
  52896. }
  52897. scene.loadingPluginName = plugin.name;
  52898. scene._removePendingData(loadingToken);
  52899. }
  52900. else {
  52901. var asyncedPlugin = plugin;
  52902. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  52903. if (onSuccess) {
  52904. onSuccess(scene);
  52905. }
  52906. scene.loadingPluginName = plugin.name;
  52907. scene._removePendingData(loadingToken);
  52908. }, progressHandler, errorHandler);
  52909. }
  52910. if (SceneLoader.ShowLoadingScreen) {
  52911. scene.executeWhenReady(function () {
  52912. scene.getEngine().hideLoadingUI();
  52913. });
  52914. }
  52915. }, progressHandler, errorHandler, pluginExtension);
  52916. };
  52917. // Flags
  52918. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  52919. SceneLoader._ShowLoadingScreen = true;
  52920. SceneLoader._CleanBoneMatrixWeights = false;
  52921. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  52922. // Members
  52923. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  52924. SceneLoader._registeredPlugins = {};
  52925. return SceneLoader;
  52926. }());
  52927. BABYLON.SceneLoader = SceneLoader;
  52928. ;
  52929. })(BABYLON || (BABYLON = {}));
  52930. //# sourceMappingURL=babylon.sceneLoader.js.map
  52931. var BABYLON;
  52932. (function (BABYLON) {
  52933. var Internals;
  52934. (function (Internals) {
  52935. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  52936. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52937. var parsedMaterial = parsedData.materials[index];
  52938. if (parsedMaterial.id === id) {
  52939. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52940. }
  52941. }
  52942. return null;
  52943. };
  52944. var isDescendantOf = function (mesh, names, hierarchyIds) {
  52945. for (var i in names) {
  52946. if (mesh.name === names[i]) {
  52947. hierarchyIds.push(mesh.id);
  52948. return true;
  52949. }
  52950. }
  52951. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  52952. hierarchyIds.push(mesh.id);
  52953. return true;
  52954. }
  52955. return false;
  52956. };
  52957. var logOperation = function (operation, producer) {
  52958. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  52959. };
  52960. BABYLON.SceneLoader.RegisterPlugin({
  52961. name: "babylon.js",
  52962. extensions: ".babylon",
  52963. canDirectLoad: function (data) {
  52964. if (data.indexOf("babylon") !== -1) {
  52965. return true;
  52966. }
  52967. return false;
  52968. },
  52969. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  52970. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52971. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52972. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52973. // and avoid problems with multiple concurrent .babylon loads.
  52974. var log = "importMesh has failed JSON parse";
  52975. try {
  52976. var parsedData = JSON.parse(data);
  52977. log = "";
  52978. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52979. if (!meshesNames) {
  52980. meshesNames = null;
  52981. }
  52982. else if (!Array.isArray(meshesNames)) {
  52983. meshesNames = [meshesNames];
  52984. }
  52985. var hierarchyIds = new Array();
  52986. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52987. var loadedSkeletonsIds = [];
  52988. var loadedMaterialsIds = [];
  52989. var index;
  52990. var cache;
  52991. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52992. var parsedMesh = parsedData.meshes[index];
  52993. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  52994. if (meshesNames !== null) {
  52995. // Remove found mesh name from list.
  52996. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  52997. }
  52998. //Geometry?
  52999. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  53000. //does the file contain geometries?
  53001. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  53002. //find the correct geometry and add it to the scene
  53003. var found = false;
  53004. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  53005. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  53006. return;
  53007. }
  53008. else {
  53009. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  53010. if (parsedGeometryData.id === parsedMesh.geometryId) {
  53011. switch (geometryType) {
  53012. case "boxes":
  53013. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  53014. break;
  53015. case "spheres":
  53016. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  53017. break;
  53018. case "cylinders":
  53019. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  53020. break;
  53021. case "toruses":
  53022. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  53023. break;
  53024. case "grounds":
  53025. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  53026. break;
  53027. case "planes":
  53028. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  53029. break;
  53030. case "torusKnots":
  53031. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  53032. break;
  53033. case "vertexData":
  53034. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  53035. break;
  53036. }
  53037. found = true;
  53038. }
  53039. });
  53040. }
  53041. });
  53042. if (found === false) {
  53043. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  53044. }
  53045. }
  53046. }
  53047. // Material ?
  53048. if (parsedMesh.materialId) {
  53049. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  53050. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53051. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  53052. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  53053. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  53054. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  53055. var subMatId = parsedMultiMaterial.materials[matIndex];
  53056. loadedMaterialsIds.push(subMatId);
  53057. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  53058. log += "\n\tMaterial " + mat.toString(fullDetails);
  53059. }
  53060. loadedMaterialsIds.push(parsedMultiMaterial.id);
  53061. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53062. materialFound = true;
  53063. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  53064. break;
  53065. }
  53066. }
  53067. }
  53068. if (materialFound === false) {
  53069. loadedMaterialsIds.push(parsedMesh.materialId);
  53070. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  53071. if (!mat) {
  53072. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  53073. }
  53074. else {
  53075. log += "\n\tMaterial " + mat.toString(fullDetails);
  53076. }
  53077. }
  53078. }
  53079. // Skeleton ?
  53080. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53081. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  53082. if (skeletonAlreadyLoaded === false) {
  53083. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  53084. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  53085. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  53086. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53087. skeletons.push(skeleton);
  53088. loadedSkeletonsIds.push(parsedSkeleton.id);
  53089. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  53090. }
  53091. }
  53092. }
  53093. }
  53094. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53095. meshes.push(mesh);
  53096. log += "\n\tMesh " + mesh.toString(fullDetails);
  53097. }
  53098. }
  53099. // Connecting parents
  53100. var currentMesh;
  53101. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53102. currentMesh = scene.meshes[index];
  53103. if (currentMesh._waitingParentId) {
  53104. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  53105. currentMesh._waitingParentId = null;
  53106. }
  53107. }
  53108. // freeze and compute world matrix application
  53109. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53110. currentMesh = scene.meshes[index];
  53111. if (currentMesh._waitingFreezeWorldMatrix) {
  53112. currentMesh.freezeWorldMatrix();
  53113. currentMesh._waitingFreezeWorldMatrix = null;
  53114. }
  53115. else {
  53116. currentMesh.computeWorldMatrix(true);
  53117. }
  53118. }
  53119. }
  53120. // Particles
  53121. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53122. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53123. var parsedParticleSystem = parsedData.particleSystems[index];
  53124. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  53125. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  53126. }
  53127. }
  53128. }
  53129. return true;
  53130. }
  53131. catch (err) {
  53132. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  53133. if (onError) {
  53134. onError(msg, err);
  53135. }
  53136. else {
  53137. BABYLON.Tools.Log(msg);
  53138. throw err;
  53139. }
  53140. }
  53141. finally {
  53142. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53143. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53144. }
  53145. }
  53146. return false;
  53147. },
  53148. load: function (scene, data, rootUrl, onError) {
  53149. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  53150. // when SceneLoader.debugLogging = true (default), or exception encountered.
  53151. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  53152. // and avoid problems with multiple concurrent .babylon loads.
  53153. var log = "importScene has failed JSON parse";
  53154. try {
  53155. var parsedData = JSON.parse(data);
  53156. log = "";
  53157. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  53158. // Scene
  53159. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  53160. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  53161. }
  53162. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  53163. scene.autoClear = parsedData.autoClear;
  53164. }
  53165. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  53166. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  53167. }
  53168. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  53169. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  53170. }
  53171. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  53172. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  53173. }
  53174. // Fog
  53175. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  53176. scene.fogMode = parsedData.fogMode;
  53177. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  53178. scene.fogStart = parsedData.fogStart;
  53179. scene.fogEnd = parsedData.fogEnd;
  53180. scene.fogDensity = parsedData.fogDensity;
  53181. log += "\tFog mode for scene: ";
  53182. switch (scene.fogMode) {
  53183. // getters not compiling, so using hardcoded
  53184. case 1:
  53185. log += "exp\n";
  53186. break;
  53187. case 2:
  53188. log += "exp2\n";
  53189. break;
  53190. case 3:
  53191. log += "linear\n";
  53192. break;
  53193. }
  53194. }
  53195. //Physics
  53196. if (parsedData.physicsEnabled) {
  53197. var physicsPlugin;
  53198. if (parsedData.physicsEngine === "cannon") {
  53199. physicsPlugin = new BABYLON.CannonJSPlugin();
  53200. }
  53201. else if (parsedData.physicsEngine === "oimo") {
  53202. physicsPlugin = new BABYLON.OimoJSPlugin();
  53203. }
  53204. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  53205. //else - default engine, which is currently oimo
  53206. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  53207. scene.enablePhysics(physicsGravity, physicsPlugin);
  53208. }
  53209. // Metadata
  53210. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  53211. scene.metadata = parsedData.metadata;
  53212. }
  53213. //collisions, if defined. otherwise, default is true
  53214. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  53215. scene.collisionsEnabled = parsedData.collisionsEnabled;
  53216. }
  53217. scene.workerCollisions = !!parsedData.workerCollisions;
  53218. var index;
  53219. var cache;
  53220. // Lights
  53221. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  53222. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  53223. var parsedLight = parsedData.lights[index];
  53224. var light = BABYLON.Light.Parse(parsedLight, scene);
  53225. if (light) {
  53226. log += (index === 0 ? "\n\tLights:" : "");
  53227. log += "\n\t\t" + light.toString(fullDetails);
  53228. }
  53229. }
  53230. }
  53231. // Animations
  53232. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  53233. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  53234. var parsedAnimation = parsedData.animations[index];
  53235. var animation = BABYLON.Animation.Parse(parsedAnimation);
  53236. scene.animations.push(animation);
  53237. log += (index === 0 ? "\n\tAnimations:" : "");
  53238. log += "\n\t\t" + animation.toString(fullDetails);
  53239. }
  53240. }
  53241. if (parsedData.autoAnimate) {
  53242. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  53243. }
  53244. // Materials
  53245. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  53246. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  53247. var parsedMaterial = parsedData.materials[index];
  53248. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  53249. log += (index === 0 ? "\n\tMaterials:" : "");
  53250. log += "\n\t\t" + mat.toString(fullDetails);
  53251. }
  53252. }
  53253. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  53254. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  53255. var parsedMultiMaterial = parsedData.multiMaterials[index];
  53256. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  53257. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  53258. log += "\n\t\t" + mmat.toString(fullDetails);
  53259. }
  53260. }
  53261. // Morph targets
  53262. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  53263. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  53264. var managerData = _a[_i];
  53265. BABYLON.MorphTargetManager.Parse(managerData, scene);
  53266. }
  53267. }
  53268. // Skeletons
  53269. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  53270. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  53271. var parsedSkeleton = parsedData.skeletons[index];
  53272. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  53273. log += (index === 0 ? "\n\tSkeletons:" : "");
  53274. log += "\n\t\t" + skeleton.toString(fullDetails);
  53275. }
  53276. }
  53277. // Geometries
  53278. var geometries = parsedData.geometries;
  53279. if (geometries !== undefined && geometries !== null) {
  53280. // Boxes
  53281. var boxes = geometries.boxes;
  53282. if (boxes !== undefined && boxes !== null) {
  53283. for (index = 0, cache = boxes.length; index < cache; index++) {
  53284. var parsedBox = boxes[index];
  53285. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  53286. }
  53287. }
  53288. // Spheres
  53289. var spheres = geometries.spheres;
  53290. if (spheres !== undefined && spheres !== null) {
  53291. for (index = 0, cache = spheres.length; index < cache; index++) {
  53292. var parsedSphere = spheres[index];
  53293. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  53294. }
  53295. }
  53296. // Cylinders
  53297. var cylinders = geometries.cylinders;
  53298. if (cylinders !== undefined && cylinders !== null) {
  53299. for (index = 0, cache = cylinders.length; index < cache; index++) {
  53300. var parsedCylinder = cylinders[index];
  53301. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  53302. }
  53303. }
  53304. // Toruses
  53305. var toruses = geometries.toruses;
  53306. if (toruses !== undefined && toruses !== null) {
  53307. for (index = 0, cache = toruses.length; index < cache; index++) {
  53308. var parsedTorus = toruses[index];
  53309. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  53310. }
  53311. }
  53312. // Grounds
  53313. var grounds = geometries.grounds;
  53314. if (grounds !== undefined && grounds !== null) {
  53315. for (index = 0, cache = grounds.length; index < cache; index++) {
  53316. var parsedGround = grounds[index];
  53317. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  53318. }
  53319. }
  53320. // Planes
  53321. var planes = geometries.planes;
  53322. if (planes !== undefined && planes !== null) {
  53323. for (index = 0, cache = planes.length; index < cache; index++) {
  53324. var parsedPlane = planes[index];
  53325. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  53326. }
  53327. }
  53328. // TorusKnots
  53329. var torusKnots = geometries.torusKnots;
  53330. if (torusKnots !== undefined && torusKnots !== null) {
  53331. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  53332. var parsedTorusKnot = torusKnots[index];
  53333. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  53334. }
  53335. }
  53336. // VertexData
  53337. var vertexData = geometries.vertexData;
  53338. if (vertexData !== undefined && vertexData !== null) {
  53339. for (index = 0, cache = vertexData.length; index < cache; index++) {
  53340. var parsedVertexData = vertexData[index];
  53341. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  53342. }
  53343. }
  53344. }
  53345. // Transform nodes
  53346. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  53347. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  53348. var parsedTransformNode = parsedData.transformNodes[index];
  53349. BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  53350. }
  53351. }
  53352. // Meshes
  53353. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  53354. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  53355. var parsedMesh = parsedData.meshes[index];
  53356. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  53357. log += (index === 0 ? "\n\tMeshes:" : "");
  53358. log += "\n\t\t" + mesh.toString(fullDetails);
  53359. }
  53360. }
  53361. // Cameras
  53362. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  53363. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  53364. var parsedCamera = parsedData.cameras[index];
  53365. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  53366. log += (index === 0 ? "\n\tCameras:" : "");
  53367. log += "\n\t\t" + camera.toString(fullDetails);
  53368. }
  53369. }
  53370. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  53371. scene.setActiveCameraByID(parsedData.activeCameraID);
  53372. }
  53373. // Browsing all the graph to connect the dots
  53374. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  53375. var camera = scene.cameras[index];
  53376. if (camera._waitingParentId) {
  53377. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  53378. camera._waitingParentId = null;
  53379. }
  53380. }
  53381. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53382. var light_1 = scene.lights[index];
  53383. if (light_1 && light_1._waitingParentId) {
  53384. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  53385. light_1._waitingParentId = null;
  53386. }
  53387. }
  53388. // Sounds
  53389. var loadedSounds = [];
  53390. var loadedSound;
  53391. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  53392. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  53393. var parsedSound = parsedData.sounds[index];
  53394. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53395. if (!parsedSound.url)
  53396. parsedSound.url = parsedSound.name;
  53397. if (!loadedSounds[parsedSound.url]) {
  53398. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  53399. loadedSounds[parsedSound.url] = loadedSound;
  53400. }
  53401. else {
  53402. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  53403. }
  53404. }
  53405. else {
  53406. new BABYLON.Sound(parsedSound.name, null, scene);
  53407. }
  53408. }
  53409. }
  53410. loadedSounds = [];
  53411. // Connect parents & children and parse actions
  53412. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  53413. var transformNode = scene.transformNodes[index];
  53414. if (transformNode._waitingParentId) {
  53415. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  53416. transformNode._waitingParentId = null;
  53417. }
  53418. }
  53419. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53420. var mesh = scene.meshes[index];
  53421. if (mesh._waitingParentId) {
  53422. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  53423. mesh._waitingParentId = null;
  53424. }
  53425. if (mesh._waitingActions) {
  53426. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  53427. mesh._waitingActions = null;
  53428. }
  53429. }
  53430. // freeze world matrix application
  53431. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  53432. var currentMesh = scene.meshes[index];
  53433. if (currentMesh._waitingFreezeWorldMatrix) {
  53434. currentMesh.freezeWorldMatrix();
  53435. currentMesh._waitingFreezeWorldMatrix = null;
  53436. }
  53437. else {
  53438. currentMesh.computeWorldMatrix(true);
  53439. }
  53440. }
  53441. // Particles Systems
  53442. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  53443. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  53444. var parsedParticleSystem = parsedData.particleSystems[index];
  53445. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  53446. }
  53447. }
  53448. // Environment texture
  53449. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  53450. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  53451. if (parsedData.createDefaultSkybox === true) {
  53452. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  53453. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  53454. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  53455. }
  53456. }
  53457. // Lens flares
  53458. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  53459. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  53460. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  53461. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  53462. }
  53463. }
  53464. // Shadows
  53465. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  53466. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  53467. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  53468. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  53469. }
  53470. }
  53471. // Lights exclusions / inclusions
  53472. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  53473. var light_2 = scene.lights[index];
  53474. // Excluded check
  53475. if (light_2._excludedMeshesIds.length > 0) {
  53476. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  53477. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  53478. if (excludedMesh) {
  53479. light_2.excludedMeshes.push(excludedMesh);
  53480. }
  53481. }
  53482. light_2._excludedMeshesIds = [];
  53483. }
  53484. // Included check
  53485. if (light_2._includedOnlyMeshesIds.length > 0) {
  53486. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  53487. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  53488. if (includedOnlyMesh) {
  53489. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  53490. }
  53491. }
  53492. light_2._includedOnlyMeshesIds = [];
  53493. }
  53494. }
  53495. // Actions (scene)
  53496. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  53497. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  53498. }
  53499. // Finish
  53500. return true;
  53501. }
  53502. catch (err) {
  53503. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  53504. if (onError) {
  53505. onError(msg, err);
  53506. }
  53507. else {
  53508. BABYLON.Tools.Log(msg);
  53509. throw err;
  53510. }
  53511. }
  53512. finally {
  53513. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53514. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53515. }
  53516. }
  53517. return false;
  53518. }
  53519. });
  53520. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53521. })(BABYLON || (BABYLON = {}));
  53522. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  53523. var BABYLON;
  53524. (function (BABYLON) {
  53525. var FilesInput = /** @class */ (function () {
  53526. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  53527. this.onProcessFileCallback = function () { return true; };
  53528. this._engine = engine;
  53529. this._currentScene = scene;
  53530. this._sceneLoadedCallback = sceneLoadedCallback;
  53531. this._progressCallback = progressCallback;
  53532. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  53533. this._textureLoadingCallback = textureLoadingCallback;
  53534. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  53535. this._onReloadCallback = onReloadCallback;
  53536. this._errorCallback = errorCallback;
  53537. }
  53538. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  53539. var _this = this;
  53540. if (elementToMonitor) {
  53541. this._elementToMonitor = elementToMonitor;
  53542. this._dragEnterHandler = function (e) { _this.drag(e); };
  53543. this._dragOverHandler = function (e) { _this.drag(e); };
  53544. this._dropHandler = function (e) { _this.drop(e); };
  53545. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  53546. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  53547. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  53548. }
  53549. };
  53550. FilesInput.prototype.dispose = function () {
  53551. if (!this._elementToMonitor) {
  53552. return;
  53553. }
  53554. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  53555. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  53556. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  53557. };
  53558. FilesInput.prototype.renderFunction = function () {
  53559. if (this._additionalRenderLoopLogicCallback) {
  53560. this._additionalRenderLoopLogicCallback();
  53561. }
  53562. if (this._currentScene) {
  53563. if (this._textureLoadingCallback) {
  53564. var remaining = this._currentScene.getWaitingItemsCount();
  53565. if (remaining > 0) {
  53566. this._textureLoadingCallback(remaining);
  53567. }
  53568. }
  53569. this._currentScene.render();
  53570. }
  53571. };
  53572. FilesInput.prototype.drag = function (e) {
  53573. e.stopPropagation();
  53574. e.preventDefault();
  53575. };
  53576. FilesInput.prototype.drop = function (eventDrop) {
  53577. eventDrop.stopPropagation();
  53578. eventDrop.preventDefault();
  53579. this.loadFiles(eventDrop);
  53580. };
  53581. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  53582. var _this = this;
  53583. var reader = folder.createReader();
  53584. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  53585. reader.readEntries(function (entries) {
  53586. remaining.count += entries.length;
  53587. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  53588. var entry = entries_1[_i];
  53589. if (entry.isFile) {
  53590. entry.file(function (file) {
  53591. file.correctName = relativePath + file.name;
  53592. files.push(file);
  53593. if (--remaining.count === 0) {
  53594. callback();
  53595. }
  53596. });
  53597. }
  53598. else if (entry.isDirectory) {
  53599. _this._traverseFolder(entry, files, remaining, callback);
  53600. }
  53601. }
  53602. if (--remaining.count) {
  53603. callback();
  53604. }
  53605. });
  53606. };
  53607. FilesInput.prototype._processFiles = function (files) {
  53608. var skippedFiles = 0;
  53609. for (var i = 0; i < files.length; i++) {
  53610. var name = files[i].correctName.toLowerCase();
  53611. var extension = name.split('.').pop();
  53612. if (!this.onProcessFileCallback(files[i], name, extension)) {
  53613. skippedFiles++;
  53614. continue;
  53615. }
  53616. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  53617. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  53618. this._sceneFileToLoad = files[i];
  53619. }
  53620. else {
  53621. FilesInput.FilesToLoad[name] = files[i];
  53622. }
  53623. }
  53624. if (this._onReloadCallback) {
  53625. this._onReloadCallback(this._sceneFileToLoad);
  53626. }
  53627. else if (skippedFiles < files.length) {
  53628. this.reload();
  53629. }
  53630. };
  53631. FilesInput.prototype.loadFiles = function (event) {
  53632. var _this = this;
  53633. if (this._startingProcessingFilesCallback)
  53634. this._startingProcessingFilesCallback();
  53635. // Handling data transfer via drag'n'drop
  53636. if (event && event.dataTransfer && event.dataTransfer.files) {
  53637. this._filesToLoad = event.dataTransfer.files;
  53638. }
  53639. // Handling files from input files
  53640. if (event && event.target && event.target.files) {
  53641. this._filesToLoad = event.target.files;
  53642. }
  53643. if (this._filesToLoad && this._filesToLoad.length > 0) {
  53644. var files_1 = new Array();
  53645. var folders = [];
  53646. var items = event.dataTransfer ? event.dataTransfer.items : null;
  53647. for (var i = 0; i < this._filesToLoad.length; i++) {
  53648. var fileToLoad = this._filesToLoad[i];
  53649. var name_1 = fileToLoad.name.toLowerCase();
  53650. var entry = void 0;
  53651. fileToLoad.correctName = name_1;
  53652. if (items) {
  53653. var item = items[i];
  53654. if (item.getAsEntry) {
  53655. entry = item.getAsEntry();
  53656. }
  53657. else if (item.webkitGetAsEntry) {
  53658. entry = item.webkitGetAsEntry();
  53659. }
  53660. }
  53661. if (!entry) {
  53662. files_1.push(fileToLoad);
  53663. }
  53664. else {
  53665. if (entry.isDirectory) {
  53666. folders.push(entry);
  53667. }
  53668. else {
  53669. files_1.push(fileToLoad);
  53670. }
  53671. }
  53672. }
  53673. if (folders.length === 0) {
  53674. this._processFiles(files_1);
  53675. }
  53676. else {
  53677. var remaining = { count: folders.length };
  53678. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  53679. var folder = folders_1[_i];
  53680. this._traverseFolder(folder, files_1, remaining, function () {
  53681. _this._processFiles(files_1);
  53682. });
  53683. }
  53684. }
  53685. }
  53686. };
  53687. FilesInput.prototype.reload = function () {
  53688. var _this = this;
  53689. // If a ".babylon" file has been provided
  53690. if (this._sceneFileToLoad) {
  53691. if (this._currentScene) {
  53692. if (BABYLON.Tools.errorsCount > 0) {
  53693. BABYLON.Tools.ClearLogCache();
  53694. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  53695. }
  53696. this._engine.stopRenderLoop();
  53697. this._currentScene.dispose();
  53698. }
  53699. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  53700. _this._currentScene = newScene;
  53701. if (_this._sceneLoadedCallback) {
  53702. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  53703. }
  53704. // Wait for textures and shaders to be ready
  53705. _this._currentScene.executeWhenReady(function () {
  53706. _this._engine.runRenderLoop(function () {
  53707. _this.renderFunction();
  53708. });
  53709. });
  53710. }, function (progress) {
  53711. if (_this._progressCallback) {
  53712. _this._progressCallback(progress);
  53713. }
  53714. }, function (scene, message) {
  53715. _this._currentScene = scene;
  53716. if (_this._errorCallback) {
  53717. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  53718. }
  53719. });
  53720. }
  53721. else {
  53722. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  53723. }
  53724. };
  53725. FilesInput.FilesToLoad = {};
  53726. return FilesInput;
  53727. }());
  53728. BABYLON.FilesInput = FilesInput;
  53729. })(BABYLON || (BABYLON = {}));
  53730. //# sourceMappingURL=babylon.filesInput.js.map
  53731. var BABYLON;
  53732. (function (BABYLON) {
  53733. /**
  53734. * This class implement a typical dictionary using a string as key and the generic type T as value.
  53735. * The underlying implementation relies on an associative array to ensure the best performances.
  53736. * The value can be anything including 'null' but except 'undefined'
  53737. */
  53738. var StringDictionary = /** @class */ (function () {
  53739. function StringDictionary() {
  53740. this._count = 0;
  53741. this._data = {};
  53742. }
  53743. /**
  53744. * This will clear this dictionary and copy the content from the 'source' one.
  53745. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  53746. * @param source the dictionary to take the content from and copy to this dictionary
  53747. */
  53748. StringDictionary.prototype.copyFrom = function (source) {
  53749. var _this = this;
  53750. this.clear();
  53751. source.forEach(function (t, v) { return _this.add(t, v); });
  53752. };
  53753. /**
  53754. * Get a value based from its key
  53755. * @param key the given key to get the matching value from
  53756. * @return the value if found, otherwise undefined is returned
  53757. */
  53758. StringDictionary.prototype.get = function (key) {
  53759. var val = this._data[key];
  53760. if (val !== undefined) {
  53761. return val;
  53762. }
  53763. return undefined;
  53764. };
  53765. /**
  53766. * Get a value from its key or add it if it doesn't exist.
  53767. * This method will ensure you that a given key/data will be present in the dictionary.
  53768. * @param key the given key to get the matching value from
  53769. * @param factory the factory that will create the value if the key is not present in the dictionary.
  53770. * The factory will only be invoked if there's no data for the given key.
  53771. * @return the value corresponding to the key.
  53772. */
  53773. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  53774. var val = this.get(key);
  53775. if (val !== undefined) {
  53776. return val;
  53777. }
  53778. val = factory(key);
  53779. if (val) {
  53780. this.add(key, val);
  53781. }
  53782. return val;
  53783. };
  53784. /**
  53785. * Get a value from its key if present in the dictionary otherwise add it
  53786. * @param key the key to get the value from
  53787. * @param val if there's no such key/value pair in the dictionary add it with this value
  53788. * @return the value corresponding to the key
  53789. */
  53790. StringDictionary.prototype.getOrAdd = function (key, val) {
  53791. var curVal = this.get(key);
  53792. if (curVal !== undefined) {
  53793. return curVal;
  53794. }
  53795. this.add(key, val);
  53796. return val;
  53797. };
  53798. /**
  53799. * Check if there's a given key in the dictionary
  53800. * @param key the key to check for
  53801. * @return true if the key is present, false otherwise
  53802. */
  53803. StringDictionary.prototype.contains = function (key) {
  53804. return this._data[key] !== undefined;
  53805. };
  53806. /**
  53807. * Add a new key and its corresponding value
  53808. * @param key the key to add
  53809. * @param value the value corresponding to the key
  53810. * @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
  53811. */
  53812. StringDictionary.prototype.add = function (key, value) {
  53813. if (this._data[key] !== undefined) {
  53814. return false;
  53815. }
  53816. this._data[key] = value;
  53817. ++this._count;
  53818. return true;
  53819. };
  53820. StringDictionary.prototype.set = function (key, value) {
  53821. if (this._data[key] === undefined) {
  53822. return false;
  53823. }
  53824. this._data[key] = value;
  53825. return true;
  53826. };
  53827. /**
  53828. * Get the element of the given key and remove it from the dictionary
  53829. * @param key
  53830. */
  53831. StringDictionary.prototype.getAndRemove = function (key) {
  53832. var val = this.get(key);
  53833. if (val !== undefined) {
  53834. delete this._data[key];
  53835. --this._count;
  53836. return val;
  53837. }
  53838. return null;
  53839. };
  53840. /**
  53841. * Remove a key/value from the dictionary.
  53842. * @param key the key to remove
  53843. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  53844. */
  53845. StringDictionary.prototype.remove = function (key) {
  53846. if (this.contains(key)) {
  53847. delete this._data[key];
  53848. --this._count;
  53849. return true;
  53850. }
  53851. return false;
  53852. };
  53853. /**
  53854. * Clear the whole content of the dictionary
  53855. */
  53856. StringDictionary.prototype.clear = function () {
  53857. this._data = {};
  53858. this._count = 0;
  53859. };
  53860. Object.defineProperty(StringDictionary.prototype, "count", {
  53861. get: function () {
  53862. return this._count;
  53863. },
  53864. enumerable: true,
  53865. configurable: true
  53866. });
  53867. /**
  53868. * Execute a callback on each key/val of the dictionary.
  53869. * Note that you can remove any element in this dictionary in the callback implementation
  53870. * @param callback the callback to execute on a given key/value pair
  53871. */
  53872. StringDictionary.prototype.forEach = function (callback) {
  53873. for (var cur in this._data) {
  53874. var val = this._data[cur];
  53875. callback(cur, val);
  53876. }
  53877. };
  53878. /**
  53879. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  53880. * If the callback returns null or undefined the method will iterate to the next key/value pair
  53881. * Note that you can remove any element in this dictionary in the callback implementation
  53882. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  53883. */
  53884. StringDictionary.prototype.first = function (callback) {
  53885. for (var cur in this._data) {
  53886. var val = this._data[cur];
  53887. var res = callback(cur, val);
  53888. if (res) {
  53889. return res;
  53890. }
  53891. }
  53892. return null;
  53893. };
  53894. return StringDictionary;
  53895. }());
  53896. BABYLON.StringDictionary = StringDictionary;
  53897. })(BABYLON || (BABYLON = {}));
  53898. //# sourceMappingURL=babylon.stringDictionary.js.map
  53899. var BABYLON;
  53900. (function (BABYLON) {
  53901. var Tags = /** @class */ (function () {
  53902. function Tags() {
  53903. }
  53904. Tags.EnableFor = function (obj) {
  53905. obj._tags = obj._tags || {};
  53906. obj.hasTags = function () {
  53907. return Tags.HasTags(obj);
  53908. };
  53909. obj.addTags = function (tagsString) {
  53910. return Tags.AddTagsTo(obj, tagsString);
  53911. };
  53912. obj.removeTags = function (tagsString) {
  53913. return Tags.RemoveTagsFrom(obj, tagsString);
  53914. };
  53915. obj.matchesTagsQuery = function (tagsQuery) {
  53916. return Tags.MatchesQuery(obj, tagsQuery);
  53917. };
  53918. };
  53919. Tags.DisableFor = function (obj) {
  53920. delete obj._tags;
  53921. delete obj.hasTags;
  53922. delete obj.addTags;
  53923. delete obj.removeTags;
  53924. delete obj.matchesTagsQuery;
  53925. };
  53926. Tags.HasTags = function (obj) {
  53927. if (!obj._tags) {
  53928. return false;
  53929. }
  53930. return !BABYLON.Tools.IsEmpty(obj._tags);
  53931. };
  53932. Tags.GetTags = function (obj, asString) {
  53933. if (asString === void 0) { asString = true; }
  53934. if (!obj._tags) {
  53935. return null;
  53936. }
  53937. if (asString) {
  53938. var tagsArray = [];
  53939. for (var tag in obj._tags) {
  53940. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  53941. tagsArray.push(tag);
  53942. }
  53943. }
  53944. return tagsArray.join(" ");
  53945. }
  53946. else {
  53947. return obj._tags;
  53948. }
  53949. };
  53950. // the tags 'true' and 'false' are reserved and cannot be used as tags
  53951. // a tag cannot start with '||', '&&', and '!'
  53952. // it cannot contain whitespaces
  53953. Tags.AddTagsTo = function (obj, tagsString) {
  53954. if (!tagsString) {
  53955. return;
  53956. }
  53957. if (typeof tagsString !== "string") {
  53958. return;
  53959. }
  53960. var tags = tagsString.split(" ");
  53961. tags.forEach(function (tag, index, array) {
  53962. Tags._AddTagTo(obj, tag);
  53963. });
  53964. };
  53965. Tags._AddTagTo = function (obj, tag) {
  53966. tag = tag.trim();
  53967. if (tag === "" || tag === "true" || tag === "false") {
  53968. return;
  53969. }
  53970. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  53971. return;
  53972. }
  53973. Tags.EnableFor(obj);
  53974. obj._tags[tag] = true;
  53975. };
  53976. Tags.RemoveTagsFrom = function (obj, tagsString) {
  53977. if (!Tags.HasTags(obj)) {
  53978. return;
  53979. }
  53980. var tags = tagsString.split(" ");
  53981. for (var t in tags) {
  53982. Tags._RemoveTagFrom(obj, tags[t]);
  53983. }
  53984. };
  53985. Tags._RemoveTagFrom = function (obj, tag) {
  53986. delete obj._tags[tag];
  53987. };
  53988. Tags.MatchesQuery = function (obj, tagsQuery) {
  53989. if (tagsQuery === undefined) {
  53990. return true;
  53991. }
  53992. if (tagsQuery === "") {
  53993. return Tags.HasTags(obj);
  53994. }
  53995. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  53996. };
  53997. return Tags;
  53998. }());
  53999. BABYLON.Tags = Tags;
  54000. })(BABYLON || (BABYLON = {}));
  54001. //# sourceMappingURL=babylon.tags.js.map
  54002. var BABYLON;
  54003. (function (BABYLON) {
  54004. var Internals;
  54005. (function (Internals) {
  54006. var AndOrNotEvaluator = /** @class */ (function () {
  54007. function AndOrNotEvaluator() {
  54008. }
  54009. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  54010. if (!query.match(/\([^\(\)]*\)/g)) {
  54011. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  54012. }
  54013. else {
  54014. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  54015. // remove parenthesis
  54016. r = r.slice(1, r.length - 1);
  54017. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  54018. });
  54019. }
  54020. if (query === "true") {
  54021. return true;
  54022. }
  54023. if (query === "false") {
  54024. return false;
  54025. }
  54026. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  54027. };
  54028. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  54029. evaluateCallback = evaluateCallback || (function (r) {
  54030. return r === "true" ? true : false;
  54031. });
  54032. var result;
  54033. var or = parenthesisContent.split("||");
  54034. for (var i in or) {
  54035. if (or.hasOwnProperty(i)) {
  54036. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  54037. var and = ori.split("&&");
  54038. if (and.length > 1) {
  54039. for (var j = 0; j < and.length; ++j) {
  54040. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  54041. if (andj !== "true" && andj !== "false") {
  54042. if (andj[0] === "!") {
  54043. result = !evaluateCallback(andj.substring(1));
  54044. }
  54045. else {
  54046. result = evaluateCallback(andj);
  54047. }
  54048. }
  54049. else {
  54050. result = andj === "true" ? true : false;
  54051. }
  54052. if (!result) {
  54053. ori = "false";
  54054. break;
  54055. }
  54056. }
  54057. }
  54058. if (result || ori === "true") {
  54059. result = true;
  54060. break;
  54061. }
  54062. // result equals false (or undefined)
  54063. if (ori !== "true" && ori !== "false") {
  54064. if (ori[0] === "!") {
  54065. result = !evaluateCallback(ori.substring(1));
  54066. }
  54067. else {
  54068. result = evaluateCallback(ori);
  54069. }
  54070. }
  54071. else {
  54072. result = ori === "true" ? true : false;
  54073. }
  54074. }
  54075. }
  54076. // the whole parenthesis scope is replaced by 'true' or 'false'
  54077. return result ? "true" : "false";
  54078. };
  54079. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  54080. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  54081. // remove whitespaces
  54082. r = r.replace(/[\s]/g, function () { return ""; });
  54083. return r.length % 2 ? "!" : "";
  54084. });
  54085. booleanString = booleanString.trim();
  54086. if (booleanString === "!true") {
  54087. booleanString = "false";
  54088. }
  54089. else if (booleanString === "!false") {
  54090. booleanString = "true";
  54091. }
  54092. return booleanString;
  54093. };
  54094. return AndOrNotEvaluator;
  54095. }());
  54096. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  54097. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54098. })(BABYLON || (BABYLON = {}));
  54099. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  54100. var BABYLON;
  54101. (function (BABYLON) {
  54102. var Database = /** @class */ (function () {
  54103. function Database(urlToScene, callbackManifestChecked) {
  54104. // Handling various flavors of prefixed version of IndexedDB
  54105. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  54106. this.callbackManifestChecked = callbackManifestChecked;
  54107. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  54108. this.db = null;
  54109. this._enableSceneOffline = false;
  54110. this._enableTexturesOffline = false;
  54111. this.manifestVersionFound = 0;
  54112. this.mustUpdateRessources = false;
  54113. this.hasReachedQuota = false;
  54114. if (!Database.IDBStorageEnabled) {
  54115. this.callbackManifestChecked(true);
  54116. }
  54117. else {
  54118. this.checkManifestFile();
  54119. }
  54120. }
  54121. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  54122. get: function () {
  54123. return this._enableSceneOffline;
  54124. },
  54125. enumerable: true,
  54126. configurable: true
  54127. });
  54128. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  54129. get: function () {
  54130. return this._enableTexturesOffline;
  54131. },
  54132. enumerable: true,
  54133. configurable: true
  54134. });
  54135. Database.prototype.checkManifestFile = function () {
  54136. var _this = this;
  54137. var noManifestFile = function () {
  54138. _this._enableSceneOffline = false;
  54139. _this._enableTexturesOffline = false;
  54140. _this.callbackManifestChecked(false);
  54141. };
  54142. var timeStampUsed = false;
  54143. var manifestURL = this.currentSceneUrl + ".manifest";
  54144. var xhr = new XMLHttpRequest();
  54145. if (navigator.onLine) {
  54146. // Adding a timestamp to by-pass browsers' cache
  54147. timeStampUsed = true;
  54148. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  54149. }
  54150. xhr.open("GET", manifestURL, true);
  54151. xhr.addEventListener("load", function () {
  54152. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54153. try {
  54154. var manifestFile = JSON.parse(xhr.response);
  54155. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  54156. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  54157. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  54158. _this.manifestVersionFound = manifestFile.version;
  54159. }
  54160. if (_this.callbackManifestChecked) {
  54161. _this.callbackManifestChecked(true);
  54162. }
  54163. }
  54164. catch (ex) {
  54165. noManifestFile();
  54166. }
  54167. }
  54168. else {
  54169. noManifestFile();
  54170. }
  54171. }, false);
  54172. xhr.addEventListener("error", function (event) {
  54173. if (timeStampUsed) {
  54174. timeStampUsed = false;
  54175. // Let's retry without the timeStamp
  54176. // It could fail when coupled with HTML5 Offline API
  54177. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  54178. xhr.open("GET", retryManifestURL, true);
  54179. xhr.send();
  54180. }
  54181. else {
  54182. noManifestFile();
  54183. }
  54184. }, false);
  54185. try {
  54186. xhr.send();
  54187. }
  54188. catch (ex) {
  54189. BABYLON.Tools.Error("Error on XHR send request.");
  54190. this.callbackManifestChecked(false);
  54191. }
  54192. };
  54193. Database.prototype.openAsync = function (successCallback, errorCallback) {
  54194. var _this = this;
  54195. var handleError = function () {
  54196. _this.isSupported = false;
  54197. if (errorCallback)
  54198. errorCallback();
  54199. };
  54200. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  54201. // Your browser doesn't support IndexedDB
  54202. this.isSupported = false;
  54203. if (errorCallback)
  54204. errorCallback();
  54205. }
  54206. else {
  54207. // If the DB hasn't been opened or created yet
  54208. if (!this.db) {
  54209. this.hasReachedQuota = false;
  54210. this.isSupported = true;
  54211. var request = this.idbFactory.open("babylonjs", 1);
  54212. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  54213. request.onerror = function (event) {
  54214. handleError();
  54215. };
  54216. // executes when a version change transaction cannot complete due to other active transactions
  54217. request.onblocked = function (event) {
  54218. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  54219. handleError();
  54220. };
  54221. // DB has been opened successfully
  54222. request.onsuccess = function (event) {
  54223. _this.db = request.result;
  54224. successCallback();
  54225. };
  54226. // Initialization of the DB. Creating Scenes & Textures stores
  54227. request.onupgradeneeded = function (event) {
  54228. _this.db = (event.target).result;
  54229. if (_this.db) {
  54230. try {
  54231. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  54232. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  54233. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  54234. }
  54235. catch (ex) {
  54236. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  54237. handleError();
  54238. }
  54239. }
  54240. };
  54241. }
  54242. else {
  54243. if (successCallback)
  54244. successCallback();
  54245. }
  54246. }
  54247. };
  54248. Database.prototype.loadImageFromDB = function (url, image) {
  54249. var _this = this;
  54250. var completeURL = Database.ReturnFullUrlLocation(url);
  54251. var saveAndLoadImage = function () {
  54252. if (!_this.hasReachedQuota && _this.db !== null) {
  54253. // the texture is not yet in the DB, let's try to save it
  54254. _this._saveImageIntoDBAsync(completeURL, image);
  54255. }
  54256. else {
  54257. image.src = url;
  54258. }
  54259. };
  54260. if (!this.mustUpdateRessources) {
  54261. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  54262. }
  54263. else {
  54264. saveAndLoadImage();
  54265. }
  54266. };
  54267. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  54268. if (this.isSupported && this.db !== null) {
  54269. var texture;
  54270. var transaction = this.db.transaction(["textures"]);
  54271. transaction.onabort = function (event) {
  54272. image.src = url;
  54273. };
  54274. transaction.oncomplete = function (event) {
  54275. var blobTextureURL;
  54276. if (texture) {
  54277. var URL = window.URL || window.webkitURL;
  54278. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  54279. image.onerror = function () {
  54280. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  54281. image.src = url;
  54282. };
  54283. image.src = blobTextureURL;
  54284. }
  54285. else {
  54286. notInDBCallback();
  54287. }
  54288. };
  54289. var getRequest = transaction.objectStore("textures").get(url);
  54290. getRequest.onsuccess = function (event) {
  54291. texture = (event.target).result;
  54292. };
  54293. getRequest.onerror = function (event) {
  54294. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  54295. image.src = url;
  54296. };
  54297. }
  54298. else {
  54299. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54300. image.src = url;
  54301. }
  54302. };
  54303. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  54304. var _this = this;
  54305. if (this.isSupported) {
  54306. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  54307. var generateBlobUrl = function () {
  54308. var blobTextureURL;
  54309. if (blob) {
  54310. var URL = window.URL || window.webkitURL;
  54311. try {
  54312. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  54313. }
  54314. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  54315. catch (ex) {
  54316. blobTextureURL = URL.createObjectURL(blob);
  54317. }
  54318. }
  54319. if (blobTextureURL) {
  54320. image.src = blobTextureURL;
  54321. }
  54322. };
  54323. if (Database.IsUASupportingBlobStorage) {
  54324. var xhr = new XMLHttpRequest(), blob;
  54325. xhr.open("GET", url, true);
  54326. xhr.responseType = "blob";
  54327. xhr.addEventListener("load", function () {
  54328. if (xhr.status === 200 && _this.db) {
  54329. // Blob as response (XHR2)
  54330. blob = xhr.response;
  54331. var transaction = _this.db.transaction(["textures"], "readwrite");
  54332. // the transaction could abort because of a QuotaExceededError error
  54333. transaction.onabort = function (event) {
  54334. try {
  54335. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54336. var srcElement = (event.srcElement || event.target);
  54337. var error = srcElement.error;
  54338. if (error && error.name === "QuotaExceededError") {
  54339. _this.hasReachedQuota = true;
  54340. }
  54341. }
  54342. catch (ex) { }
  54343. generateBlobUrl();
  54344. };
  54345. transaction.oncomplete = function (event) {
  54346. generateBlobUrl();
  54347. };
  54348. var newTexture = { textureUrl: url, data: blob };
  54349. try {
  54350. // Put the blob into the dabase
  54351. var addRequest = transaction.objectStore("textures").put(newTexture);
  54352. addRequest.onsuccess = function (event) {
  54353. };
  54354. addRequest.onerror = function (event) {
  54355. generateBlobUrl();
  54356. };
  54357. }
  54358. catch (ex) {
  54359. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  54360. if (ex.code === 25) {
  54361. Database.IsUASupportingBlobStorage = false;
  54362. }
  54363. image.src = url;
  54364. }
  54365. }
  54366. else {
  54367. image.src = url;
  54368. }
  54369. }, false);
  54370. xhr.addEventListener("error", function (event) {
  54371. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  54372. image.src = url;
  54373. }, false);
  54374. xhr.send();
  54375. }
  54376. else {
  54377. image.src = url;
  54378. }
  54379. }
  54380. else {
  54381. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54382. image.src = url;
  54383. }
  54384. };
  54385. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  54386. var _this = this;
  54387. var updateVersion = function () {
  54388. // the version is not yet in the DB or we need to update it
  54389. _this._saveVersionIntoDBAsync(url, versionLoaded);
  54390. };
  54391. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  54392. };
  54393. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  54394. var _this = this;
  54395. if (this.isSupported && this.db) {
  54396. var version;
  54397. try {
  54398. var transaction = this.db.transaction(["versions"]);
  54399. transaction.oncomplete = function (event) {
  54400. if (version) {
  54401. // If the version in the JSON file is > than the version in DB
  54402. if (_this.manifestVersionFound > version.data) {
  54403. _this.mustUpdateRessources = true;
  54404. updateInDBCallback();
  54405. }
  54406. else {
  54407. callback(version.data);
  54408. }
  54409. }
  54410. else {
  54411. _this.mustUpdateRessources = true;
  54412. updateInDBCallback();
  54413. }
  54414. };
  54415. transaction.onabort = function (event) {
  54416. callback(-1);
  54417. };
  54418. var getRequest = transaction.objectStore("versions").get(url);
  54419. getRequest.onsuccess = function (event) {
  54420. version = (event.target).result;
  54421. };
  54422. getRequest.onerror = function (event) {
  54423. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  54424. callback(-1);
  54425. };
  54426. }
  54427. catch (ex) {
  54428. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  54429. callback(-1);
  54430. }
  54431. }
  54432. else {
  54433. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54434. callback(-1);
  54435. }
  54436. };
  54437. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  54438. var _this = this;
  54439. if (this.isSupported && !this.hasReachedQuota && this.db) {
  54440. try {
  54441. // Open a transaction to the database
  54442. var transaction = this.db.transaction(["versions"], "readwrite");
  54443. // the transaction could abort because of a QuotaExceededError error
  54444. transaction.onabort = function (event) {
  54445. try {
  54446. var error = event.srcElement['error'];
  54447. if (error && error.name === "QuotaExceededError") {
  54448. _this.hasReachedQuota = true;
  54449. }
  54450. }
  54451. catch (ex) { }
  54452. callback(-1);
  54453. };
  54454. transaction.oncomplete = function (event) {
  54455. callback(_this.manifestVersionFound);
  54456. };
  54457. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  54458. // Put the scene into the database
  54459. var addRequest = transaction.objectStore("versions").put(newVersion);
  54460. addRequest.onsuccess = function (event) {
  54461. };
  54462. addRequest.onerror = function (event) {
  54463. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  54464. };
  54465. }
  54466. catch (ex) {
  54467. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  54468. callback(-1);
  54469. }
  54470. }
  54471. else {
  54472. callback(-1);
  54473. }
  54474. };
  54475. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  54476. var _this = this;
  54477. var completeUrl = Database.ReturnFullUrlLocation(url);
  54478. var saveAndLoadFile = function () {
  54479. // the scene is not yet in the DB, let's try to save it
  54480. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  54481. };
  54482. this._checkVersionFromDB(completeUrl, function (version) {
  54483. if (version !== -1) {
  54484. if (!_this.mustUpdateRessources) {
  54485. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  54486. }
  54487. else {
  54488. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  54489. }
  54490. }
  54491. else {
  54492. if (errorCallback) {
  54493. errorCallback();
  54494. }
  54495. }
  54496. });
  54497. };
  54498. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  54499. if (this.isSupported && this.db) {
  54500. var targetStore;
  54501. if (url.indexOf(".babylon") !== -1) {
  54502. targetStore = "scenes";
  54503. }
  54504. else {
  54505. targetStore = "textures";
  54506. }
  54507. var file;
  54508. var transaction = this.db.transaction([targetStore]);
  54509. transaction.oncomplete = function (event) {
  54510. if (file) {
  54511. callback(file.data);
  54512. }
  54513. else {
  54514. notInDBCallback();
  54515. }
  54516. };
  54517. transaction.onabort = function (event) {
  54518. notInDBCallback();
  54519. };
  54520. var getRequest = transaction.objectStore(targetStore).get(url);
  54521. getRequest.onsuccess = function (event) {
  54522. file = (event.target).result;
  54523. };
  54524. getRequest.onerror = function (event) {
  54525. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  54526. notInDBCallback();
  54527. };
  54528. }
  54529. else {
  54530. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54531. callback();
  54532. }
  54533. };
  54534. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  54535. var _this = this;
  54536. if (this.isSupported) {
  54537. var targetStore;
  54538. if (url.indexOf(".babylon") !== -1) {
  54539. targetStore = "scenes";
  54540. }
  54541. else {
  54542. targetStore = "textures";
  54543. }
  54544. // Create XHR
  54545. var xhr = new XMLHttpRequest();
  54546. var fileData;
  54547. xhr.open("GET", url, true);
  54548. if (useArrayBuffer) {
  54549. xhr.responseType = "arraybuffer";
  54550. }
  54551. if (progressCallback) {
  54552. xhr.onprogress = progressCallback;
  54553. }
  54554. xhr.addEventListener("load", function () {
  54555. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  54556. // Blob as response (XHR2)
  54557. //fileData = xhr.responseText;
  54558. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  54559. if (!_this.hasReachedQuota && _this.db) {
  54560. // Open a transaction to the database
  54561. var transaction = _this.db.transaction([targetStore], "readwrite");
  54562. // the transaction could abort because of a QuotaExceededError error
  54563. transaction.onabort = function (event) {
  54564. try {
  54565. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54566. var error = event.srcElement['error'];
  54567. if (error && error.name === "QuotaExceededError") {
  54568. _this.hasReachedQuota = true;
  54569. }
  54570. }
  54571. catch (ex) { }
  54572. callback(fileData);
  54573. };
  54574. transaction.oncomplete = function (event) {
  54575. callback(fileData);
  54576. };
  54577. var newFile;
  54578. if (targetStore === "scenes") {
  54579. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  54580. }
  54581. else {
  54582. newFile = { textureUrl: url, data: fileData };
  54583. }
  54584. try {
  54585. // Put the scene into the database
  54586. var addRequest = transaction.objectStore(targetStore).put(newFile);
  54587. addRequest.onsuccess = function (event) {
  54588. };
  54589. addRequest.onerror = function (event) {
  54590. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  54591. };
  54592. }
  54593. catch (ex) {
  54594. callback(fileData);
  54595. }
  54596. }
  54597. else {
  54598. callback(fileData);
  54599. }
  54600. }
  54601. else {
  54602. callback();
  54603. }
  54604. }, false);
  54605. xhr.addEventListener("error", function (event) {
  54606. BABYLON.Tools.Error("error on XHR request.");
  54607. callback();
  54608. }, false);
  54609. xhr.send();
  54610. }
  54611. else {
  54612. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54613. callback();
  54614. }
  54615. };
  54616. Database.IsUASupportingBlobStorage = true;
  54617. Database.IDBStorageEnabled = true;
  54618. Database.parseURL = function (url) {
  54619. var a = document.createElement('a');
  54620. a.href = url;
  54621. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  54622. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  54623. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  54624. return absLocation;
  54625. };
  54626. Database.ReturnFullUrlLocation = function (url) {
  54627. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  54628. return (Database.parseURL(window.location.href) + url);
  54629. }
  54630. else {
  54631. return url;
  54632. }
  54633. };
  54634. return Database;
  54635. }());
  54636. BABYLON.Database = Database;
  54637. })(BABYLON || (BABYLON = {}));
  54638. //# sourceMappingURL=babylon.database.js.map
  54639. var BABYLON;
  54640. (function (BABYLON) {
  54641. var FresnelParameters = /** @class */ (function () {
  54642. function FresnelParameters() {
  54643. this._isEnabled = true;
  54644. this.leftColor = BABYLON.Color3.White();
  54645. this.rightColor = BABYLON.Color3.Black();
  54646. this.bias = 0;
  54647. this.power = 1;
  54648. }
  54649. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  54650. get: function () {
  54651. return this._isEnabled;
  54652. },
  54653. set: function (value) {
  54654. if (this._isEnabled === value) {
  54655. return;
  54656. }
  54657. this._isEnabled = value;
  54658. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  54659. },
  54660. enumerable: true,
  54661. configurable: true
  54662. });
  54663. FresnelParameters.prototype.clone = function () {
  54664. var newFresnelParameters = new FresnelParameters();
  54665. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  54666. return newFresnelParameters;
  54667. };
  54668. FresnelParameters.prototype.serialize = function () {
  54669. var serializationObject = {};
  54670. serializationObject.isEnabled = this.isEnabled;
  54671. serializationObject.leftColor = this.leftColor;
  54672. serializationObject.rightColor = this.rightColor;
  54673. serializationObject.bias = this.bias;
  54674. serializationObject.power = this.power;
  54675. return serializationObject;
  54676. };
  54677. FresnelParameters.Parse = function (parsedFresnelParameters) {
  54678. var fresnelParameters = new FresnelParameters();
  54679. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  54680. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  54681. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  54682. fresnelParameters.bias = parsedFresnelParameters.bias;
  54683. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  54684. return fresnelParameters;
  54685. };
  54686. return FresnelParameters;
  54687. }());
  54688. BABYLON.FresnelParameters = FresnelParameters;
  54689. })(BABYLON || (BABYLON = {}));
  54690. //# sourceMappingURL=babylon.fresnelParameters.js.map
  54691. var BABYLON;
  54692. (function (BABYLON) {
  54693. var MultiMaterial = /** @class */ (function (_super) {
  54694. __extends(MultiMaterial, _super);
  54695. function MultiMaterial(name, scene) {
  54696. var _this = _super.call(this, name, scene, true) || this;
  54697. scene.multiMaterials.push(_this);
  54698. _this.subMaterials = new Array();
  54699. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  54700. return _this;
  54701. }
  54702. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  54703. get: function () {
  54704. return this._subMaterials;
  54705. },
  54706. set: function (value) {
  54707. this._subMaterials = value;
  54708. this._hookArray(value);
  54709. },
  54710. enumerable: true,
  54711. configurable: true
  54712. });
  54713. MultiMaterial.prototype._hookArray = function (array) {
  54714. var _this = this;
  54715. var oldPush = array.push;
  54716. array.push = function () {
  54717. var items = [];
  54718. for (var _i = 0; _i < arguments.length; _i++) {
  54719. items[_i] = arguments[_i];
  54720. }
  54721. var result = oldPush.apply(array, items);
  54722. _this._markAllSubMeshesAsTexturesDirty();
  54723. return result;
  54724. };
  54725. var oldSplice = array.splice;
  54726. array.splice = function (index, deleteCount) {
  54727. var deleted = oldSplice.apply(array, [index, deleteCount]);
  54728. _this._markAllSubMeshesAsTexturesDirty();
  54729. return deleted;
  54730. };
  54731. };
  54732. // Properties
  54733. MultiMaterial.prototype.getSubMaterial = function (index) {
  54734. if (index < 0 || index >= this.subMaterials.length) {
  54735. return this.getScene().defaultMaterial;
  54736. }
  54737. return this.subMaterials[index];
  54738. };
  54739. MultiMaterial.prototype.getActiveTextures = function () {
  54740. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  54741. if (subMaterial) {
  54742. return subMaterial.getActiveTextures();
  54743. }
  54744. else {
  54745. return [];
  54746. }
  54747. }));
  54748. var _a;
  54749. };
  54750. // Methods
  54751. MultiMaterial.prototype.getClassName = function () {
  54752. return "MultiMaterial";
  54753. };
  54754. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  54755. for (var index = 0; index < this.subMaterials.length; index++) {
  54756. var subMaterial = this.subMaterials[index];
  54757. if (subMaterial) {
  54758. if (subMaterial.storeEffectOnSubMeshes) {
  54759. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  54760. return false;
  54761. }
  54762. continue;
  54763. }
  54764. if (!subMaterial.isReady(mesh)) {
  54765. return false;
  54766. }
  54767. }
  54768. }
  54769. return true;
  54770. };
  54771. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  54772. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  54773. for (var index = 0; index < this.subMaterials.length; index++) {
  54774. var subMaterial = null;
  54775. var current = this.subMaterials[index];
  54776. if (cloneChildren && current) {
  54777. subMaterial = current.clone(name + "-" + current.name);
  54778. }
  54779. else {
  54780. subMaterial = this.subMaterials[index];
  54781. }
  54782. newMultiMaterial.subMaterials.push(subMaterial);
  54783. }
  54784. return newMultiMaterial;
  54785. };
  54786. MultiMaterial.prototype.serialize = function () {
  54787. var serializationObject = {};
  54788. serializationObject.name = this.name;
  54789. serializationObject.id = this.id;
  54790. serializationObject.tags = BABYLON.Tags.GetTags(this);
  54791. serializationObject.materials = [];
  54792. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  54793. var subMat = this.subMaterials[matIndex];
  54794. if (subMat) {
  54795. serializationObject.materials.push(subMat.id);
  54796. }
  54797. else {
  54798. serializationObject.materials.push(null);
  54799. }
  54800. }
  54801. return serializationObject;
  54802. };
  54803. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54804. var scene = this.getScene();
  54805. if (!scene) {
  54806. return;
  54807. }
  54808. var index = scene.multiMaterials.indexOf(this);
  54809. if (index >= 0) {
  54810. scene.multiMaterials.splice(index, 1);
  54811. }
  54812. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54813. };
  54814. return MultiMaterial;
  54815. }(BABYLON.Material));
  54816. BABYLON.MultiMaterial = MultiMaterial;
  54817. })(BABYLON || (BABYLON = {}));
  54818. //# sourceMappingURL=babylon.multiMaterial.js.map
  54819. var BABYLON;
  54820. (function (BABYLON) {
  54821. var FreeCameraTouchInput = /** @class */ (function () {
  54822. function FreeCameraTouchInput() {
  54823. this._offsetX = null;
  54824. this._offsetY = null;
  54825. this._pointerCount = 0;
  54826. this._pointerPressed = new Array();
  54827. this.touchAngularSensibility = 200000.0;
  54828. this.touchMoveSensibility = 250.0;
  54829. }
  54830. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  54831. var _this = this;
  54832. var previousPosition = null;
  54833. if (this._pointerInput === undefined) {
  54834. this._onLostFocus = function (evt) {
  54835. _this._offsetX = null;
  54836. _this._offsetY = null;
  54837. };
  54838. this._pointerInput = function (p, s) {
  54839. var evt = p.event;
  54840. if (evt.pointerType === "mouse") {
  54841. return;
  54842. }
  54843. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  54844. if (!noPreventDefault) {
  54845. evt.preventDefault();
  54846. }
  54847. _this._pointerPressed.push(evt.pointerId);
  54848. if (_this._pointerPressed.length !== 1) {
  54849. return;
  54850. }
  54851. previousPosition = {
  54852. x: evt.clientX,
  54853. y: evt.clientY
  54854. };
  54855. }
  54856. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  54857. if (!noPreventDefault) {
  54858. evt.preventDefault();
  54859. }
  54860. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54861. if (index === -1) {
  54862. return;
  54863. }
  54864. _this._pointerPressed.splice(index, 1);
  54865. if (index != 0) {
  54866. return;
  54867. }
  54868. previousPosition = null;
  54869. _this._offsetX = null;
  54870. _this._offsetY = null;
  54871. }
  54872. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  54873. if (!noPreventDefault) {
  54874. evt.preventDefault();
  54875. }
  54876. if (!previousPosition) {
  54877. return;
  54878. }
  54879. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54880. if (index != 0) {
  54881. return;
  54882. }
  54883. _this._offsetX = evt.clientX - previousPosition.x;
  54884. _this._offsetY = -(evt.clientY - previousPosition.y);
  54885. }
  54886. };
  54887. }
  54888. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  54889. if (this._onLostFocus) {
  54890. element.addEventListener("blur", this._onLostFocus);
  54891. }
  54892. };
  54893. FreeCameraTouchInput.prototype.detachControl = function (element) {
  54894. if (this._pointerInput && element) {
  54895. if (this._observer) {
  54896. this.camera.getScene().onPointerObservable.remove(this._observer);
  54897. this._observer = null;
  54898. }
  54899. if (this._onLostFocus) {
  54900. element.removeEventListener("blur", this._onLostFocus);
  54901. this._onLostFocus = null;
  54902. }
  54903. this._pointerPressed = [];
  54904. this._offsetX = null;
  54905. this._offsetY = null;
  54906. this._pointerCount = 0;
  54907. }
  54908. };
  54909. FreeCameraTouchInput.prototype.checkInputs = function () {
  54910. if (this._offsetX && this._offsetY) {
  54911. var camera = this.camera;
  54912. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  54913. if (this._pointerPressed.length > 1) {
  54914. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  54915. }
  54916. else {
  54917. var speed = camera._computeLocalCameraSpeed();
  54918. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  54919. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  54920. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  54921. }
  54922. }
  54923. };
  54924. FreeCameraTouchInput.prototype.getClassName = function () {
  54925. return "FreeCameraTouchInput";
  54926. };
  54927. FreeCameraTouchInput.prototype.getSimpleName = function () {
  54928. return "touch";
  54929. };
  54930. __decorate([
  54931. BABYLON.serialize()
  54932. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  54933. __decorate([
  54934. BABYLON.serialize()
  54935. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  54936. return FreeCameraTouchInput;
  54937. }());
  54938. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  54939. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  54940. })(BABYLON || (BABYLON = {}));
  54941. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  54942. var BABYLON;
  54943. (function (BABYLON) {
  54944. // We're mainly based on the logic defined into the FreeCamera code
  54945. var TouchCamera = /** @class */ (function (_super) {
  54946. __extends(TouchCamera, _super);
  54947. //-- end properties for backward compatibility for inputs
  54948. function TouchCamera(name, position, scene) {
  54949. var _this = _super.call(this, name, position, scene) || this;
  54950. _this.inputs.addTouch();
  54951. _this._setupInputs();
  54952. return _this;
  54953. }
  54954. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  54955. //-- Begin properties for backward compatibility for inputs
  54956. get: function () {
  54957. var touch = this.inputs.attached["touch"];
  54958. if (touch)
  54959. return touch.touchAngularSensibility;
  54960. return 0;
  54961. },
  54962. set: function (value) {
  54963. var touch = this.inputs.attached["touch"];
  54964. if (touch)
  54965. touch.touchAngularSensibility = value;
  54966. },
  54967. enumerable: true,
  54968. configurable: true
  54969. });
  54970. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  54971. get: function () {
  54972. var touch = this.inputs.attached["touch"];
  54973. if (touch)
  54974. return touch.touchMoveSensibility;
  54975. return 0;
  54976. },
  54977. set: function (value) {
  54978. var touch = this.inputs.attached["touch"];
  54979. if (touch)
  54980. touch.touchMoveSensibility = value;
  54981. },
  54982. enumerable: true,
  54983. configurable: true
  54984. });
  54985. TouchCamera.prototype.getClassName = function () {
  54986. return "TouchCamera";
  54987. };
  54988. TouchCamera.prototype._setupInputs = function () {
  54989. var mouse = this.inputs.attached["mouse"];
  54990. if (mouse) {
  54991. mouse.touchEnabled = false;
  54992. }
  54993. };
  54994. return TouchCamera;
  54995. }(BABYLON.FreeCamera));
  54996. BABYLON.TouchCamera = TouchCamera;
  54997. })(BABYLON || (BABYLON = {}));
  54998. //# sourceMappingURL=babylon.touchCamera.js.map
  54999. var BABYLON;
  55000. (function (BABYLON) {
  55001. var ProceduralTexture = /** @class */ (function (_super) {
  55002. __extends(ProceduralTexture, _super);
  55003. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  55004. if (fallbackTexture === void 0) { fallbackTexture = null; }
  55005. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55006. if (isCube === void 0) { isCube = false; }
  55007. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  55008. _this.isCube = isCube;
  55009. _this.isEnabled = true;
  55010. _this._currentRefreshId = -1;
  55011. _this._refreshRate = 1;
  55012. _this._vertexBuffers = {};
  55013. _this._uniforms = new Array();
  55014. _this._samplers = new Array();
  55015. _this._textures = {};
  55016. _this._floats = {};
  55017. _this._floatsArrays = {};
  55018. _this._colors3 = {};
  55019. _this._colors4 = {};
  55020. _this._vectors2 = {};
  55021. _this._vectors3 = {};
  55022. _this._matrices = {};
  55023. _this._fallbackTextureUsed = false;
  55024. scene._proceduralTextures.push(_this);
  55025. _this._engine = scene.getEngine();
  55026. _this.name = name;
  55027. _this.isRenderTarget = true;
  55028. _this._size = size;
  55029. _this._generateMipMaps = generateMipMaps;
  55030. _this.setFragment(fragment);
  55031. _this._fallbackTexture = fallbackTexture;
  55032. if (isCube) {
  55033. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  55034. _this.setFloat("face", 0);
  55035. }
  55036. else {
  55037. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  55038. }
  55039. // VBO
  55040. var vertices = [];
  55041. vertices.push(1, 1);
  55042. vertices.push(-1, 1);
  55043. vertices.push(-1, -1);
  55044. vertices.push(1, -1);
  55045. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  55046. _this._createIndexBuffer();
  55047. return _this;
  55048. }
  55049. ProceduralTexture.prototype._createIndexBuffer = function () {
  55050. var engine = this._engine;
  55051. // Indices
  55052. var indices = [];
  55053. indices.push(0);
  55054. indices.push(1);
  55055. indices.push(2);
  55056. indices.push(0);
  55057. indices.push(2);
  55058. indices.push(3);
  55059. this._indexBuffer = engine.createIndexBuffer(indices);
  55060. };
  55061. ProceduralTexture.prototype._rebuild = function () {
  55062. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55063. if (vb) {
  55064. vb._rebuild();
  55065. }
  55066. this._createIndexBuffer();
  55067. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  55068. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  55069. }
  55070. };
  55071. ProceduralTexture.prototype.reset = function () {
  55072. if (this._effect === undefined) {
  55073. return;
  55074. }
  55075. var engine = this._engine;
  55076. engine._releaseEffect(this._effect);
  55077. };
  55078. ProceduralTexture.prototype.isReady = function () {
  55079. var _this = this;
  55080. var engine = this._engine;
  55081. var shaders;
  55082. if (!this._fragment) {
  55083. return false;
  55084. }
  55085. if (this._fallbackTextureUsed) {
  55086. return true;
  55087. }
  55088. if (this._fragment.fragmentElement !== undefined) {
  55089. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  55090. }
  55091. else {
  55092. shaders = { vertex: "procedural", fragment: this._fragment };
  55093. }
  55094. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  55095. _this.releaseInternalTexture();
  55096. if (_this._fallbackTexture) {
  55097. _this._texture = _this._fallbackTexture._texture;
  55098. if (_this._texture) {
  55099. _this._texture.incrementReferences();
  55100. }
  55101. }
  55102. _this._fallbackTextureUsed = true;
  55103. });
  55104. return this._effect.isReady();
  55105. };
  55106. ProceduralTexture.prototype.resetRefreshCounter = function () {
  55107. this._currentRefreshId = -1;
  55108. };
  55109. ProceduralTexture.prototype.setFragment = function (fragment) {
  55110. this._fragment = fragment;
  55111. };
  55112. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  55113. get: function () {
  55114. return this._refreshRate;
  55115. },
  55116. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  55117. set: function (value) {
  55118. this._refreshRate = value;
  55119. this.resetRefreshCounter();
  55120. },
  55121. enumerable: true,
  55122. configurable: true
  55123. });
  55124. ProceduralTexture.prototype._shouldRender = function () {
  55125. if (!this.isEnabled || !this.isReady() || !this._texture) {
  55126. return false;
  55127. }
  55128. if (this._fallbackTextureUsed) {
  55129. return false;
  55130. }
  55131. if (this._currentRefreshId === -1) {
  55132. this._currentRefreshId = 1;
  55133. return true;
  55134. }
  55135. if (this.refreshRate === this._currentRefreshId) {
  55136. this._currentRefreshId = 1;
  55137. return true;
  55138. }
  55139. this._currentRefreshId++;
  55140. return false;
  55141. };
  55142. ProceduralTexture.prototype.getRenderSize = function () {
  55143. return this._size;
  55144. };
  55145. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  55146. if (this._fallbackTextureUsed) {
  55147. return;
  55148. }
  55149. this.releaseInternalTexture();
  55150. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  55151. };
  55152. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  55153. if (this._uniforms.indexOf(uniformName) === -1) {
  55154. this._uniforms.push(uniformName);
  55155. }
  55156. };
  55157. ProceduralTexture.prototype.setTexture = function (name, texture) {
  55158. if (this._samplers.indexOf(name) === -1) {
  55159. this._samplers.push(name);
  55160. }
  55161. this._textures[name] = texture;
  55162. return this;
  55163. };
  55164. ProceduralTexture.prototype.setFloat = function (name, value) {
  55165. this._checkUniform(name);
  55166. this._floats[name] = value;
  55167. return this;
  55168. };
  55169. ProceduralTexture.prototype.setFloats = function (name, value) {
  55170. this._checkUniform(name);
  55171. this._floatsArrays[name] = value;
  55172. return this;
  55173. };
  55174. ProceduralTexture.prototype.setColor3 = function (name, value) {
  55175. this._checkUniform(name);
  55176. this._colors3[name] = value;
  55177. return this;
  55178. };
  55179. ProceduralTexture.prototype.setColor4 = function (name, value) {
  55180. this._checkUniform(name);
  55181. this._colors4[name] = value;
  55182. return this;
  55183. };
  55184. ProceduralTexture.prototype.setVector2 = function (name, value) {
  55185. this._checkUniform(name);
  55186. this._vectors2[name] = value;
  55187. return this;
  55188. };
  55189. ProceduralTexture.prototype.setVector3 = function (name, value) {
  55190. this._checkUniform(name);
  55191. this._vectors3[name] = value;
  55192. return this;
  55193. };
  55194. ProceduralTexture.prototype.setMatrix = function (name, value) {
  55195. this._checkUniform(name);
  55196. this._matrices[name] = value;
  55197. return this;
  55198. };
  55199. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55200. var scene = this.getScene();
  55201. if (!scene) {
  55202. return;
  55203. }
  55204. var engine = this._engine;
  55205. // Render
  55206. engine.enableEffect(this._effect);
  55207. engine.setState(false);
  55208. // Texture
  55209. for (var name in this._textures) {
  55210. this._effect.setTexture(name, this._textures[name]);
  55211. }
  55212. // Float
  55213. for (name in this._floats) {
  55214. this._effect.setFloat(name, this._floats[name]);
  55215. }
  55216. // Floats
  55217. for (name in this._floatsArrays) {
  55218. this._effect.setArray(name, this._floatsArrays[name]);
  55219. }
  55220. // Color3
  55221. for (name in this._colors3) {
  55222. this._effect.setColor3(name, this._colors3[name]);
  55223. }
  55224. // Color4
  55225. for (name in this._colors4) {
  55226. var color = this._colors4[name];
  55227. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55228. }
  55229. // Vector2
  55230. for (name in this._vectors2) {
  55231. this._effect.setVector2(name, this._vectors2[name]);
  55232. }
  55233. // Vector3
  55234. for (name in this._vectors3) {
  55235. this._effect.setVector3(name, this._vectors3[name]);
  55236. }
  55237. // Matrix
  55238. for (name in this._matrices) {
  55239. this._effect.setMatrix(name, this._matrices[name]);
  55240. }
  55241. if (!this._texture) {
  55242. return;
  55243. }
  55244. if (this.isCube) {
  55245. for (var face = 0; face < 6; face++) {
  55246. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  55247. // VBOs
  55248. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55249. this._effect.setFloat("face", face);
  55250. // Clear
  55251. engine.clear(scene.clearColor, true, true, true);
  55252. // Draw order
  55253. engine.draw(true, 0, 6);
  55254. // Mipmaps
  55255. if (face === 5) {
  55256. engine.generateMipMapsForCubemap(this._texture);
  55257. }
  55258. }
  55259. }
  55260. else {
  55261. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  55262. // VBOs
  55263. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  55264. // Clear
  55265. engine.clear(scene.clearColor, true, true, true);
  55266. // Draw order
  55267. engine.draw(true, 0, 6);
  55268. }
  55269. // Unbind
  55270. engine.unBindFramebuffer(this._texture, this.isCube);
  55271. if (this.onGenerated) {
  55272. this.onGenerated();
  55273. }
  55274. };
  55275. ProceduralTexture.prototype.clone = function () {
  55276. var textureSize = this.getSize();
  55277. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  55278. // Base texture
  55279. newTexture.hasAlpha = this.hasAlpha;
  55280. newTexture.level = this.level;
  55281. // RenderTarget Texture
  55282. newTexture.coordinatesMode = this.coordinatesMode;
  55283. return newTexture;
  55284. };
  55285. ProceduralTexture.prototype.dispose = function () {
  55286. var scene = this.getScene();
  55287. if (!scene) {
  55288. return;
  55289. }
  55290. var index = scene._proceduralTextures.indexOf(this);
  55291. if (index >= 0) {
  55292. scene._proceduralTextures.splice(index, 1);
  55293. }
  55294. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  55295. if (vertexBuffer) {
  55296. vertexBuffer.dispose();
  55297. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  55298. }
  55299. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  55300. this._indexBuffer = null;
  55301. }
  55302. _super.prototype.dispose.call(this);
  55303. };
  55304. return ProceduralTexture;
  55305. }(BABYLON.Texture));
  55306. BABYLON.ProceduralTexture = ProceduralTexture;
  55307. })(BABYLON || (BABYLON = {}));
  55308. //# sourceMappingURL=babylon.proceduralTexture.js.map
  55309. var BABYLON;
  55310. (function (BABYLON) {
  55311. var CustomProceduralTexture = /** @class */ (function (_super) {
  55312. __extends(CustomProceduralTexture, _super);
  55313. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  55314. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  55315. _this._animate = true;
  55316. _this._time = 0;
  55317. _this._texturePath = texturePath;
  55318. //Try to load json
  55319. _this.loadJson(texturePath);
  55320. _this.refreshRate = 1;
  55321. return _this;
  55322. }
  55323. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  55324. var _this = this;
  55325. var noConfigFile = function () {
  55326. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  55327. try {
  55328. _this.setFragment(_this._texturePath);
  55329. }
  55330. catch (ex) {
  55331. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  55332. }
  55333. };
  55334. var configFileUrl = jsonUrl + "/config.json";
  55335. var xhr = new XMLHttpRequest();
  55336. xhr.open("GET", configFileUrl, true);
  55337. xhr.addEventListener("load", function () {
  55338. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  55339. try {
  55340. _this._config = JSON.parse(xhr.response);
  55341. _this.updateShaderUniforms();
  55342. _this.updateTextures();
  55343. _this.setFragment(_this._texturePath + "/custom");
  55344. _this._animate = _this._config.animate;
  55345. _this.refreshRate = _this._config.refreshrate;
  55346. }
  55347. catch (ex) {
  55348. noConfigFile();
  55349. }
  55350. }
  55351. else {
  55352. noConfigFile();
  55353. }
  55354. }, false);
  55355. xhr.addEventListener("error", function () {
  55356. noConfigFile();
  55357. }, false);
  55358. try {
  55359. xhr.send();
  55360. }
  55361. catch (ex) {
  55362. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  55363. }
  55364. };
  55365. CustomProceduralTexture.prototype.isReady = function () {
  55366. if (!_super.prototype.isReady.call(this)) {
  55367. return false;
  55368. }
  55369. for (var name in this._textures) {
  55370. var texture = this._textures[name];
  55371. if (!texture.isReady()) {
  55372. return false;
  55373. }
  55374. }
  55375. return true;
  55376. };
  55377. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  55378. var scene = this.getScene();
  55379. if (this._animate && scene) {
  55380. this._time += scene.getAnimationRatio() * 0.03;
  55381. this.updateShaderUniforms();
  55382. }
  55383. _super.prototype.render.call(this, useCameraPostProcess);
  55384. };
  55385. CustomProceduralTexture.prototype.updateTextures = function () {
  55386. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  55387. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  55388. }
  55389. };
  55390. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  55391. if (this._config) {
  55392. for (var j = 0; j < this._config.uniforms.length; j++) {
  55393. var uniform = this._config.uniforms[j];
  55394. switch (uniform.type) {
  55395. case "float":
  55396. this.setFloat(uniform.name, uniform.value);
  55397. break;
  55398. case "color3":
  55399. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  55400. break;
  55401. case "color4":
  55402. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  55403. break;
  55404. case "vector2":
  55405. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  55406. break;
  55407. case "vector3":
  55408. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  55409. break;
  55410. }
  55411. }
  55412. }
  55413. this.setFloat("time", this._time);
  55414. };
  55415. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  55416. get: function () {
  55417. return this._animate;
  55418. },
  55419. set: function (value) {
  55420. this._animate = value;
  55421. },
  55422. enumerable: true,
  55423. configurable: true
  55424. });
  55425. return CustomProceduralTexture;
  55426. }(BABYLON.ProceduralTexture));
  55427. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  55428. })(BABYLON || (BABYLON = {}));
  55429. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  55430. var BABYLON;
  55431. (function (BABYLON) {
  55432. var FreeCameraGamepadInput = /** @class */ (function () {
  55433. function FreeCameraGamepadInput() {
  55434. this.gamepadAngularSensibility = 200;
  55435. this.gamepadMoveSensibility = 40;
  55436. // private members
  55437. this._cameraTransform = BABYLON.Matrix.Identity();
  55438. this._deltaTransform = BABYLON.Vector3.Zero();
  55439. this._vector3 = BABYLON.Vector3.Zero();
  55440. this._vector2 = BABYLON.Vector2.Zero();
  55441. }
  55442. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55443. var _this = this;
  55444. var manager = this.camera.getScene().gamepadManager;
  55445. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55446. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55447. // prioritize XBOX gamepads.
  55448. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55449. _this.gamepad = gamepad;
  55450. }
  55451. }
  55452. });
  55453. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55454. if (_this.gamepad === gamepad) {
  55455. _this.gamepad = null;
  55456. }
  55457. });
  55458. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55459. };
  55460. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  55461. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55462. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55463. this.gamepad = null;
  55464. };
  55465. FreeCameraGamepadInput.prototype.checkInputs = function () {
  55466. if (this.gamepad && this.gamepad.leftStick) {
  55467. var camera = this.camera;
  55468. var LSValues = this.gamepad.leftStick;
  55469. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  55470. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55471. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  55472. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  55473. var RSValues = this.gamepad.rightStick;
  55474. if (RSValues) {
  55475. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  55476. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  55477. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  55478. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  55479. }
  55480. else {
  55481. RSValues = { x: 0, y: 0 };
  55482. }
  55483. if (!camera.rotationQuaternion) {
  55484. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  55485. }
  55486. else {
  55487. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  55488. }
  55489. var speed = camera._computeLocalCameraSpeed() * 50.0;
  55490. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  55491. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  55492. camera.cameraDirection.addInPlace(this._deltaTransform);
  55493. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  55494. camera.cameraRotation.addInPlace(this._vector2);
  55495. }
  55496. };
  55497. FreeCameraGamepadInput.prototype.getClassName = function () {
  55498. return "FreeCameraGamepadInput";
  55499. };
  55500. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  55501. return "gamepad";
  55502. };
  55503. __decorate([
  55504. BABYLON.serialize()
  55505. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  55506. __decorate([
  55507. BABYLON.serialize()
  55508. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55509. return FreeCameraGamepadInput;
  55510. }());
  55511. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  55512. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  55513. })(BABYLON || (BABYLON = {}));
  55514. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  55515. var BABYLON;
  55516. (function (BABYLON) {
  55517. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  55518. function ArcRotateCameraGamepadInput() {
  55519. this.gamepadRotationSensibility = 80;
  55520. this.gamepadMoveSensibility = 40;
  55521. }
  55522. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55523. var _this = this;
  55524. var manager = this.camera.getScene().gamepadManager;
  55525. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55526. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55527. // prioritize XBOX gamepads.
  55528. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55529. _this.gamepad = gamepad;
  55530. }
  55531. }
  55532. });
  55533. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55534. if (_this.gamepad === gamepad) {
  55535. _this.gamepad = null;
  55536. }
  55537. });
  55538. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55539. };
  55540. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  55541. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55542. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55543. this.gamepad = null;
  55544. };
  55545. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  55546. if (this.gamepad) {
  55547. var camera = this.camera;
  55548. var RSValues = this.gamepad.rightStick;
  55549. if (RSValues) {
  55550. if (RSValues.x != 0) {
  55551. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  55552. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  55553. camera.inertialAlphaOffset += normalizedRX;
  55554. }
  55555. }
  55556. if (RSValues.y != 0) {
  55557. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  55558. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  55559. camera.inertialBetaOffset += normalizedRY;
  55560. }
  55561. }
  55562. }
  55563. var LSValues = this.gamepad.leftStick;
  55564. if (LSValues && LSValues.y != 0) {
  55565. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55566. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  55567. this.camera.inertialRadiusOffset -= normalizedLY;
  55568. }
  55569. }
  55570. }
  55571. };
  55572. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  55573. return "ArcRotateCameraGamepadInput";
  55574. };
  55575. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  55576. return "gamepad";
  55577. };
  55578. __decorate([
  55579. BABYLON.serialize()
  55580. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  55581. __decorate([
  55582. BABYLON.serialize()
  55583. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55584. return ArcRotateCameraGamepadInput;
  55585. }());
  55586. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  55587. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  55588. })(BABYLON || (BABYLON = {}));
  55589. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  55590. var BABYLON;
  55591. (function (BABYLON) {
  55592. var GamepadManager = /** @class */ (function () {
  55593. function GamepadManager() {
  55594. var _this = this;
  55595. this._babylonGamepads = [];
  55596. this._oneGamepadConnected = false;
  55597. this._isMonitoring = false;
  55598. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  55599. if (!BABYLON.Tools.IsWindowObjectExist()) {
  55600. this._gamepadEventSupported = false;
  55601. }
  55602. else {
  55603. this._gamepadEventSupported = 'GamepadEvent' in window;
  55604. this._gamepadSupport = (navigator.getGamepads ||
  55605. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  55606. }
  55607. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  55608. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  55609. for (var i in _this._babylonGamepads) {
  55610. var gamepad = _this._babylonGamepads[i];
  55611. if (gamepad && gamepad._isConnected) {
  55612. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  55613. }
  55614. }
  55615. });
  55616. this._onGamepadConnectedEvent = function (evt) {
  55617. var gamepad = evt.gamepad;
  55618. if (gamepad.index in _this._babylonGamepads) {
  55619. if (_this._babylonGamepads[gamepad.index].isConnected) {
  55620. return;
  55621. }
  55622. }
  55623. var newGamepad;
  55624. if (_this._babylonGamepads[gamepad.index]) {
  55625. newGamepad = _this._babylonGamepads[gamepad.index];
  55626. newGamepad.browserGamepad = gamepad;
  55627. newGamepad._isConnected = true;
  55628. }
  55629. else {
  55630. newGamepad = _this._addNewGamepad(gamepad);
  55631. }
  55632. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55633. _this._startMonitoringGamepads();
  55634. };
  55635. this._onGamepadDisconnectedEvent = function (evt) {
  55636. var gamepad = evt.gamepad;
  55637. // Remove the gamepad from the list of gamepads to monitor.
  55638. for (var i in _this._babylonGamepads) {
  55639. if (_this._babylonGamepads[i].index === gamepad.index) {
  55640. var disconnectedGamepad = _this._babylonGamepads[i];
  55641. disconnectedGamepad._isConnected = false;
  55642. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  55643. break;
  55644. }
  55645. }
  55646. };
  55647. if (this._gamepadSupport) {
  55648. //first add already-connected gamepads
  55649. this._updateGamepadObjects();
  55650. if (this._babylonGamepads.length) {
  55651. this._startMonitoringGamepads();
  55652. }
  55653. // Checking if the gamepad connected event is supported (like in Firefox)
  55654. if (this._gamepadEventSupported) {
  55655. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55656. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  55657. }
  55658. else {
  55659. this._startMonitoringGamepads();
  55660. }
  55661. }
  55662. }
  55663. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  55664. get: function () {
  55665. return this._babylonGamepads;
  55666. },
  55667. enumerable: true,
  55668. configurable: true
  55669. });
  55670. GamepadManager.prototype.getGamepadByType = function (type) {
  55671. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  55672. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  55673. var gamepad = _a[_i];
  55674. if (gamepad && gamepad.type === type) {
  55675. return gamepad;
  55676. }
  55677. }
  55678. return null;
  55679. };
  55680. GamepadManager.prototype.dispose = function () {
  55681. if (this._gamepadEventSupported) {
  55682. if (this._onGamepadConnectedEvent) {
  55683. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  55684. }
  55685. if (this._onGamepadDisconnectedEvent) {
  55686. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  55687. }
  55688. this._onGamepadConnectedEvent = null;
  55689. this._onGamepadDisconnectedEvent = null;
  55690. }
  55691. this._babylonGamepads.forEach(function (gamepad) {
  55692. gamepad.dispose();
  55693. });
  55694. this.onGamepadConnectedObservable.clear();
  55695. this.onGamepadDisconnectedObservable.clear();
  55696. this._oneGamepadConnected = false;
  55697. this._stopMonitoringGamepads();
  55698. this._babylonGamepads = [];
  55699. };
  55700. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  55701. if (!this._oneGamepadConnected) {
  55702. this._oneGamepadConnected = true;
  55703. }
  55704. var newGamepad;
  55705. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  55706. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  55707. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  55708. }
  55709. else if (gamepad.pose) {
  55710. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  55711. }
  55712. else {
  55713. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  55714. }
  55715. this._babylonGamepads[newGamepad.index] = newGamepad;
  55716. return newGamepad;
  55717. };
  55718. GamepadManager.prototype._startMonitoringGamepads = function () {
  55719. if (!this._isMonitoring) {
  55720. this._isMonitoring = true;
  55721. this._checkGamepadsStatus();
  55722. }
  55723. };
  55724. GamepadManager.prototype._stopMonitoringGamepads = function () {
  55725. this._isMonitoring = false;
  55726. };
  55727. GamepadManager.prototype._checkGamepadsStatus = function () {
  55728. var _this = this;
  55729. // Hack to be compatible Chrome
  55730. this._updateGamepadObjects();
  55731. for (var i in this._babylonGamepads) {
  55732. var gamepad = this._babylonGamepads[i];
  55733. if (!gamepad || !gamepad.isConnected) {
  55734. continue;
  55735. }
  55736. gamepad.update();
  55737. }
  55738. if (this._isMonitoring) {
  55739. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  55740. }
  55741. };
  55742. // This function is called only on Chrome, which does not properly support
  55743. // connection/disconnection events and forces you to recopy again the gamepad object
  55744. GamepadManager.prototype._updateGamepadObjects = function () {
  55745. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  55746. for (var i = 0; i < gamepads.length; i++) {
  55747. if (gamepads[i]) {
  55748. if (!this._babylonGamepads[gamepads[i].index]) {
  55749. var newGamepad = this._addNewGamepad(gamepads[i]);
  55750. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55751. }
  55752. else {
  55753. // Forced to copy again this object for Chrome for unknown reason
  55754. this._babylonGamepads[i].browserGamepad = gamepads[i];
  55755. if (!this._babylonGamepads[i].isConnected) {
  55756. this._babylonGamepads[i]._isConnected = true;
  55757. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  55758. }
  55759. }
  55760. }
  55761. }
  55762. };
  55763. return GamepadManager;
  55764. }());
  55765. BABYLON.GamepadManager = GamepadManager;
  55766. })(BABYLON || (BABYLON = {}));
  55767. //# sourceMappingURL=babylon.gamepadManager.js.map
  55768. var BABYLON;
  55769. (function (BABYLON) {
  55770. var StickValues = /** @class */ (function () {
  55771. function StickValues(x, y) {
  55772. this.x = x;
  55773. this.y = y;
  55774. }
  55775. return StickValues;
  55776. }());
  55777. BABYLON.StickValues = StickValues;
  55778. var Gamepad = /** @class */ (function () {
  55779. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  55780. if (leftStickX === void 0) { leftStickX = 0; }
  55781. if (leftStickY === void 0) { leftStickY = 1; }
  55782. if (rightStickX === void 0) { rightStickX = 2; }
  55783. if (rightStickY === void 0) { rightStickY = 3; }
  55784. this.id = id;
  55785. this.index = index;
  55786. this.browserGamepad = browserGamepad;
  55787. this._isConnected = true;
  55788. this.type = Gamepad.GAMEPAD;
  55789. this._leftStickAxisX = leftStickX;
  55790. this._leftStickAxisY = leftStickY;
  55791. this._rightStickAxisX = rightStickX;
  55792. this._rightStickAxisY = rightStickY;
  55793. if (this.browserGamepad.axes.length >= 2) {
  55794. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55795. }
  55796. if (this.browserGamepad.axes.length >= 4) {
  55797. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55798. }
  55799. }
  55800. Object.defineProperty(Gamepad.prototype, "isConnected", {
  55801. get: function () {
  55802. return this._isConnected;
  55803. },
  55804. enumerable: true,
  55805. configurable: true
  55806. });
  55807. Gamepad.prototype.onleftstickchanged = function (callback) {
  55808. this._onleftstickchanged = callback;
  55809. };
  55810. Gamepad.prototype.onrightstickchanged = function (callback) {
  55811. this._onrightstickchanged = callback;
  55812. };
  55813. Object.defineProperty(Gamepad.prototype, "leftStick", {
  55814. get: function () {
  55815. return this._leftStick;
  55816. },
  55817. set: function (newValues) {
  55818. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  55819. this._onleftstickchanged(newValues);
  55820. }
  55821. this._leftStick = newValues;
  55822. },
  55823. enumerable: true,
  55824. configurable: true
  55825. });
  55826. Object.defineProperty(Gamepad.prototype, "rightStick", {
  55827. get: function () {
  55828. return this._rightStick;
  55829. },
  55830. set: function (newValues) {
  55831. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  55832. this._onrightstickchanged(newValues);
  55833. }
  55834. this._rightStick = newValues;
  55835. },
  55836. enumerable: true,
  55837. configurable: true
  55838. });
  55839. Gamepad.prototype.update = function () {
  55840. if (this._leftStick) {
  55841. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55842. }
  55843. if (this._rightStick) {
  55844. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55845. }
  55846. };
  55847. Gamepad.prototype.dispose = function () {
  55848. };
  55849. Gamepad.GAMEPAD = 0;
  55850. Gamepad.GENERIC = 1;
  55851. Gamepad.XBOX = 2;
  55852. Gamepad.POSE_ENABLED = 3;
  55853. return Gamepad;
  55854. }());
  55855. BABYLON.Gamepad = Gamepad;
  55856. var GenericPad = /** @class */ (function (_super) {
  55857. __extends(GenericPad, _super);
  55858. function GenericPad(id, index, browserGamepad) {
  55859. var _this = _super.call(this, id, index, browserGamepad) || this;
  55860. _this.onButtonDownObservable = new BABYLON.Observable();
  55861. _this.onButtonUpObservable = new BABYLON.Observable();
  55862. _this.type = Gamepad.GENERIC;
  55863. _this._buttons = new Array(browserGamepad.buttons.length);
  55864. return _this;
  55865. }
  55866. GenericPad.prototype.onbuttondown = function (callback) {
  55867. this._onbuttondown = callback;
  55868. };
  55869. GenericPad.prototype.onbuttonup = function (callback) {
  55870. this._onbuttonup = callback;
  55871. };
  55872. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55873. if (newValue !== currentValue) {
  55874. if (newValue === 1) {
  55875. if (this._onbuttondown) {
  55876. this._onbuttondown(buttonIndex);
  55877. }
  55878. this.onButtonDownObservable.notifyObservers(buttonIndex);
  55879. }
  55880. if (newValue === 0) {
  55881. if (this._onbuttonup) {
  55882. this._onbuttonup(buttonIndex);
  55883. }
  55884. this.onButtonUpObservable.notifyObservers(buttonIndex);
  55885. }
  55886. }
  55887. return newValue;
  55888. };
  55889. GenericPad.prototype.update = function () {
  55890. _super.prototype.update.call(this);
  55891. for (var index = 0; index < this._buttons.length; index++) {
  55892. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  55893. }
  55894. };
  55895. return GenericPad;
  55896. }(Gamepad));
  55897. BABYLON.GenericPad = GenericPad;
  55898. })(BABYLON || (BABYLON = {}));
  55899. //# sourceMappingURL=babylon.gamepad.js.map
  55900. var BABYLON;
  55901. (function (BABYLON) {
  55902. var Xbox360Button;
  55903. (function (Xbox360Button) {
  55904. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55905. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55906. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55907. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55908. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55909. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55910. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55911. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55912. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55913. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55914. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55915. var Xbox360Dpad;
  55916. (function (Xbox360Dpad) {
  55917. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55918. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55919. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55920. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55921. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55922. var Xbox360Pad = /** @class */ (function (_super) {
  55923. __extends(Xbox360Pad, _super);
  55924. function Xbox360Pad(id, index, gamepad, xboxOne) {
  55925. if (xboxOne === void 0) { xboxOne = false; }
  55926. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  55927. _this._leftTrigger = 0;
  55928. _this._rightTrigger = 0;
  55929. _this.onButtonDownObservable = new BABYLON.Observable();
  55930. _this.onButtonUpObservable = new BABYLON.Observable();
  55931. _this.onPadDownObservable = new BABYLON.Observable();
  55932. _this.onPadUpObservable = new BABYLON.Observable();
  55933. _this._buttonA = 0;
  55934. _this._buttonB = 0;
  55935. _this._buttonX = 0;
  55936. _this._buttonY = 0;
  55937. _this._buttonBack = 0;
  55938. _this._buttonStart = 0;
  55939. _this._buttonLB = 0;
  55940. _this._buttonRB = 0;
  55941. _this._buttonLeftStick = 0;
  55942. _this._buttonRightStick = 0;
  55943. _this._dPadUp = 0;
  55944. _this._dPadDown = 0;
  55945. _this._dPadLeft = 0;
  55946. _this._dPadRight = 0;
  55947. _this._isXboxOnePad = false;
  55948. _this.type = BABYLON.Gamepad.XBOX;
  55949. _this._isXboxOnePad = xboxOne;
  55950. return _this;
  55951. }
  55952. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55953. this._onlefttriggerchanged = callback;
  55954. };
  55955. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55956. this._onrighttriggerchanged = callback;
  55957. };
  55958. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55959. get: function () {
  55960. return this._leftTrigger;
  55961. },
  55962. set: function (newValue) {
  55963. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55964. this._onlefttriggerchanged(newValue);
  55965. }
  55966. this._leftTrigger = newValue;
  55967. },
  55968. enumerable: true,
  55969. configurable: true
  55970. });
  55971. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55972. get: function () {
  55973. return this._rightTrigger;
  55974. },
  55975. set: function (newValue) {
  55976. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55977. this._onrighttriggerchanged(newValue);
  55978. }
  55979. this._rightTrigger = newValue;
  55980. },
  55981. enumerable: true,
  55982. configurable: true
  55983. });
  55984. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55985. this._onbuttondown = callback;
  55986. };
  55987. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55988. this._onbuttonup = callback;
  55989. };
  55990. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55991. this._ondpaddown = callback;
  55992. };
  55993. Xbox360Pad.prototype.ondpadup = function (callback) {
  55994. this._ondpadup = callback;
  55995. };
  55996. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55997. if (newValue !== currentValue) {
  55998. if (newValue === 1) {
  55999. if (this._onbuttondown) {
  56000. this._onbuttondown(buttonType);
  56001. }
  56002. this.onButtonDownObservable.notifyObservers(buttonType);
  56003. }
  56004. if (newValue === 0) {
  56005. if (this._onbuttonup) {
  56006. this._onbuttonup(buttonType);
  56007. }
  56008. this.onButtonUpObservable.notifyObservers(buttonType);
  56009. }
  56010. }
  56011. return newValue;
  56012. };
  56013. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  56014. if (newValue !== currentValue) {
  56015. if (newValue === 1) {
  56016. if (this._ondpaddown) {
  56017. this._ondpaddown(buttonType);
  56018. }
  56019. this.onPadDownObservable.notifyObservers(buttonType);
  56020. }
  56021. if (newValue === 0) {
  56022. if (this._ondpadup) {
  56023. this._ondpadup(buttonType);
  56024. }
  56025. this.onPadUpObservable.notifyObservers(buttonType);
  56026. }
  56027. }
  56028. return newValue;
  56029. };
  56030. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  56031. get: function () {
  56032. return this._buttonA;
  56033. },
  56034. set: function (value) {
  56035. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  56036. },
  56037. enumerable: true,
  56038. configurable: true
  56039. });
  56040. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  56041. get: function () {
  56042. return this._buttonB;
  56043. },
  56044. set: function (value) {
  56045. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  56046. },
  56047. enumerable: true,
  56048. configurable: true
  56049. });
  56050. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  56051. get: function () {
  56052. return this._buttonX;
  56053. },
  56054. set: function (value) {
  56055. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  56056. },
  56057. enumerable: true,
  56058. configurable: true
  56059. });
  56060. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  56061. get: function () {
  56062. return this._buttonY;
  56063. },
  56064. set: function (value) {
  56065. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  56066. },
  56067. enumerable: true,
  56068. configurable: true
  56069. });
  56070. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  56071. get: function () {
  56072. return this._buttonStart;
  56073. },
  56074. set: function (value) {
  56075. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  56076. },
  56077. enumerable: true,
  56078. configurable: true
  56079. });
  56080. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  56081. get: function () {
  56082. return this._buttonBack;
  56083. },
  56084. set: function (value) {
  56085. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  56086. },
  56087. enumerable: true,
  56088. configurable: true
  56089. });
  56090. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  56091. get: function () {
  56092. return this._buttonLB;
  56093. },
  56094. set: function (value) {
  56095. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  56096. },
  56097. enumerable: true,
  56098. configurable: true
  56099. });
  56100. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  56101. get: function () {
  56102. return this._buttonRB;
  56103. },
  56104. set: function (value) {
  56105. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  56106. },
  56107. enumerable: true,
  56108. configurable: true
  56109. });
  56110. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  56111. get: function () {
  56112. return this._buttonLeftStick;
  56113. },
  56114. set: function (value) {
  56115. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  56116. },
  56117. enumerable: true,
  56118. configurable: true
  56119. });
  56120. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  56121. get: function () {
  56122. return this._buttonRightStick;
  56123. },
  56124. set: function (value) {
  56125. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  56126. },
  56127. enumerable: true,
  56128. configurable: true
  56129. });
  56130. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  56131. get: function () {
  56132. return this._dPadUp;
  56133. },
  56134. set: function (value) {
  56135. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  56136. },
  56137. enumerable: true,
  56138. configurable: true
  56139. });
  56140. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  56141. get: function () {
  56142. return this._dPadDown;
  56143. },
  56144. set: function (value) {
  56145. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  56146. },
  56147. enumerable: true,
  56148. configurable: true
  56149. });
  56150. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  56151. get: function () {
  56152. return this._dPadLeft;
  56153. },
  56154. set: function (value) {
  56155. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  56156. },
  56157. enumerable: true,
  56158. configurable: true
  56159. });
  56160. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  56161. get: function () {
  56162. return this._dPadRight;
  56163. },
  56164. set: function (value) {
  56165. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  56166. },
  56167. enumerable: true,
  56168. configurable: true
  56169. });
  56170. Xbox360Pad.prototype.update = function () {
  56171. _super.prototype.update.call(this);
  56172. if (this._isXboxOnePad) {
  56173. this.buttonA = this.browserGamepad.buttons[0].value;
  56174. this.buttonB = this.browserGamepad.buttons[1].value;
  56175. this.buttonX = this.browserGamepad.buttons[2].value;
  56176. this.buttonY = this.browserGamepad.buttons[3].value;
  56177. this.buttonLB = this.browserGamepad.buttons[4].value;
  56178. this.buttonRB = this.browserGamepad.buttons[5].value;
  56179. this.leftTrigger = this.browserGamepad.axes[2];
  56180. this.rightTrigger = this.browserGamepad.axes[5];
  56181. this.buttonBack = this.browserGamepad.buttons[9].value;
  56182. this.buttonStart = this.browserGamepad.buttons[8].value;
  56183. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  56184. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  56185. this.dPadUp = this.browserGamepad.buttons[11].value;
  56186. this.dPadDown = this.browserGamepad.buttons[12].value;
  56187. this.dPadLeft = this.browserGamepad.buttons[13].value;
  56188. this.dPadRight = this.browserGamepad.buttons[14].value;
  56189. }
  56190. else {
  56191. this.buttonA = this.browserGamepad.buttons[0].value;
  56192. this.buttonB = this.browserGamepad.buttons[1].value;
  56193. this.buttonX = this.browserGamepad.buttons[2].value;
  56194. this.buttonY = this.browserGamepad.buttons[3].value;
  56195. this.buttonLB = this.browserGamepad.buttons[4].value;
  56196. this.buttonRB = this.browserGamepad.buttons[5].value;
  56197. this.leftTrigger = this.browserGamepad.buttons[6].value;
  56198. this.rightTrigger = this.browserGamepad.buttons[7].value;
  56199. this.buttonBack = this.browserGamepad.buttons[8].value;
  56200. this.buttonStart = this.browserGamepad.buttons[9].value;
  56201. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  56202. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  56203. this.dPadUp = this.browserGamepad.buttons[12].value;
  56204. this.dPadDown = this.browserGamepad.buttons[13].value;
  56205. this.dPadLeft = this.browserGamepad.buttons[14].value;
  56206. this.dPadRight = this.browserGamepad.buttons[15].value;
  56207. }
  56208. };
  56209. return Xbox360Pad;
  56210. }(BABYLON.Gamepad));
  56211. BABYLON.Xbox360Pad = Xbox360Pad;
  56212. })(BABYLON || (BABYLON = {}));
  56213. //# sourceMappingURL=babylon.xboxGamepad.js.map
  56214. var BABYLON;
  56215. (function (BABYLON) {
  56216. var PoseEnabledControllerType;
  56217. (function (PoseEnabledControllerType) {
  56218. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  56219. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  56220. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  56221. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  56222. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  56223. var PoseEnabledControllerHelper = /** @class */ (function () {
  56224. function PoseEnabledControllerHelper() {
  56225. }
  56226. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  56227. // Oculus Touch
  56228. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  56229. return new BABYLON.OculusTouchController(vrGamepad);
  56230. }
  56231. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  56232. return new BABYLON.WindowsMotionController(vrGamepad);
  56233. }
  56234. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  56235. return new BABYLON.ViveController(vrGamepad);
  56236. }
  56237. else {
  56238. return new BABYLON.GenericController(vrGamepad);
  56239. }
  56240. };
  56241. return PoseEnabledControllerHelper;
  56242. }());
  56243. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  56244. var PoseEnabledController = /** @class */ (function (_super) {
  56245. __extends(PoseEnabledController, _super);
  56246. function PoseEnabledController(browserGamepad) {
  56247. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  56248. _this.deviceScaleFactor = 1;
  56249. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  56250. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  56251. _this.controllerType = PoseEnabledControllerType.GENERIC;
  56252. _this.position = BABYLON.Vector3.Zero();
  56253. _this.rotationQuaternion = new BABYLON.Quaternion();
  56254. _this.devicePosition = BABYLON.Vector3.Zero();
  56255. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  56256. _this._calculatedPosition = BABYLON.Vector3.Zero();
  56257. _this._calculatedRotation = new BABYLON.Quaternion();
  56258. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  56259. return _this;
  56260. }
  56261. PoseEnabledController.prototype.update = function () {
  56262. _super.prototype.update.call(this);
  56263. var pose = this.browserGamepad.pose;
  56264. this.updateFromDevice(pose);
  56265. if (this._mesh) {
  56266. this._mesh.position.copyFrom(this._calculatedPosition);
  56267. if (this._mesh.rotationQuaternion) {
  56268. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  56269. }
  56270. }
  56271. };
  56272. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  56273. if (poseData) {
  56274. this.rawPose = poseData;
  56275. if (poseData.position) {
  56276. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  56277. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  56278. this.devicePosition.z *= -1;
  56279. }
  56280. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  56281. this._calculatedPosition.addInPlace(this.position);
  56282. }
  56283. var pose = this.rawPose;
  56284. if (poseData.orientation && pose.orientation) {
  56285. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  56286. if (this._mesh) {
  56287. if (this._mesh.getScene().useRightHandedSystem) {
  56288. this.deviceRotationQuaternion.z *= -1;
  56289. this.deviceRotationQuaternion.w *= -1;
  56290. }
  56291. else {
  56292. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  56293. }
  56294. }
  56295. // if the camera is set, rotate to the camera's rotation
  56296. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  56297. }
  56298. }
  56299. };
  56300. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  56301. if (this._mesh) {
  56302. this._mesh.parent = null;
  56303. }
  56304. this._mesh = mesh;
  56305. if (this._poseControlledCamera) {
  56306. this._mesh.parent = this._poseControlledCamera;
  56307. }
  56308. if (!this._mesh.rotationQuaternion) {
  56309. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  56310. }
  56311. };
  56312. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  56313. this._poseControlledCamera = camera;
  56314. if (this._mesh) {
  56315. this._mesh.parent = this._poseControlledCamera;
  56316. }
  56317. };
  56318. PoseEnabledController.prototype.dispose = function () {
  56319. if (this._mesh) {
  56320. this._mesh.dispose();
  56321. }
  56322. this._mesh = null;
  56323. _super.prototype.dispose.call(this);
  56324. };
  56325. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  56326. get: function () {
  56327. return this._mesh;
  56328. },
  56329. enumerable: true,
  56330. configurable: true
  56331. });
  56332. PoseEnabledController.prototype.getForwardRay = function (length) {
  56333. if (length === void 0) { length = 100; }
  56334. if (!this.mesh) {
  56335. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  56336. }
  56337. var m = this.mesh.getWorldMatrix();
  56338. var origin = m.getTranslation();
  56339. var forward = new BABYLON.Vector3(0, 0, -1);
  56340. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56341. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56342. return new BABYLON.Ray(origin, direction, length);
  56343. };
  56344. return PoseEnabledController;
  56345. }(BABYLON.Gamepad));
  56346. BABYLON.PoseEnabledController = PoseEnabledController;
  56347. })(BABYLON || (BABYLON = {}));
  56348. //# sourceMappingURL=babylon.poseEnabledController.js.map
  56349. var BABYLON;
  56350. (function (BABYLON) {
  56351. var WebVRController = /** @class */ (function (_super) {
  56352. __extends(WebVRController, _super);
  56353. function WebVRController(vrGamepad) {
  56354. var _this = _super.call(this, vrGamepad) || this;
  56355. // Observables
  56356. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  56357. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  56358. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  56359. _this.onPadStateChangedObservable = new BABYLON.Observable();
  56360. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  56361. _this.pad = { x: 0, y: 0 };
  56362. // avoid GC, store state in a tmp object
  56363. _this._changes = {
  56364. pressChanged: false,
  56365. touchChanged: false,
  56366. valueChanged: false,
  56367. changed: false
  56368. };
  56369. _this._buttons = new Array(vrGamepad.buttons.length);
  56370. _this.hand = vrGamepad.hand;
  56371. return _this;
  56372. }
  56373. WebVRController.prototype.onButtonStateChange = function (callback) {
  56374. this._onButtonStateChange = callback;
  56375. };
  56376. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  56377. get: function () {
  56378. return this._defaultModel;
  56379. },
  56380. enumerable: true,
  56381. configurable: true
  56382. });
  56383. WebVRController.prototype.update = function () {
  56384. _super.prototype.update.call(this);
  56385. for (var index = 0; index < this._buttons.length; index++) {
  56386. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  56387. }
  56388. ;
  56389. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  56390. this.pad.x = this.leftStick.x;
  56391. this.pad.y = this.leftStick.y;
  56392. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  56393. }
  56394. };
  56395. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  56396. if (!newState) {
  56397. newState = {
  56398. pressed: false,
  56399. touched: false,
  56400. value: 0
  56401. };
  56402. }
  56403. if (!currentState) {
  56404. this._buttons[buttonIndex] = {
  56405. pressed: newState.pressed,
  56406. touched: newState.touched,
  56407. value: newState.value
  56408. };
  56409. return;
  56410. }
  56411. this._checkChanges(newState, currentState);
  56412. if (this._changes.changed) {
  56413. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  56414. this.handleButtonChange(buttonIndex, newState, this._changes);
  56415. }
  56416. this._buttons[buttonIndex].pressed = newState.pressed;
  56417. this._buttons[buttonIndex].touched = newState.touched;
  56418. // oculus triggers are never 0, thou not touched.
  56419. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  56420. };
  56421. WebVRController.prototype._checkChanges = function (newState, currentState) {
  56422. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  56423. this._changes.touchChanged = newState.touched !== currentState.touched;
  56424. this._changes.valueChanged = newState.value !== currentState.value;
  56425. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  56426. return this._changes;
  56427. };
  56428. WebVRController.prototype.dispose = function () {
  56429. _super.prototype.dispose.call(this);
  56430. this.onTriggerStateChangedObservable.clear();
  56431. this.onMainButtonStateChangedObservable.clear();
  56432. this.onSecondaryButtonStateChangedObservable.clear();
  56433. this.onPadStateChangedObservable.clear();
  56434. this.onPadValuesChangedObservable.clear();
  56435. };
  56436. return WebVRController;
  56437. }(BABYLON.PoseEnabledController));
  56438. BABYLON.WebVRController = WebVRController;
  56439. })(BABYLON || (BABYLON = {}));
  56440. //# sourceMappingURL=babylon.webVRController.js.map
  56441. var BABYLON;
  56442. (function (BABYLON) {
  56443. var OculusTouchController = /** @class */ (function (_super) {
  56444. __extends(OculusTouchController, _super);
  56445. function OculusTouchController(vrGamepad) {
  56446. var _this = _super.call(this, vrGamepad) || this;
  56447. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  56448. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  56449. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  56450. return _this;
  56451. }
  56452. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56453. var _this = this;
  56454. var meshName;
  56455. // Hand
  56456. if (this.hand === 'left') {
  56457. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  56458. }
  56459. else {
  56460. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  56461. }
  56462. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  56463. /*
  56464. Parent Mesh name: oculus_touch_left
  56465. - body
  56466. - trigger
  56467. - thumbstick
  56468. - grip
  56469. - button_y
  56470. - button_x
  56471. - button_enter
  56472. */
  56473. _this._defaultModel = newMeshes[1];
  56474. _this.attachToMesh(_this._defaultModel);
  56475. if (meshLoaded) {
  56476. meshLoaded(_this._defaultModel);
  56477. }
  56478. });
  56479. };
  56480. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  56481. // helper getters for left and right hand.
  56482. get: function () {
  56483. if (this.hand === 'right') {
  56484. return this.onMainButtonStateChangedObservable;
  56485. }
  56486. else {
  56487. throw new Error('No A button on left hand');
  56488. }
  56489. },
  56490. enumerable: true,
  56491. configurable: true
  56492. });
  56493. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  56494. get: function () {
  56495. if (this.hand === 'right') {
  56496. return this.onSecondaryButtonStateChangedObservable;
  56497. }
  56498. else {
  56499. throw new Error('No B button on left hand');
  56500. }
  56501. },
  56502. enumerable: true,
  56503. configurable: true
  56504. });
  56505. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  56506. get: function () {
  56507. if (this.hand === 'left') {
  56508. return this.onMainButtonStateChangedObservable;
  56509. }
  56510. else {
  56511. throw new Error('No X button on right hand');
  56512. }
  56513. },
  56514. enumerable: true,
  56515. configurable: true
  56516. });
  56517. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  56518. get: function () {
  56519. if (this.hand === 'left') {
  56520. return this.onSecondaryButtonStateChangedObservable;
  56521. }
  56522. else {
  56523. throw new Error('No Y button on right hand');
  56524. }
  56525. },
  56526. enumerable: true,
  56527. configurable: true
  56528. });
  56529. /*
  56530. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  56531. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  56532. 2) secondary trigger (same)
  56533. 3) A (right) X (left), touch, pressed = value
  56534. 4) B / Y
  56535. 5) thumb rest
  56536. */
  56537. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56538. var notifyObject = state; //{ state: state, changes: changes };
  56539. var triggerDirection = this.hand === 'right' ? -1 : 1;
  56540. switch (buttonIdx) {
  56541. case 0:
  56542. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56543. return;
  56544. case 1:// index trigger
  56545. if (this._defaultModel) {
  56546. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  56547. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  56548. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  56549. }
  56550. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56551. return;
  56552. case 2:// secondary trigger
  56553. if (this._defaultModel) {
  56554. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  56555. }
  56556. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  56557. return;
  56558. case 3:
  56559. if (this._defaultModel) {
  56560. if (notifyObject.pressed) {
  56561. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  56562. }
  56563. else {
  56564. (this._defaultModel.getChildren()[1]).position.y = 0;
  56565. }
  56566. }
  56567. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56568. return;
  56569. case 4:
  56570. if (this._defaultModel) {
  56571. if (notifyObject.pressed) {
  56572. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56573. }
  56574. else {
  56575. (this._defaultModel.getChildren()[2]).position.y = 0;
  56576. }
  56577. }
  56578. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56579. return;
  56580. case 5:
  56581. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  56582. return;
  56583. }
  56584. };
  56585. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  56586. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  56587. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  56588. return OculusTouchController;
  56589. }(BABYLON.WebVRController));
  56590. BABYLON.OculusTouchController = OculusTouchController;
  56591. })(BABYLON || (BABYLON = {}));
  56592. //# sourceMappingURL=babylon.oculusTouchController.js.map
  56593. var BABYLON;
  56594. (function (BABYLON) {
  56595. var ViveController = /** @class */ (function (_super) {
  56596. __extends(ViveController, _super);
  56597. function ViveController(vrGamepad) {
  56598. var _this = _super.call(this, vrGamepad) || this;
  56599. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  56600. return _this;
  56601. }
  56602. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56603. var _this = this;
  56604. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  56605. /*
  56606. Parent Mesh name: ViveWand
  56607. - body
  56608. - r_gripper
  56609. - l_gripper
  56610. - menu_button
  56611. - system_button
  56612. - trackpad
  56613. - trigger
  56614. - LED
  56615. */
  56616. _this._defaultModel = newMeshes[1];
  56617. _this.attachToMesh(_this._defaultModel);
  56618. if (meshLoaded) {
  56619. meshLoaded(_this._defaultModel);
  56620. }
  56621. });
  56622. };
  56623. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  56624. get: function () {
  56625. return this.onMainButtonStateChangedObservable;
  56626. },
  56627. enumerable: true,
  56628. configurable: true
  56629. });
  56630. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  56631. get: function () {
  56632. return this.onMainButtonStateChangedObservable;
  56633. },
  56634. enumerable: true,
  56635. configurable: true
  56636. });
  56637. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  56638. get: function () {
  56639. return this.onSecondaryButtonStateChangedObservable;
  56640. },
  56641. enumerable: true,
  56642. configurable: true
  56643. });
  56644. /**
  56645. * Vive mapping:
  56646. * 0: touchpad
  56647. * 1: trigger
  56648. * 2: left AND right buttons
  56649. * 3: menu button
  56650. */
  56651. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56652. var notifyObject = state; //{ state: state, changes: changes };
  56653. switch (buttonIdx) {
  56654. case 0:
  56655. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56656. return;
  56657. case 1:// index trigger
  56658. if (this._defaultModel) {
  56659. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  56660. }
  56661. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56662. return;
  56663. case 2:// left AND right button
  56664. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56665. return;
  56666. case 3:
  56667. if (this._defaultModel) {
  56668. if (notifyObject.pressed) {
  56669. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56670. }
  56671. else {
  56672. (this._defaultModel.getChildren()[2]).position.y = 0;
  56673. }
  56674. }
  56675. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56676. return;
  56677. }
  56678. };
  56679. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  56680. ViveController.MODEL_FILENAME = 'wand.babylon';
  56681. return ViveController;
  56682. }(BABYLON.WebVRController));
  56683. BABYLON.ViveController = ViveController;
  56684. })(BABYLON || (BABYLON = {}));
  56685. //# sourceMappingURL=babylon.viveController.js.map
  56686. var BABYLON;
  56687. (function (BABYLON) {
  56688. var GenericController = /** @class */ (function (_super) {
  56689. __extends(GenericController, _super);
  56690. function GenericController(vrGamepad) {
  56691. return _super.call(this, vrGamepad) || this;
  56692. }
  56693. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56694. var _this = this;
  56695. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  56696. _this._defaultModel = newMeshes[1];
  56697. _this.attachToMesh(_this._defaultModel);
  56698. if (meshLoaded) {
  56699. meshLoaded(_this._defaultModel);
  56700. }
  56701. });
  56702. };
  56703. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56704. console.log("Button id: " + buttonIdx + "state: ");
  56705. console.dir(state);
  56706. };
  56707. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  56708. GenericController.MODEL_FILENAME = 'generic.babylon';
  56709. return GenericController;
  56710. }(BABYLON.WebVRController));
  56711. BABYLON.GenericController = GenericController;
  56712. })(BABYLON || (BABYLON = {}));
  56713. //# sourceMappingURL=babylon.genericController.js.map
  56714. var BABYLON;
  56715. (function (BABYLON) {
  56716. var LoadedMeshInfo = /** @class */ (function () {
  56717. function LoadedMeshInfo() {
  56718. this.buttonMeshes = {};
  56719. this.axisMeshes = {};
  56720. }
  56721. return LoadedMeshInfo;
  56722. }());
  56723. var WindowsMotionController = /** @class */ (function (_super) {
  56724. __extends(WindowsMotionController, _super);
  56725. function WindowsMotionController(vrGamepad) {
  56726. var _this = _super.call(this, vrGamepad) || this;
  56727. _this._mapping = {
  56728. // Semantic button names
  56729. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  56730. // A mapping of the button name to glTF model node name
  56731. // that should be transformed by button value.
  56732. buttonMeshNames: {
  56733. 'trigger': 'SELECT',
  56734. 'menu': 'MENU',
  56735. 'grip': 'GRASP',
  56736. 'thumbstick': 'THUMBSTICK_PRESS',
  56737. 'trackpad': 'TOUCHPAD_PRESS'
  56738. },
  56739. // This mapping is used to translate from the Motion Controller to Babylon semantics
  56740. buttonObservableNames: {
  56741. 'trigger': 'onTriggerStateChangedObservable',
  56742. 'menu': 'onSecondaryButtonStateChangedObservable',
  56743. 'grip': 'onMainButtonStateChangedObservable',
  56744. 'thumbstick': 'onPadStateChangedObservable',
  56745. 'trackpad': 'onTrackpadChangedObservable'
  56746. },
  56747. // A mapping of the axis name to glTF model node name
  56748. // that should be transformed by axis value.
  56749. // This array mirrors the browserGamepad.axes array, such that
  56750. // the mesh corresponding to axis 0 is in this array index 0.
  56751. axisMeshNames: [
  56752. 'THUMBSTICK_X',
  56753. 'THUMBSTICK_Y',
  56754. 'TOUCHPAD_TOUCH_X',
  56755. 'TOUCHPAD_TOUCH_Y'
  56756. ],
  56757. pointingPoseMeshName: 'POINTING_POSE'
  56758. };
  56759. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  56760. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  56761. _this._loadedMeshInfo = null;
  56762. return _this;
  56763. }
  56764. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  56765. get: function () {
  56766. return this.onTriggerStateChangedObservable;
  56767. },
  56768. enumerable: true,
  56769. configurable: true
  56770. });
  56771. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  56772. get: function () {
  56773. return this.onSecondaryButtonStateChangedObservable;
  56774. },
  56775. enumerable: true,
  56776. configurable: true
  56777. });
  56778. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  56779. get: function () {
  56780. return this.onMainButtonStateChangedObservable;
  56781. },
  56782. enumerable: true,
  56783. configurable: true
  56784. });
  56785. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  56786. get: function () {
  56787. return this.onPadStateChangedObservable;
  56788. },
  56789. enumerable: true,
  56790. configurable: true
  56791. });
  56792. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  56793. get: function () {
  56794. return this.onTrackpadChangedObservable;
  56795. },
  56796. enumerable: true,
  56797. configurable: true
  56798. });
  56799. /**
  56800. * Called once per frame by the engine.
  56801. */
  56802. WindowsMotionController.prototype.update = function () {
  56803. _super.prototype.update.call(this);
  56804. // Only need to animate axes if there is a loaded mesh
  56805. if (this._loadedMeshInfo) {
  56806. if (this.browserGamepad.axes) {
  56807. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  56808. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  56809. }
  56810. }
  56811. }
  56812. };
  56813. /**
  56814. * Called once for each button that changed state since the last frame
  56815. * @param buttonIdx Which button index changed
  56816. * @param state New state of the button
  56817. * @param changes Which properties on the state changed since last frame
  56818. */
  56819. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56820. var buttonName = this._mapping.buttons[buttonIdx];
  56821. if (!buttonName) {
  56822. return;
  56823. }
  56824. // Only emit events for buttons that we know how to map from index to name
  56825. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  56826. if (observable) {
  56827. observable.notifyObservers(state);
  56828. }
  56829. this.lerpButtonTransform(buttonName, state.value);
  56830. };
  56831. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  56832. // If there is no loaded mesh, there is nothing to transform.
  56833. if (!this._loadedMeshInfo) {
  56834. return;
  56835. }
  56836. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  56837. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56838. return;
  56839. }
  56840. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  56841. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  56842. };
  56843. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  56844. if (!this._loadedMeshInfo) {
  56845. return;
  56846. }
  56847. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  56848. if (!meshInfo) {
  56849. return;
  56850. }
  56851. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56852. return;
  56853. }
  56854. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  56855. var lerpValue = axisValue * 0.5 + 0.5;
  56856. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  56857. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  56858. };
  56859. /**
  56860. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  56861. * @param scene scene in which to add meshes
  56862. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  56863. */
  56864. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  56865. var _this = this;
  56866. if (forceDefault === void 0) { forceDefault = false; }
  56867. var path;
  56868. var filename;
  56869. // Checking if GLB loader is present
  56870. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  56871. // Determine the device specific folder based on the ID suffix
  56872. var device = 'default';
  56873. if (this.id && !forceDefault) {
  56874. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  56875. device = ((match && match[0]) || device);
  56876. }
  56877. // Hand
  56878. if (this.hand === 'left') {
  56879. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  56880. }
  56881. else {
  56882. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  56883. }
  56884. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  56885. }
  56886. else {
  56887. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  56888. path = BABYLON.GenericController.MODEL_BASE_URL;
  56889. filename = BABYLON.GenericController.MODEL_FILENAME;
  56890. }
  56891. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  56892. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  56893. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  56894. if (!_this._loadedMeshInfo) {
  56895. return;
  56896. }
  56897. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  56898. _this.attachToMesh(_this._defaultModel);
  56899. if (meshLoaded) {
  56900. meshLoaded(_this._defaultModel);
  56901. }
  56902. }, null, function (scene, message) {
  56903. BABYLON.Tools.Log(message);
  56904. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  56905. if (!forceDefault) {
  56906. _this.initControllerMesh(scene, meshLoaded, true);
  56907. }
  56908. });
  56909. };
  56910. /**
  56911. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  56912. * can be transformed by button presses and axes values, based on this._mapping.
  56913. *
  56914. * @param scene scene in which the meshes exist
  56915. * @param meshes list of meshes that make up the controller model to process
  56916. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  56917. */
  56918. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  56919. var loadedMeshInfo = null;
  56920. // Create a new mesh to contain the glTF hierarchy
  56921. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  56922. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  56923. var childMesh = null;
  56924. for (var i = 0; i < meshes.length; i++) {
  56925. var mesh = meshes[i];
  56926. if (!mesh.parent) {
  56927. // Exclude controller meshes from picking results
  56928. mesh.isPickable = false;
  56929. // Handle root node, attach to the new parentMesh
  56930. childMesh = mesh;
  56931. break;
  56932. }
  56933. }
  56934. if (childMesh) {
  56935. childMesh.setParent(parentMesh);
  56936. // Create our mesh info. Note that this method will always return non-null.
  56937. loadedMeshInfo = this.createMeshInfo(parentMesh);
  56938. }
  56939. else {
  56940. BABYLON.Tools.Warn('Could not find root node in model file.');
  56941. }
  56942. return loadedMeshInfo;
  56943. };
  56944. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  56945. var loadedMeshInfo = new LoadedMeshInfo();
  56946. var i;
  56947. loadedMeshInfo.rootNode = rootNode;
  56948. // Reset the caches
  56949. loadedMeshInfo.buttonMeshes = {};
  56950. loadedMeshInfo.axisMeshes = {};
  56951. // Button Meshes
  56952. for (i = 0; i < this._mapping.buttons.length; i++) {
  56953. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  56954. if (!buttonMeshName) {
  56955. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  56956. continue;
  56957. }
  56958. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  56959. if (!buttonMesh) {
  56960. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  56961. continue;
  56962. }
  56963. var buttonMeshInfo = {
  56964. index: i,
  56965. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  56966. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  56967. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  56968. };
  56969. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  56970. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  56971. }
  56972. else {
  56973. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  56974. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  56975. '(VALUE: ' + !!buttonMeshInfo.value +
  56976. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  56977. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  56978. ')');
  56979. }
  56980. }
  56981. // Axis Meshes
  56982. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  56983. var axisMeshName = this._mapping.axisMeshNames[i];
  56984. if (!axisMeshName) {
  56985. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  56986. continue;
  56987. }
  56988. var axisMesh = getChildByName(rootNode, axisMeshName);
  56989. if (!axisMesh) {
  56990. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  56991. continue;
  56992. }
  56993. var axisMeshInfo = {
  56994. index: i,
  56995. value: getImmediateChildByName(axisMesh, 'VALUE'),
  56996. min: getImmediateChildByName(axisMesh, 'MIN'),
  56997. max: getImmediateChildByName(axisMesh, 'MAX')
  56998. };
  56999. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  57000. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  57001. }
  57002. else {
  57003. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  57004. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  57005. '(VALUE: ' + !!axisMeshInfo.value +
  57006. ', MIN: ' + !!axisMeshInfo.min +
  57007. ', MAX:' + !!axisMeshInfo.max +
  57008. ')');
  57009. }
  57010. }
  57011. // Pointing Ray
  57012. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  57013. if (!loadedMeshInfo.pointingPoseNode) {
  57014. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  57015. }
  57016. return loadedMeshInfo;
  57017. // Look through all children recursively. This will return null if no mesh exists with the given name.
  57018. function getChildByName(node, name) {
  57019. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  57020. }
  57021. // Look through only immediate children. This will return null if no mesh exists with the given name.
  57022. function getImmediateChildByName(node, name) {
  57023. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  57024. }
  57025. };
  57026. WindowsMotionController.prototype.getForwardRay = function (length) {
  57027. if (length === void 0) { length = 100; }
  57028. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  57029. return _super.prototype.getForwardRay.call(this, length);
  57030. }
  57031. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  57032. var origin = m.getTranslation();
  57033. var forward = new BABYLON.Vector3(0, 0, -1);
  57034. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57035. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57036. return new BABYLON.Ray(origin, direction, length);
  57037. };
  57038. WindowsMotionController.prototype.dispose = function () {
  57039. _super.prototype.dispose.call(this);
  57040. this.onTrackpadChangedObservable.clear();
  57041. };
  57042. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  57043. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  57044. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  57045. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  57046. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  57047. return WindowsMotionController;
  57048. }(BABYLON.WebVRController));
  57049. BABYLON.WindowsMotionController = WindowsMotionController;
  57050. })(BABYLON || (BABYLON = {}));
  57051. //# sourceMappingURL=babylon.windowsMotionController.js.map
  57052. var BABYLON;
  57053. (function (BABYLON) {
  57054. var FollowCamera = /** @class */ (function (_super) {
  57055. __extends(FollowCamera, _super);
  57056. function FollowCamera(name, position, scene, lockedTarget) {
  57057. if (lockedTarget === void 0) { lockedTarget = null; }
  57058. var _this = _super.call(this, name, position, scene) || this;
  57059. _this.radius = 12;
  57060. _this.rotationOffset = 0;
  57061. _this.heightOffset = 4;
  57062. _this.cameraAcceleration = 0.05;
  57063. _this.maxCameraSpeed = 20;
  57064. _this.lockedTarget = lockedTarget;
  57065. return _this;
  57066. }
  57067. FollowCamera.prototype.getRadians = function (degrees) {
  57068. return degrees * Math.PI / 180;
  57069. };
  57070. FollowCamera.prototype.follow = function (cameraTarget) {
  57071. if (!cameraTarget)
  57072. return;
  57073. var yRotation;
  57074. if (cameraTarget.rotationQuaternion) {
  57075. var rotMatrix = new BABYLON.Matrix();
  57076. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  57077. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  57078. }
  57079. else {
  57080. yRotation = cameraTarget.rotation.y;
  57081. }
  57082. var radians = this.getRadians(this.rotationOffset) + yRotation;
  57083. var targetPosition = cameraTarget.getAbsolutePosition();
  57084. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  57085. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  57086. var dx = targetX - this.position.x;
  57087. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  57088. var dz = (targetZ) - this.position.z;
  57089. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  57090. var vy = dy * this.cameraAcceleration;
  57091. var vz = dz * this.cameraAcceleration * 2;
  57092. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  57093. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57094. }
  57095. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  57096. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57097. }
  57098. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  57099. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  57100. }
  57101. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  57102. this.setTarget(targetPosition);
  57103. };
  57104. FollowCamera.prototype._checkInputs = function () {
  57105. _super.prototype._checkInputs.call(this);
  57106. if (this.lockedTarget) {
  57107. this.follow(this.lockedTarget);
  57108. }
  57109. };
  57110. FollowCamera.prototype.getClassName = function () {
  57111. return "FollowCamera";
  57112. };
  57113. __decorate([
  57114. BABYLON.serialize()
  57115. ], FollowCamera.prototype, "radius", void 0);
  57116. __decorate([
  57117. BABYLON.serialize()
  57118. ], FollowCamera.prototype, "rotationOffset", void 0);
  57119. __decorate([
  57120. BABYLON.serialize()
  57121. ], FollowCamera.prototype, "heightOffset", void 0);
  57122. __decorate([
  57123. BABYLON.serialize()
  57124. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  57125. __decorate([
  57126. BABYLON.serialize()
  57127. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  57128. __decorate([
  57129. BABYLON.serializeAsMeshReference("lockedTargetId")
  57130. ], FollowCamera.prototype, "lockedTarget", void 0);
  57131. return FollowCamera;
  57132. }(BABYLON.TargetCamera));
  57133. BABYLON.FollowCamera = FollowCamera;
  57134. var ArcFollowCamera = /** @class */ (function (_super) {
  57135. __extends(ArcFollowCamera, _super);
  57136. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  57137. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  57138. _this.alpha = alpha;
  57139. _this.beta = beta;
  57140. _this.radius = radius;
  57141. _this.target = target;
  57142. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  57143. _this.follow();
  57144. return _this;
  57145. }
  57146. ArcFollowCamera.prototype.follow = function () {
  57147. if (!this.target) {
  57148. return;
  57149. }
  57150. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  57151. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  57152. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  57153. var targetPosition = this.target.getAbsolutePosition();
  57154. this.position = targetPosition.add(this._cartesianCoordinates);
  57155. this.setTarget(targetPosition);
  57156. };
  57157. ArcFollowCamera.prototype._checkInputs = function () {
  57158. _super.prototype._checkInputs.call(this);
  57159. this.follow();
  57160. };
  57161. ArcFollowCamera.prototype.getClassName = function () {
  57162. return "ArcFollowCamera";
  57163. };
  57164. return ArcFollowCamera;
  57165. }(BABYLON.TargetCamera));
  57166. BABYLON.ArcFollowCamera = ArcFollowCamera;
  57167. })(BABYLON || (BABYLON = {}));
  57168. //# sourceMappingURL=babylon.followCamera.js.map
  57169. var BABYLON;
  57170. (function (BABYLON) {
  57171. // We're mainly based on the logic defined into the FreeCamera code
  57172. var UniversalCamera = /** @class */ (function (_super) {
  57173. __extends(UniversalCamera, _super);
  57174. //-- end properties for backward compatibility for inputs
  57175. function UniversalCamera(name, position, scene) {
  57176. var _this = _super.call(this, name, position, scene) || this;
  57177. _this.inputs.addGamepad();
  57178. return _this;
  57179. }
  57180. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  57181. //-- Begin properties for backward compatibility for inputs
  57182. get: function () {
  57183. var gamepad = this.inputs.attached["gamepad"];
  57184. if (gamepad)
  57185. return gamepad.gamepadAngularSensibility;
  57186. return 0;
  57187. },
  57188. set: function (value) {
  57189. var gamepad = this.inputs.attached["gamepad"];
  57190. if (gamepad)
  57191. gamepad.gamepadAngularSensibility = value;
  57192. },
  57193. enumerable: true,
  57194. configurable: true
  57195. });
  57196. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  57197. get: function () {
  57198. var gamepad = this.inputs.attached["gamepad"];
  57199. if (gamepad)
  57200. return gamepad.gamepadMoveSensibility;
  57201. return 0;
  57202. },
  57203. set: function (value) {
  57204. var gamepad = this.inputs.attached["gamepad"];
  57205. if (gamepad)
  57206. gamepad.gamepadMoveSensibility = value;
  57207. },
  57208. enumerable: true,
  57209. configurable: true
  57210. });
  57211. UniversalCamera.prototype.getClassName = function () {
  57212. return "UniversalCamera";
  57213. };
  57214. return UniversalCamera;
  57215. }(BABYLON.TouchCamera));
  57216. BABYLON.UniversalCamera = UniversalCamera;
  57217. })(BABYLON || (BABYLON = {}));
  57218. //# sourceMappingURL=babylon.universalCamera.js.map
  57219. var BABYLON;
  57220. (function (BABYLON) {
  57221. // We're mainly based on the logic defined into the FreeCamera code
  57222. var GamepadCamera = /** @class */ (function (_super) {
  57223. __extends(GamepadCamera, _super);
  57224. //-- end properties for backward compatibility for inputs
  57225. function GamepadCamera(name, position, scene) {
  57226. return _super.call(this, name, position, scene) || this;
  57227. }
  57228. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  57229. //-- Begin properties for backward compatibility for inputs
  57230. get: function () {
  57231. var gamepad = this.inputs.attached["gamepad"];
  57232. if (gamepad)
  57233. return gamepad.gamepadAngularSensibility;
  57234. return 0;
  57235. },
  57236. set: function (value) {
  57237. var gamepad = this.inputs.attached["gamepad"];
  57238. if (gamepad)
  57239. gamepad.gamepadAngularSensibility = value;
  57240. },
  57241. enumerable: true,
  57242. configurable: true
  57243. });
  57244. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  57245. get: function () {
  57246. var gamepad = this.inputs.attached["gamepad"];
  57247. if (gamepad)
  57248. return gamepad.gamepadMoveSensibility;
  57249. return 0;
  57250. },
  57251. set: function (value) {
  57252. var gamepad = this.inputs.attached["gamepad"];
  57253. if (gamepad)
  57254. gamepad.gamepadMoveSensibility = value;
  57255. },
  57256. enumerable: true,
  57257. configurable: true
  57258. });
  57259. GamepadCamera.prototype.getClassName = function () {
  57260. return "GamepadCamera";
  57261. };
  57262. return GamepadCamera;
  57263. }(BABYLON.UniversalCamera));
  57264. BABYLON.GamepadCamera = GamepadCamera;
  57265. })(BABYLON || (BABYLON = {}));
  57266. //# sourceMappingURL=babylon.gamepadCamera.js.map
  57267. var BABYLON;
  57268. (function (BABYLON) {
  57269. var PostProcessRenderPipelineManager = /** @class */ (function () {
  57270. function PostProcessRenderPipelineManager() {
  57271. this._renderPipelines = {};
  57272. }
  57273. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  57274. this._renderPipelines[renderPipeline._name] = renderPipeline;
  57275. };
  57276. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  57277. if (unique === void 0) { unique = false; }
  57278. var renderPipeline = this._renderPipelines[renderPipelineName];
  57279. if (!renderPipeline) {
  57280. return;
  57281. }
  57282. renderPipeline._attachCameras(cameras, unique);
  57283. };
  57284. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  57285. var renderPipeline = this._renderPipelines[renderPipelineName];
  57286. if (!renderPipeline) {
  57287. return;
  57288. }
  57289. renderPipeline._detachCameras(cameras);
  57290. };
  57291. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  57292. var renderPipeline = this._renderPipelines[renderPipelineName];
  57293. if (!renderPipeline) {
  57294. return;
  57295. }
  57296. renderPipeline._enableEffect(renderEffectName, cameras);
  57297. };
  57298. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  57299. var renderPipeline = this._renderPipelines[renderPipelineName];
  57300. if (!renderPipeline) {
  57301. return;
  57302. }
  57303. renderPipeline._disableEffect(renderEffectName, cameras);
  57304. };
  57305. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  57306. var renderPipeline = this._renderPipelines[renderPipelineName];
  57307. if (!renderPipeline) {
  57308. return;
  57309. }
  57310. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  57311. };
  57312. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  57313. var renderPipeline = this._renderPipelines[renderPipelineName];
  57314. if (!renderPipeline) {
  57315. return;
  57316. }
  57317. renderPipeline._disableDisplayOnlyPass(cameras);
  57318. };
  57319. PostProcessRenderPipelineManager.prototype.update = function () {
  57320. for (var renderPipelineName in this._renderPipelines) {
  57321. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57322. var pipeline = this._renderPipelines[renderPipelineName];
  57323. if (!pipeline.isSupported) {
  57324. pipeline.dispose();
  57325. delete this._renderPipelines[renderPipelineName];
  57326. }
  57327. else {
  57328. pipeline._update();
  57329. }
  57330. }
  57331. }
  57332. };
  57333. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  57334. for (var renderPipelineName in this._renderPipelines) {
  57335. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57336. var pipeline = this._renderPipelines[renderPipelineName];
  57337. pipeline._rebuild();
  57338. }
  57339. }
  57340. };
  57341. PostProcessRenderPipelineManager.prototype.dispose = function () {
  57342. for (var renderPipelineName in this._renderPipelines) {
  57343. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  57344. var pipeline = this._renderPipelines[renderPipelineName];
  57345. pipeline.dispose();
  57346. }
  57347. }
  57348. };
  57349. return PostProcessRenderPipelineManager;
  57350. }());
  57351. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  57352. })(BABYLON || (BABYLON = {}));
  57353. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  57354. var BABYLON;
  57355. (function (BABYLON) {
  57356. var PostProcessRenderPass = /** @class */ (function () {
  57357. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  57358. this._refCount = 0;
  57359. this._name = name;
  57360. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  57361. this.setRenderList(renderList);
  57362. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  57363. this._renderTexture.onAfterRenderObservable.add(afterRender);
  57364. this._scene = scene;
  57365. this._renderList = renderList;
  57366. }
  57367. // private
  57368. PostProcessRenderPass.prototype._incRefCount = function () {
  57369. if (this._refCount === 0) {
  57370. this._scene.customRenderTargets.push(this._renderTexture);
  57371. }
  57372. return ++this._refCount;
  57373. };
  57374. PostProcessRenderPass.prototype._decRefCount = function () {
  57375. this._refCount--;
  57376. if (this._refCount <= 0) {
  57377. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  57378. }
  57379. return this._refCount;
  57380. };
  57381. PostProcessRenderPass.prototype._update = function () {
  57382. this.setRenderList(this._renderList);
  57383. };
  57384. // public
  57385. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  57386. this._renderTexture.renderList = renderList;
  57387. };
  57388. PostProcessRenderPass.prototype.getRenderTexture = function () {
  57389. return this._renderTexture;
  57390. };
  57391. return PostProcessRenderPass;
  57392. }());
  57393. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  57394. })(BABYLON || (BABYLON = {}));
  57395. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  57396. var BABYLON;
  57397. (function (BABYLON) {
  57398. var PostProcessRenderEffect = /** @class */ (function () {
  57399. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  57400. this._engine = engine;
  57401. this._name = name;
  57402. this._singleInstance = singleInstance || true;
  57403. this._getPostProcess = getPostProcess;
  57404. this._cameras = {};
  57405. this._indicesForCamera = {};
  57406. this._postProcesses = {};
  57407. this._renderPasses = {};
  57408. this._renderEffectAsPasses = {};
  57409. }
  57410. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  57411. get: function () {
  57412. for (var index in this._postProcesses) {
  57413. if (!this._postProcesses[index].isSupported) {
  57414. return false;
  57415. }
  57416. }
  57417. return true;
  57418. },
  57419. enumerable: true,
  57420. configurable: true
  57421. });
  57422. PostProcessRenderEffect.prototype._update = function () {
  57423. for (var renderPassName in this._renderPasses) {
  57424. this._renderPasses[renderPassName]._update();
  57425. }
  57426. };
  57427. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  57428. this._renderPasses[renderPass._name] = renderPass;
  57429. this._linkParameters();
  57430. };
  57431. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  57432. delete this._renderPasses[renderPass._name];
  57433. this._linkParameters();
  57434. };
  57435. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  57436. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  57437. this._linkParameters();
  57438. };
  57439. PostProcessRenderEffect.prototype.getPass = function (passName) {
  57440. for (var renderPassName in this._renderPasses) {
  57441. if (renderPassName === passName) {
  57442. return this._renderPasses[passName];
  57443. }
  57444. }
  57445. return null;
  57446. };
  57447. PostProcessRenderEffect.prototype.emptyPasses = function () {
  57448. this._renderPasses = {};
  57449. this._linkParameters();
  57450. };
  57451. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  57452. var cameraKey;
  57453. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57454. if (!cams) {
  57455. return;
  57456. }
  57457. for (var i = 0; i < cams.length; i++) {
  57458. var camera = cams[i];
  57459. var cameraName = camera.name;
  57460. if (this._singleInstance) {
  57461. cameraKey = 0;
  57462. }
  57463. else {
  57464. cameraKey = cameraName;
  57465. }
  57466. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  57467. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  57468. if (!this._indicesForCamera[cameraName]) {
  57469. this._indicesForCamera[cameraName] = [];
  57470. }
  57471. this._indicesForCamera[cameraName].push(index);
  57472. if (!this._cameras[cameraName]) {
  57473. this._cameras[cameraName] = camera;
  57474. }
  57475. for (var passName in this._renderPasses) {
  57476. this._renderPasses[passName]._incRefCount();
  57477. }
  57478. }
  57479. this._linkParameters();
  57480. };
  57481. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  57482. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57483. if (!cams) {
  57484. return;
  57485. }
  57486. for (var i = 0; i < cams.length; i++) {
  57487. var camera = cams[i];
  57488. var cameraName = camera.name;
  57489. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57490. if (this._cameras[cameraName]) {
  57491. //this._indicesForCamera.splice(index, 1);
  57492. this._cameras[cameraName] = null;
  57493. }
  57494. for (var passName in this._renderPasses) {
  57495. this._renderPasses[passName]._decRefCount();
  57496. }
  57497. }
  57498. };
  57499. PostProcessRenderEffect.prototype._enable = function (cameras) {
  57500. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57501. if (!cams) {
  57502. return;
  57503. }
  57504. for (var i = 0; i < cams.length; i++) {
  57505. var camera = cams[i];
  57506. var cameraName = camera.name;
  57507. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  57508. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  57509. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  57510. }
  57511. }
  57512. for (var passName in this._renderPasses) {
  57513. this._renderPasses[passName]._incRefCount();
  57514. }
  57515. }
  57516. };
  57517. PostProcessRenderEffect.prototype._disable = function (cameras) {
  57518. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57519. if (!cams) {
  57520. return;
  57521. }
  57522. for (var i = 0; i < cams.length; i++) {
  57523. var camera = cams[i];
  57524. var cameraName = camera.Name;
  57525. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57526. for (var passName in this._renderPasses) {
  57527. this._renderPasses[passName]._decRefCount();
  57528. }
  57529. }
  57530. };
  57531. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  57532. if (this._singleInstance) {
  57533. return this._postProcesses[0];
  57534. }
  57535. else {
  57536. if (!camera) {
  57537. return null;
  57538. }
  57539. return this._postProcesses[camera.name];
  57540. }
  57541. };
  57542. PostProcessRenderEffect.prototype._linkParameters = function () {
  57543. var _this = this;
  57544. for (var index in this._postProcesses) {
  57545. if (this.applyParameters) {
  57546. this.applyParameters(this._postProcesses[index]);
  57547. }
  57548. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  57549. _this._linkTextures(effect);
  57550. });
  57551. }
  57552. };
  57553. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  57554. for (var renderPassName in this._renderPasses) {
  57555. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  57556. }
  57557. for (var renderEffectName in this._renderEffectAsPasses) {
  57558. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  57559. }
  57560. };
  57561. return PostProcessRenderEffect;
  57562. }());
  57563. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  57564. })(BABYLON || (BABYLON = {}));
  57565. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  57566. var BABYLON;
  57567. (function (BABYLON) {
  57568. var PostProcessRenderPipeline = /** @class */ (function () {
  57569. function PostProcessRenderPipeline(engine, name) {
  57570. this._engine = engine;
  57571. this._name = name;
  57572. this._renderEffects = {};
  57573. this._renderEffectsForIsolatedPass = new Array();
  57574. this._cameras = [];
  57575. }
  57576. PostProcessRenderPipeline.prototype.getClassName = function () {
  57577. return "PostProcessRenderPipeline";
  57578. };
  57579. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  57580. get: function () {
  57581. for (var renderEffectName in this._renderEffects) {
  57582. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57583. if (!this._renderEffects[renderEffectName].isSupported) {
  57584. return false;
  57585. }
  57586. }
  57587. }
  57588. return true;
  57589. },
  57590. enumerable: true,
  57591. configurable: true
  57592. });
  57593. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  57594. this._renderEffects[renderEffect._name] = renderEffect;
  57595. };
  57596. // private
  57597. PostProcessRenderPipeline.prototype._rebuild = function () {
  57598. };
  57599. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  57600. var renderEffects = this._renderEffects[renderEffectName];
  57601. if (!renderEffects) {
  57602. return;
  57603. }
  57604. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57605. };
  57606. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  57607. var renderEffects = this._renderEffects[renderEffectName];
  57608. if (!renderEffects) {
  57609. return;
  57610. }
  57611. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57612. };
  57613. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  57614. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57615. if (!cams) {
  57616. return;
  57617. }
  57618. var indicesToDelete = [];
  57619. var i;
  57620. for (i = 0; i < cams.length; i++) {
  57621. var camera = cams[i];
  57622. var cameraName = camera.name;
  57623. if (this._cameras.indexOf(camera) === -1) {
  57624. this._cameras[cameraName] = camera;
  57625. }
  57626. else if (unique) {
  57627. indicesToDelete.push(i);
  57628. }
  57629. }
  57630. for (i = 0; i < indicesToDelete.length; i++) {
  57631. cameras.splice(indicesToDelete[i], 1);
  57632. }
  57633. for (var renderEffectName in this._renderEffects) {
  57634. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57635. this._renderEffects[renderEffectName]._attachCameras(cams);
  57636. }
  57637. }
  57638. };
  57639. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  57640. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57641. if (!cams) {
  57642. return;
  57643. }
  57644. for (var renderEffectName in this._renderEffects) {
  57645. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57646. this._renderEffects[renderEffectName]._detachCameras(cams);
  57647. }
  57648. }
  57649. for (var i = 0; i < cams.length; i++) {
  57650. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  57651. }
  57652. };
  57653. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  57654. var _this = this;
  57655. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57656. if (!cams) {
  57657. return;
  57658. }
  57659. var pass = null;
  57660. var renderEffectName;
  57661. for (renderEffectName in this._renderEffects) {
  57662. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57663. pass = this._renderEffects[renderEffectName].getPass(passName);
  57664. if (pass != null) {
  57665. break;
  57666. }
  57667. }
  57668. }
  57669. if (pass === null) {
  57670. return;
  57671. }
  57672. for (renderEffectName in this._renderEffects) {
  57673. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57674. this._renderEffects[renderEffectName]._disable(cams);
  57675. }
  57676. }
  57677. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  57678. for (var i = 0; i < cams.length; i++) {
  57679. var camera = cams[i];
  57680. var cameraName = camera.name;
  57681. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  57682. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  57683. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  57684. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  57685. }
  57686. };
  57687. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  57688. var _this = this;
  57689. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57690. if (!cams) {
  57691. return;
  57692. }
  57693. for (var i = 0; i < cams.length; i++) {
  57694. var camera = cams[i];
  57695. var cameraName = camera.name;
  57696. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  57697. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  57698. }
  57699. for (var renderEffectName in this._renderEffects) {
  57700. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57701. this._renderEffects[renderEffectName]._enable(cams);
  57702. }
  57703. }
  57704. };
  57705. PostProcessRenderPipeline.prototype._update = function () {
  57706. for (var renderEffectName in this._renderEffects) {
  57707. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57708. this._renderEffects[renderEffectName]._update();
  57709. }
  57710. }
  57711. for (var i = 0; i < this._cameras.length; i++) {
  57712. var cameraName = this._cameras[i].name;
  57713. if (this._renderEffectsForIsolatedPass[cameraName]) {
  57714. this._renderEffectsForIsolatedPass[cameraName]._update();
  57715. }
  57716. }
  57717. };
  57718. PostProcessRenderPipeline.prototype._reset = function () {
  57719. this._renderEffects = {};
  57720. this._renderEffectsForIsolatedPass = new Array();
  57721. };
  57722. PostProcessRenderPipeline.prototype.dispose = function () {
  57723. // Must be implemented by children
  57724. };
  57725. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  57726. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  57727. __decorate([
  57728. BABYLON.serialize()
  57729. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  57730. return PostProcessRenderPipeline;
  57731. }());
  57732. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  57733. })(BABYLON || (BABYLON = {}));
  57734. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  57735. var BABYLON;
  57736. (function (BABYLON) {
  57737. var DepthRenderer = /** @class */ (function () {
  57738. function DepthRenderer(scene, type) {
  57739. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  57740. var _this = this;
  57741. this._scene = scene;
  57742. var engine = scene.getEngine();
  57743. // Render target
  57744. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  57745. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57746. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57747. this._depthMap.refreshRate = 1;
  57748. this._depthMap.renderParticles = false;
  57749. this._depthMap.renderList = null;
  57750. // set default depth value to 1.0 (far away)
  57751. this._depthMap.onClearObservable.add(function (engine) {
  57752. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  57753. });
  57754. // Custom render function
  57755. var renderSubMesh = function (subMesh) {
  57756. var mesh = subMesh.getRenderingMesh();
  57757. var scene = _this._scene;
  57758. var engine = scene.getEngine();
  57759. var material = subMesh.getMaterial();
  57760. if (!material) {
  57761. return;
  57762. }
  57763. // Culling
  57764. engine.setState(material.backFaceCulling);
  57765. // Managing instances
  57766. var batch = mesh._getInstancesRenderList(subMesh._id);
  57767. if (batch.mustReturn) {
  57768. return;
  57769. }
  57770. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57771. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  57772. engine.enableEffect(_this._effect);
  57773. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  57774. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  57775. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  57776. // Alpha test
  57777. if (material && material.needAlphaTesting()) {
  57778. var alphaTexture = material.getAlphaTestTexture();
  57779. if (alphaTexture) {
  57780. _this._effect.setTexture("diffuseSampler", alphaTexture);
  57781. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57782. }
  57783. }
  57784. // Bones
  57785. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57786. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57787. }
  57788. // Draw
  57789. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57790. }
  57791. };
  57792. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57793. var index;
  57794. if (depthOnlySubMeshes.length) {
  57795. engine.setColorWrite(false);
  57796. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57797. renderSubMesh(depthOnlySubMeshes.data[index]);
  57798. }
  57799. engine.setColorWrite(true);
  57800. }
  57801. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57802. renderSubMesh(opaqueSubMeshes.data[index]);
  57803. }
  57804. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57805. renderSubMesh(alphaTestSubMeshes.data[index]);
  57806. }
  57807. };
  57808. }
  57809. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  57810. var material = subMesh.getMaterial();
  57811. if (material.disableDepthWrite) {
  57812. return false;
  57813. }
  57814. var defines = [];
  57815. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57816. var mesh = subMesh.getMesh();
  57817. // Alpha test
  57818. if (material && material.needAlphaTesting()) {
  57819. defines.push("#define ALPHATEST");
  57820. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57821. attribs.push(BABYLON.VertexBuffer.UVKind);
  57822. defines.push("#define UV1");
  57823. }
  57824. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57825. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57826. defines.push("#define UV2");
  57827. }
  57828. }
  57829. // Bones
  57830. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57831. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57832. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57833. if (mesh.numBoneInfluencers > 4) {
  57834. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57835. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57836. }
  57837. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57838. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  57839. }
  57840. else {
  57841. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57842. }
  57843. // Instances
  57844. if (useInstances) {
  57845. defines.push("#define INSTANCES");
  57846. attribs.push("world0");
  57847. attribs.push("world1");
  57848. attribs.push("world2");
  57849. attribs.push("world3");
  57850. }
  57851. // Get correct effect
  57852. var join = defines.join("\n");
  57853. if (this._cachedDefines !== join) {
  57854. this._cachedDefines = join;
  57855. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  57856. }
  57857. return this._effect.isReady();
  57858. };
  57859. DepthRenderer.prototype.getDepthMap = function () {
  57860. return this._depthMap;
  57861. };
  57862. // Methods
  57863. DepthRenderer.prototype.dispose = function () {
  57864. this._depthMap.dispose();
  57865. };
  57866. return DepthRenderer;
  57867. }());
  57868. BABYLON.DepthRenderer = DepthRenderer;
  57869. })(BABYLON || (BABYLON = {}));
  57870. //# sourceMappingURL=babylon.depthRenderer.js.map
  57871. var BABYLON;
  57872. (function (BABYLON) {
  57873. var SSAORenderingPipeline = /** @class */ (function (_super) {
  57874. __extends(SSAORenderingPipeline, _super);
  57875. /**
  57876. * @constructor
  57877. * @param {string} name - The rendering pipeline name
  57878. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57879. * @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 }
  57880. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57881. */
  57882. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  57883. var _this = _super.call(this, scene.getEngine(), name) || this;
  57884. // Members
  57885. /**
  57886. * The PassPostProcess id in the pipeline that contains the original scene color
  57887. * @type {string}
  57888. */
  57889. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57890. /**
  57891. * The SSAO PostProcess id in the pipeline
  57892. * @type {string}
  57893. */
  57894. _this.SSAORenderEffect = "SSAORenderEffect";
  57895. /**
  57896. * The horizontal blur PostProcess id in the pipeline
  57897. * @type {string}
  57898. */
  57899. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57900. /**
  57901. * The vertical blur PostProcess id in the pipeline
  57902. * @type {string}
  57903. */
  57904. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57905. /**
  57906. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57907. * @type {string}
  57908. */
  57909. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57910. /**
  57911. * The output strength of the SSAO post-process. Default value is 1.0.
  57912. * @type {number}
  57913. */
  57914. _this.totalStrength = 1.0;
  57915. /**
  57916. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  57917. * @type {number}
  57918. */
  57919. _this.radius = 0.0001;
  57920. /**
  57921. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  57922. * Must not be equal to fallOff and superior to fallOff.
  57923. * Default value is 0.975
  57924. * @type {number}
  57925. */
  57926. _this.area = 0.0075;
  57927. /**
  57928. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  57929. * Must not be equal to area and inferior to area.
  57930. * Default value is 0.0
  57931. * @type {number}
  57932. */
  57933. _this.fallOff = 0.000001;
  57934. /**
  57935. * The base color of the SSAO post-process
  57936. * The final result is "base + ssao" between [0, 1]
  57937. * @type {number}
  57938. */
  57939. _this.base = 0.5;
  57940. _this._firstUpdate = true;
  57941. _this._scene = scene;
  57942. // Set up assets
  57943. _this._createRandomTexture();
  57944. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57945. var ssaoRatio = ratio.ssaoRatio || ratio;
  57946. var combineRatio = ratio.combineRatio || ratio;
  57947. _this._ratio = {
  57948. ssaoRatio: ssaoRatio,
  57949. combineRatio: combineRatio
  57950. };
  57951. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57952. _this._createSSAOPostProcess(ssaoRatio);
  57953. _this._createBlurPostProcess(ssaoRatio);
  57954. _this._createSSAOCombinePostProcess(combineRatio);
  57955. // Set up pipeline
  57956. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57957. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57958. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57959. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57960. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57961. // Finish
  57962. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57963. if (cameras)
  57964. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57965. return _this;
  57966. }
  57967. // Public Methods
  57968. /**
  57969. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57970. */
  57971. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57972. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57973. for (var i = 0; i < this._scene.cameras.length; i++) {
  57974. var camera = this._scene.cameras[i];
  57975. this._originalColorPostProcess.dispose(camera);
  57976. this._ssaoPostProcess.dispose(camera);
  57977. this._blurHPostProcess.dispose(camera);
  57978. this._blurVPostProcess.dispose(camera);
  57979. this._ssaoCombinePostProcess.dispose(camera);
  57980. }
  57981. this._randomTexture.dispose();
  57982. if (disableDepthRender)
  57983. this._scene.disableDepthRenderer();
  57984. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57985. _super.prototype.dispose.call(this);
  57986. };
  57987. // Private Methods
  57988. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  57989. var _this = this;
  57990. var size = 16;
  57991. 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);
  57992. 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);
  57993. this._blurHPostProcess.onActivateObservable.add(function () {
  57994. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  57995. _this._blurHPostProcess.kernel = size * dw;
  57996. });
  57997. this._blurVPostProcess.onActivateObservable.add(function () {
  57998. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  57999. _this._blurVPostProcess.kernel = size * dw;
  58000. });
  58001. };
  58002. SSAORenderingPipeline.prototype._rebuild = function () {
  58003. this._firstUpdate = true;
  58004. _super.prototype._rebuild.call(this);
  58005. };
  58006. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58007. var _this = this;
  58008. var numSamples = 16;
  58009. var sampleSphere = [
  58010. 0.5381, 0.1856, -0.4319,
  58011. 0.1379, 0.2486, 0.4430,
  58012. 0.3371, 0.5679, -0.0057,
  58013. -0.6999, -0.0451, -0.0019,
  58014. 0.0689, -0.1598, -0.8547,
  58015. 0.0560, 0.0069, -0.1843,
  58016. -0.0146, 0.1402, 0.0762,
  58017. 0.0100, -0.1924, -0.0344,
  58018. -0.3577, -0.5301, -0.4358,
  58019. -0.3169, 0.1063, 0.0158,
  58020. 0.0103, -0.5869, 0.0046,
  58021. -0.0897, -0.4940, 0.3287,
  58022. 0.7119, -0.0154, -0.0918,
  58023. -0.0533, 0.0596, -0.5411,
  58024. 0.0352, -0.0631, 0.5460,
  58025. -0.4776, 0.2847, -0.0271
  58026. ];
  58027. var samplesFactor = 1.0 / numSamples;
  58028. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  58029. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58030. "area", "fallOff", "base", "range", "viewport"
  58031. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58032. this._ssaoPostProcess.onApply = function (effect) {
  58033. if (_this._firstUpdate) {
  58034. effect.setArray3("sampleSphere", sampleSphere);
  58035. effect.setFloat("samplesFactor", samplesFactor);
  58036. effect.setFloat("randTextureTiles", 4.0);
  58037. }
  58038. effect.setFloat("totalStrength", _this.totalStrength);
  58039. effect.setFloat("radius", _this.radius);
  58040. effect.setFloat("area", _this.area);
  58041. effect.setFloat("fallOff", _this.fallOff);
  58042. effect.setFloat("base", _this.base);
  58043. effect.setTexture("textureSampler", _this._depthTexture);
  58044. effect.setTexture("randomSampler", _this._randomTexture);
  58045. };
  58046. };
  58047. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58048. var _this = this;
  58049. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58050. this._ssaoCombinePostProcess.onApply = function (effect) {
  58051. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58052. };
  58053. };
  58054. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  58055. var size = 512;
  58056. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58057. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58058. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58059. var context = this._randomTexture.getContext();
  58060. var rand = function (min, max) {
  58061. return Math.random() * (max - min) + min;
  58062. };
  58063. var randVector = BABYLON.Vector3.Zero();
  58064. for (var x = 0; x < size; x++) {
  58065. for (var y = 0; y < size; y++) {
  58066. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  58067. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  58068. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  58069. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58070. context.fillRect(x, y, 1, 1);
  58071. }
  58072. }
  58073. this._randomTexture.update(false);
  58074. };
  58075. __decorate([
  58076. BABYLON.serialize()
  58077. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  58078. __decorate([
  58079. BABYLON.serialize()
  58080. ], SSAORenderingPipeline.prototype, "radius", void 0);
  58081. __decorate([
  58082. BABYLON.serialize()
  58083. ], SSAORenderingPipeline.prototype, "area", void 0);
  58084. __decorate([
  58085. BABYLON.serialize()
  58086. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  58087. __decorate([
  58088. BABYLON.serialize()
  58089. ], SSAORenderingPipeline.prototype, "base", void 0);
  58090. __decorate([
  58091. BABYLON.serialize()
  58092. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  58093. return SSAORenderingPipeline;
  58094. }(BABYLON.PostProcessRenderPipeline));
  58095. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  58096. })(BABYLON || (BABYLON = {}));
  58097. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  58098. var BABYLON;
  58099. (function (BABYLON) {
  58100. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  58101. __extends(SSAO2RenderingPipeline, _super);
  58102. /**
  58103. * @constructor
  58104. * @param {string} name - The rendering pipeline name
  58105. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58106. * @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 }
  58107. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58108. */
  58109. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  58110. var _this = _super.call(this, scene.getEngine(), name) || this;
  58111. // Members
  58112. /**
  58113. * The PassPostProcess id in the pipeline that contains the original scene color
  58114. * @type {string}
  58115. */
  58116. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  58117. /**
  58118. * The SSAO PostProcess id in the pipeline
  58119. * @type {string}
  58120. */
  58121. _this.SSAORenderEffect = "SSAORenderEffect";
  58122. /**
  58123. * The horizontal blur PostProcess id in the pipeline
  58124. * @type {string}
  58125. */
  58126. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  58127. /**
  58128. * The vertical blur PostProcess id in the pipeline
  58129. * @type {string}
  58130. */
  58131. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  58132. /**
  58133. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  58134. * @type {string}
  58135. */
  58136. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  58137. /**
  58138. * The output strength of the SSAO post-process. Default value is 1.0.
  58139. * @type {number}
  58140. */
  58141. _this.totalStrength = 1.0;
  58142. /**
  58143. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  58144. * @type {number}
  58145. */
  58146. _this.maxZ = 100.0;
  58147. /**
  58148. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  58149. * @type {number}
  58150. */
  58151. _this.minZAspect = 0.2;
  58152. /**
  58153. * Number of samples used for the SSAO calculations. Default value is 8
  58154. * @type {number}
  58155. */
  58156. _this._samples = 8;
  58157. /**
  58158. * Are we using bilateral blur ?
  58159. * @type {boolean}
  58160. */
  58161. _this._expensiveBlur = true;
  58162. /**
  58163. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  58164. * @type {number}
  58165. */
  58166. _this.radius = 2.0;
  58167. /**
  58168. * The base color of the SSAO post-process
  58169. * The final result is "base + ssao" between [0, 1]
  58170. * @type {number}
  58171. */
  58172. _this.base = 0.1;
  58173. _this._firstUpdate = true;
  58174. _this._scene = scene;
  58175. if (!_this.isSupported) {
  58176. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  58177. return _this;
  58178. }
  58179. var ssaoRatio = ratio.ssaoRatio || ratio;
  58180. var blurRatio = ratio.blurRatio || ratio;
  58181. _this._ratio = {
  58182. ssaoRatio: ssaoRatio,
  58183. blurRatio: blurRatio
  58184. };
  58185. // Set up assets
  58186. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  58187. _this._createRandomTexture();
  58188. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  58189. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  58190. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  58191. _this._createSSAOPostProcess(1.0);
  58192. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  58193. _this._createSSAOCombinePostProcess(blurRatio);
  58194. // Set up pipeline
  58195. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  58196. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  58197. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  58198. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  58199. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  58200. // Finish
  58201. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58202. if (cameras)
  58203. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58204. return _this;
  58205. }
  58206. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  58207. get: function () {
  58208. return this._samples;
  58209. },
  58210. set: function (n) {
  58211. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  58212. this._samples = n;
  58213. this._sampleSphere = this._generateHemisphere();
  58214. this._firstUpdate = true;
  58215. },
  58216. enumerable: true,
  58217. configurable: true
  58218. });
  58219. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  58220. get: function () {
  58221. return this._expensiveBlur;
  58222. },
  58223. set: function (b) {
  58224. 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"]);
  58225. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  58226. this._expensiveBlur = b;
  58227. this._firstUpdate = true;
  58228. },
  58229. enumerable: true,
  58230. configurable: true
  58231. });
  58232. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  58233. /**
  58234. * Support test.
  58235. * @type {boolean}
  58236. */
  58237. get: function () {
  58238. var engine = BABYLON.Engine.LastCreatedEngine;
  58239. if (!engine) {
  58240. return false;
  58241. }
  58242. return engine.getCaps().drawBuffersExtension;
  58243. },
  58244. enumerable: true,
  58245. configurable: true
  58246. });
  58247. // Public Methods
  58248. /**
  58249. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  58250. */
  58251. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  58252. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  58253. for (var i = 0; i < this._scene.cameras.length; i++) {
  58254. var camera = this._scene.cameras[i];
  58255. this._originalColorPostProcess.dispose(camera);
  58256. this._ssaoPostProcess.dispose(camera);
  58257. this._blurHPostProcess.dispose(camera);
  58258. this._blurVPostProcess.dispose(camera);
  58259. this._ssaoCombinePostProcess.dispose(camera);
  58260. }
  58261. this._randomTexture.dispose();
  58262. if (disableGeometryBufferRenderer)
  58263. this._scene.disableGeometryBufferRenderer();
  58264. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58265. _super.prototype.dispose.call(this);
  58266. };
  58267. // Private Methods
  58268. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  58269. var _this = this;
  58270. this._samplerOffsets = [];
  58271. var expensive = this.expensiveBlur;
  58272. for (var i = -8; i < 8; i++) {
  58273. this._samplerOffsets.push(i * 2 + 0.5);
  58274. }
  58275. 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");
  58276. this._blurHPostProcess.onApply = function (effect) {
  58277. if (!_this._scene.activeCamera) {
  58278. return;
  58279. }
  58280. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  58281. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58282. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58283. effect.setFloat("radius", _this.radius);
  58284. effect.setTexture("depthSampler", _this._depthTexture);
  58285. if (_this._firstUpdate) {
  58286. effect.setArray("samplerOffsets", _this._samplerOffsets);
  58287. }
  58288. };
  58289. 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");
  58290. this._blurVPostProcess.onApply = function (effect) {
  58291. if (!_this._scene.activeCamera) {
  58292. return;
  58293. }
  58294. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  58295. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58296. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58297. effect.setFloat("radius", _this.radius);
  58298. effect.setTexture("depthSampler", _this._depthTexture);
  58299. if (_this._firstUpdate) {
  58300. effect.setArray("samplerOffsets", _this._samplerOffsets);
  58301. _this._firstUpdate = false;
  58302. }
  58303. };
  58304. };
  58305. SSAO2RenderingPipeline.prototype._rebuild = function () {
  58306. this._firstUpdate = true;
  58307. _super.prototype._rebuild.call(this);
  58308. };
  58309. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  58310. var numSamples = this.samples;
  58311. var result = [];
  58312. var vector, scale;
  58313. var rand = function (min, max) {
  58314. return Math.random() * (max - min) + min;
  58315. };
  58316. var i = 0;
  58317. while (i < numSamples) {
  58318. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  58319. vector.normalize();
  58320. scale = i / numSamples;
  58321. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  58322. vector.scaleInPlace(scale);
  58323. result.push(vector.x, vector.y, vector.z);
  58324. i++;
  58325. }
  58326. return result;
  58327. };
  58328. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  58329. var _this = this;
  58330. var numSamples = this.samples;
  58331. this._sampleSphere = this._generateHemisphere();
  58332. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  58333. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  58334. "base", "range", "projection", "near", "far", "texelSize",
  58335. "xViewport", "yViewport", "maxZ", "minZAspect"
  58336. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  58337. this._ssaoPostProcess.onApply = function (effect) {
  58338. if (_this._firstUpdate) {
  58339. effect.setArray3("sampleSphere", _this._sampleSphere);
  58340. effect.setFloat("randTextureTiles", 4.0);
  58341. }
  58342. if (!_this._scene.activeCamera) {
  58343. return;
  58344. }
  58345. effect.setFloat("samplesFactor", 1 / _this.samples);
  58346. effect.setFloat("totalStrength", _this.totalStrength);
  58347. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  58348. effect.setFloat("radius", _this.radius);
  58349. effect.setFloat("maxZ", _this.maxZ);
  58350. effect.setFloat("minZAspect", _this.minZAspect);
  58351. effect.setFloat("base", _this.base);
  58352. effect.setFloat("near", _this._scene.activeCamera.minZ);
  58353. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  58354. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  58355. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  58356. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  58357. effect.setTexture("textureSampler", _this._depthTexture);
  58358. effect.setTexture("normalSampler", _this._normalTexture);
  58359. effect.setTexture("randomSampler", _this._randomTexture);
  58360. };
  58361. };
  58362. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  58363. var _this = this;
  58364. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58365. this._ssaoCombinePostProcess.onApply = function (effect) {
  58366. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  58367. };
  58368. };
  58369. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  58370. var size = 512;
  58371. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  58372. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58373. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58374. var context = this._randomTexture.getContext();
  58375. var rand = function (min, max) {
  58376. return Math.random() * (max - min) + min;
  58377. };
  58378. var randVector = BABYLON.Vector3.Zero();
  58379. for (var x = 0; x < size; x++) {
  58380. for (var y = 0; y < size; y++) {
  58381. randVector.x = rand(0.0, 1.0);
  58382. randVector.y = rand(0.0, 1.0);
  58383. randVector.z = 0.0;
  58384. randVector.normalize();
  58385. randVector.scaleInPlace(255);
  58386. randVector.x = Math.floor(randVector.x);
  58387. randVector.y = Math.floor(randVector.y);
  58388. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  58389. context.fillRect(x, y, 1, 1);
  58390. }
  58391. }
  58392. this._randomTexture.update(false);
  58393. };
  58394. __decorate([
  58395. BABYLON.serialize()
  58396. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  58397. __decorate([
  58398. BABYLON.serialize()
  58399. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  58400. __decorate([
  58401. BABYLON.serialize()
  58402. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  58403. __decorate([
  58404. BABYLON.serialize("samples")
  58405. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  58406. __decorate([
  58407. BABYLON.serialize("expensiveBlur")
  58408. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  58409. __decorate([
  58410. BABYLON.serialize()
  58411. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  58412. __decorate([
  58413. BABYLON.serialize()
  58414. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  58415. __decorate([
  58416. BABYLON.serialize()
  58417. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  58418. return SSAO2RenderingPipeline;
  58419. }(BABYLON.PostProcessRenderPipeline));
  58420. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  58421. })(BABYLON || (BABYLON = {}));
  58422. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  58423. // BABYLON.JS Chromatic Aberration GLSL Shader
  58424. // Author: Olivier Guyot
  58425. // Separates very slightly R, G and B colors on the edges of the screen
  58426. // Inspired by Francois Tarlier & Martins Upitis
  58427. var BABYLON;
  58428. (function (BABYLON) {
  58429. var LensRenderingPipeline = /** @class */ (function (_super) {
  58430. __extends(LensRenderingPipeline, _super);
  58431. /**
  58432. * @constructor
  58433. *
  58434. * Effect parameters are as follow:
  58435. * {
  58436. * chromatic_aberration: number; // from 0 to x (1 for realism)
  58437. * edge_blur: number; // from 0 to x (1 for realism)
  58438. * distortion: number; // from 0 to x (1 for realism)
  58439. * grain_amount: number; // from 0 to 1
  58440. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  58441. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  58442. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  58443. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  58444. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  58445. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  58446. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  58447. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  58448. * }
  58449. * Note: if an effect parameter is unset, effect is disabled
  58450. *
  58451. * @param {string} name - The rendering pipeline name
  58452. * @param {object} parameters - An object containing all parameters (see above)
  58453. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58454. * @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)
  58455. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58456. */
  58457. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  58458. if (ratio === void 0) { ratio = 1.0; }
  58459. var _this = _super.call(this, scene.getEngine(), name) || this;
  58460. // Lens effects can be of the following:
  58461. // - chromatic aberration (slight shift of RGB colors)
  58462. // - blur on the edge of the lens
  58463. // - lens distortion
  58464. // - depth-of-field blur & highlights enhancing
  58465. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  58466. // - grain effect (noise or custom texture)
  58467. // Two additional texture samplers are needed:
  58468. // - depth map (for depth-of-field)
  58469. // - grain texture
  58470. /**
  58471. * The chromatic aberration PostProcess id in the pipeline
  58472. * @type {string}
  58473. */
  58474. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  58475. /**
  58476. * The highlights enhancing PostProcess id in the pipeline
  58477. * @type {string}
  58478. */
  58479. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  58480. /**
  58481. * The depth-of-field PostProcess id in the pipeline
  58482. * @type {string}
  58483. */
  58484. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  58485. _this._scene = scene;
  58486. // Fetch texture samplers
  58487. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  58488. if (parameters.grain_texture) {
  58489. _this._grainTexture = parameters.grain_texture;
  58490. }
  58491. else {
  58492. _this._createGrainTexture();
  58493. }
  58494. // save parameters
  58495. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  58496. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  58497. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  58498. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  58499. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  58500. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  58501. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  58502. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  58503. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  58504. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  58505. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  58506. // Create effects
  58507. _this._createChromaticAberrationPostProcess(ratio);
  58508. _this._createHighlightsPostProcess(ratio);
  58509. _this._createDepthOfFieldPostProcess(ratio / 4);
  58510. // Set up pipeline
  58511. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  58512. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  58513. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  58514. if (_this._highlightsGain === -1) {
  58515. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  58516. }
  58517. // Finish
  58518. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58519. if (cameras) {
  58520. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58521. }
  58522. return _this;
  58523. }
  58524. // public methods (self explanatory)
  58525. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  58526. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  58527. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  58528. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  58529. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  58530. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  58531. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  58532. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  58533. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  58534. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  58535. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  58536. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  58537. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  58538. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  58539. };
  58540. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  58541. this._highlightsPostProcess.updateEffect();
  58542. };
  58543. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  58544. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  58545. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  58546. this._highlightsGain = amount;
  58547. };
  58548. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  58549. if (this._highlightsGain === -1) {
  58550. this._highlightsGain = 1.0;
  58551. }
  58552. this._highlightsThreshold = amount;
  58553. };
  58554. LensRenderingPipeline.prototype.disableHighlights = function () {
  58555. this._highlightsGain = -1;
  58556. };
  58557. /**
  58558. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  58559. */
  58560. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58561. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58562. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58563. this._chromaticAberrationPostProcess = null;
  58564. this._highlightsPostProcess = null;
  58565. this._depthOfFieldPostProcess = null;
  58566. this._grainTexture.dispose();
  58567. if (disableDepthRender)
  58568. this._scene.disableDepthRenderer();
  58569. };
  58570. // colors shifting and distortion
  58571. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  58572. var _this = this;
  58573. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  58574. [], // samplers
  58575. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58576. this._chromaticAberrationPostProcess.onApply = function (effect) {
  58577. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  58578. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58579. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58580. };
  58581. };
  58582. // highlights enhancing
  58583. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  58584. var _this = this;
  58585. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  58586. [], // samplers
  58587. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  58588. this._highlightsPostProcess.onApply = function (effect) {
  58589. effect.setFloat('gain', _this._highlightsGain);
  58590. effect.setFloat('threshold', _this._highlightsThreshold);
  58591. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  58592. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58593. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58594. };
  58595. };
  58596. // colors shifting and distortion
  58597. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  58598. var _this = this;
  58599. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  58600. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  58601. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  58602. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58603. this._depthOfFieldPostProcess.onApply = function (effect) {
  58604. effect.setTexture("depthSampler", _this._depthTexture);
  58605. effect.setTexture("grainSampler", _this._grainTexture);
  58606. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  58607. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  58608. effect.setFloat('grain_amount', _this._grainAmount);
  58609. effect.setBool('blur_noise', _this._blurNoise);
  58610. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58611. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58612. effect.setFloat('distortion', _this._distortion);
  58613. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  58614. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  58615. effect.setFloat('aperture', _this._dofAperture);
  58616. effect.setFloat('darken', _this._dofDarken);
  58617. effect.setFloat('edge_blur', _this._edgeBlur);
  58618. effect.setBool('highlights', (_this._highlightsGain !== -1));
  58619. if (_this._scene.activeCamera) {
  58620. effect.setFloat('near', _this._scene.activeCamera.minZ);
  58621. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  58622. }
  58623. };
  58624. };
  58625. // creates a black and white random noise texture, 512x512
  58626. LensRenderingPipeline.prototype._createGrainTexture = function () {
  58627. var size = 512;
  58628. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58629. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58630. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58631. var context = this._grainTexture.getContext();
  58632. var rand = function (min, max) {
  58633. return Math.random() * (max - min) + min;
  58634. };
  58635. var value;
  58636. for (var x = 0; x < size; x++) {
  58637. for (var y = 0; y < size; y++) {
  58638. value = Math.floor(rand(0.42, 0.58) * 255);
  58639. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  58640. context.fillRect(x, y, 1, 1);
  58641. }
  58642. }
  58643. this._grainTexture.update(false);
  58644. };
  58645. return LensRenderingPipeline;
  58646. }(BABYLON.PostProcessRenderPipeline));
  58647. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  58648. })(BABYLON || (BABYLON = {}));
  58649. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  58650. var BABYLON;
  58651. (function (BABYLON) {
  58652. var StandardRenderingPipeline = /** @class */ (function (_super) {
  58653. __extends(StandardRenderingPipeline, _super);
  58654. /**
  58655. * @constructor
  58656. * @param {string} name - The rendering pipeline name
  58657. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58658. * @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)
  58659. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  58660. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58661. */
  58662. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  58663. if (originalPostProcess === void 0) { originalPostProcess = null; }
  58664. var _this = _super.call(this, scene.getEngine(), name) || this;
  58665. _this.downSampleX4PostProcess = null;
  58666. _this.brightPassPostProcess = null;
  58667. _this.blurHPostProcesses = [];
  58668. _this.blurVPostProcesses = [];
  58669. _this.textureAdderPostProcess = null;
  58670. _this.volumetricLightPostProcess = null;
  58671. _this.volumetricLightSmoothXPostProcess = null;
  58672. _this.volumetricLightSmoothYPostProcess = null;
  58673. _this.volumetricLightMergePostProces = null;
  58674. _this.volumetricLightFinalPostProcess = null;
  58675. _this.luminancePostProcess = null;
  58676. _this.luminanceDownSamplePostProcesses = [];
  58677. _this.hdrPostProcess = null;
  58678. _this.textureAdderFinalPostProcess = null;
  58679. _this.lensFlareFinalPostProcess = null;
  58680. _this.hdrFinalPostProcess = null;
  58681. _this.lensFlarePostProcess = null;
  58682. _this.lensFlareComposePostProcess = null;
  58683. _this.motionBlurPostProcess = null;
  58684. _this.depthOfFieldPostProcess = null;
  58685. // Values
  58686. _this.brightThreshold = 1.0;
  58687. _this.blurWidth = 512.0;
  58688. _this.horizontalBlur = false;
  58689. _this.exposure = 1.0;
  58690. _this.lensTexture = null;
  58691. _this.volumetricLightCoefficient = 0.2;
  58692. _this.volumetricLightPower = 4.0;
  58693. _this.volumetricLightBlurScale = 64.0;
  58694. _this.sourceLight = null;
  58695. _this.hdrMinimumLuminance = 1.0;
  58696. _this.hdrDecreaseRate = 0.5;
  58697. _this.hdrIncreaseRate = 0.5;
  58698. _this.lensColorTexture = null;
  58699. _this.lensFlareStrength = 20.0;
  58700. _this.lensFlareGhostDispersal = 1.4;
  58701. _this.lensFlareHaloWidth = 0.7;
  58702. _this.lensFlareDistortionStrength = 16.0;
  58703. _this.lensStarTexture = null;
  58704. _this.lensFlareDirtTexture = null;
  58705. _this.depthOfFieldDistance = 10.0;
  58706. _this.depthOfFieldBlurWidth = 64.0;
  58707. _this.motionStrength = 1.0;
  58708. // IAnimatable
  58709. _this.animations = [];
  58710. _this._currentDepthOfFieldSource = null;
  58711. _this._hdrCurrentLuminance = 1.0;
  58712. // Getters and setters
  58713. _this._bloomEnabled = true;
  58714. _this._depthOfFieldEnabled = false;
  58715. _this._vlsEnabled = false;
  58716. _this._lensFlareEnabled = false;
  58717. _this._hdrEnabled = false;
  58718. _this._motionBlurEnabled = false;
  58719. _this._motionBlurSamples = 64.0;
  58720. _this._volumetricLightStepsCount = 50.0;
  58721. _this._cameras = cameras || [];
  58722. // Initialize
  58723. _this._scene = scene;
  58724. _this._basePostProcess = originalPostProcess;
  58725. _this._ratio = ratio;
  58726. // Misc
  58727. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58728. // Finish
  58729. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58730. _this._buildPipeline();
  58731. return _this;
  58732. }
  58733. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  58734. get: function () {
  58735. return this._bloomEnabled;
  58736. },
  58737. set: function (enabled) {
  58738. if (this._bloomEnabled === enabled) {
  58739. return;
  58740. }
  58741. this._bloomEnabled = enabled;
  58742. this._buildPipeline();
  58743. },
  58744. enumerable: true,
  58745. configurable: true
  58746. });
  58747. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  58748. get: function () {
  58749. return this._depthOfFieldEnabled;
  58750. },
  58751. set: function (enabled) {
  58752. if (this._depthOfFieldEnabled === enabled) {
  58753. return;
  58754. }
  58755. this._depthOfFieldEnabled = enabled;
  58756. this._buildPipeline();
  58757. },
  58758. enumerable: true,
  58759. configurable: true
  58760. });
  58761. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  58762. get: function () {
  58763. return this._lensFlareEnabled;
  58764. },
  58765. set: function (enabled) {
  58766. if (this._lensFlareEnabled === enabled) {
  58767. return;
  58768. }
  58769. this._lensFlareEnabled = enabled;
  58770. this._buildPipeline();
  58771. },
  58772. enumerable: true,
  58773. configurable: true
  58774. });
  58775. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  58776. get: function () {
  58777. return this._hdrEnabled;
  58778. },
  58779. set: function (enabled) {
  58780. if (this._hdrEnabled === enabled) {
  58781. return;
  58782. }
  58783. this._hdrEnabled = enabled;
  58784. this._buildPipeline();
  58785. },
  58786. enumerable: true,
  58787. configurable: true
  58788. });
  58789. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  58790. get: function () {
  58791. return this._vlsEnabled;
  58792. },
  58793. set: function (enabled) {
  58794. if (this._vlsEnabled === enabled) {
  58795. return;
  58796. }
  58797. if (enabled) {
  58798. var geometry = this._scene.enableGeometryBufferRenderer();
  58799. if (!geometry) {
  58800. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  58801. return;
  58802. }
  58803. }
  58804. this._vlsEnabled = enabled;
  58805. this._buildPipeline();
  58806. },
  58807. enumerable: true,
  58808. configurable: true
  58809. });
  58810. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  58811. get: function () {
  58812. return this._motionBlurEnabled;
  58813. },
  58814. set: function (enabled) {
  58815. if (this._motionBlurEnabled === enabled) {
  58816. return;
  58817. }
  58818. this._motionBlurEnabled = enabled;
  58819. this._buildPipeline();
  58820. },
  58821. enumerable: true,
  58822. configurable: true
  58823. });
  58824. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  58825. get: function () {
  58826. return this._volumetricLightStepsCount;
  58827. },
  58828. set: function (count) {
  58829. if (this.volumetricLightPostProcess) {
  58830. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  58831. }
  58832. this._volumetricLightStepsCount = count;
  58833. },
  58834. enumerable: true,
  58835. configurable: true
  58836. });
  58837. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  58838. get: function () {
  58839. return this._motionBlurSamples;
  58840. },
  58841. set: function (samples) {
  58842. if (this.motionBlurPostProcess) {
  58843. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  58844. }
  58845. this._motionBlurSamples = samples;
  58846. },
  58847. enumerable: true,
  58848. configurable: true
  58849. });
  58850. StandardRenderingPipeline.prototype._buildPipeline = function () {
  58851. var _this = this;
  58852. var ratio = this._ratio;
  58853. var scene = this._scene;
  58854. this._disposePostProcesses();
  58855. this._reset();
  58856. // Create pass post-process
  58857. if (!this._basePostProcess) {
  58858. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  58859. this.originalPostProcess.onApply = function (effect) {
  58860. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  58861. };
  58862. }
  58863. else {
  58864. this.originalPostProcess = this._basePostProcess;
  58865. }
  58866. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  58867. this._currentDepthOfFieldSource = this.originalPostProcess;
  58868. if (this._vlsEnabled) {
  58869. // Create volumetric light
  58870. this._createVolumetricLightPostProcess(scene, ratio);
  58871. // Create volumetric light final post-process
  58872. 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);
  58873. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  58874. }
  58875. if (this._bloomEnabled) {
  58876. // Create down sample X4 post-process
  58877. this._createDownSampleX4PostProcess(scene, ratio / 2);
  58878. // Create bright pass post-process
  58879. this._createBrightPassPostProcess(scene, ratio / 2);
  58880. // Create gaussian blur post-processes (down sampling blurs)
  58881. this._createBlurPostProcesses(scene, ratio / 4, 1);
  58882. // Create texture adder post-process
  58883. this._createTextureAdderPostProcess(scene, ratio);
  58884. // Create depth-of-field source post-process
  58885. 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);
  58886. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  58887. }
  58888. if (this._lensFlareEnabled) {
  58889. // Create lens flare post-process
  58890. this._createLensFlarePostProcess(scene, ratio);
  58891. // Create depth-of-field source post-process post lens-flare and disable it now
  58892. 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);
  58893. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  58894. }
  58895. if (this._hdrEnabled) {
  58896. // Create luminance
  58897. this._createLuminancePostProcesses(scene, this._floatTextureType);
  58898. // Create HDR
  58899. this._createHdrPostProcess(scene, ratio);
  58900. // Create depth-of-field source post-process post hdr and disable it now
  58901. 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);
  58902. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  58903. }
  58904. if (this._depthOfFieldEnabled) {
  58905. // Create gaussian blur used by depth-of-field
  58906. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  58907. // Create depth-of-field post-process
  58908. this._createDepthOfFieldPostProcess(scene, ratio);
  58909. }
  58910. if (this._motionBlurEnabled) {
  58911. // Create motion blur post-process
  58912. this._createMotionBlurPostProcess(scene, ratio);
  58913. }
  58914. if (this._cameras !== null) {
  58915. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58916. }
  58917. };
  58918. // Down Sample X4 Post-Processs
  58919. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  58920. var _this = this;
  58921. var downSampleX4Offsets = new Array(32);
  58922. 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);
  58923. this.downSampleX4PostProcess.onApply = function (effect) {
  58924. var id = 0;
  58925. var width = _this.downSampleX4PostProcess.width;
  58926. var height = _this.downSampleX4PostProcess.height;
  58927. for (var i = -2; i < 2; i++) {
  58928. for (var j = -2; j < 2; j++) {
  58929. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  58930. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  58931. id += 2;
  58932. }
  58933. }
  58934. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58935. };
  58936. // Add to pipeline
  58937. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58938. };
  58939. // Brightpass Post-Process
  58940. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58941. var _this = this;
  58942. var brightOffsets = new Array(8);
  58943. 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);
  58944. this.brightPassPostProcess.onApply = function (effect) {
  58945. var sU = (1.0 / _this.brightPassPostProcess.width);
  58946. var sV = (1.0 / _this.brightPassPostProcess.height);
  58947. brightOffsets[0] = -0.5 * sU;
  58948. brightOffsets[1] = 0.5 * sV;
  58949. brightOffsets[2] = 0.5 * sU;
  58950. brightOffsets[3] = 0.5 * sV;
  58951. brightOffsets[4] = -0.5 * sU;
  58952. brightOffsets[5] = -0.5 * sV;
  58953. brightOffsets[6] = 0.5 * sU;
  58954. brightOffsets[7] = -0.5 * sV;
  58955. effect.setArray2("dsOffsets", brightOffsets);
  58956. effect.setFloat("brightThreshold", _this.brightThreshold);
  58957. };
  58958. // Add to pipeline
  58959. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  58960. };
  58961. // Create blur H&V post-processes
  58962. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  58963. var _this = this;
  58964. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  58965. var engine = scene.getEngine();
  58966. 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);
  58967. 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);
  58968. blurX.onActivateObservable.add(function () {
  58969. var dw = blurX.width / engine.getRenderWidth();
  58970. blurX.kernel = _this[blurWidthKey] * dw;
  58971. });
  58972. blurY.onActivateObservable.add(function () {
  58973. var dw = blurY.height / engine.getRenderHeight();
  58974. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  58975. });
  58976. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  58977. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  58978. this.blurHPostProcesses.push(blurX);
  58979. this.blurVPostProcesses.push(blurY);
  58980. };
  58981. // Create texture adder post-process
  58982. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  58983. var _this = this;
  58984. 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);
  58985. this.textureAdderPostProcess.onApply = function (effect) {
  58986. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  58987. effect.setTexture("lensSampler", _this.lensTexture);
  58988. effect.setFloat("exposure", _this.exposure);
  58989. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  58990. };
  58991. // Add to pipeline
  58992. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  58993. };
  58994. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  58995. var _this = this;
  58996. var geometryRenderer = scene.enableGeometryBufferRenderer();
  58997. geometryRenderer.enablePosition = true;
  58998. var geometry = geometryRenderer.getGBuffer();
  58999. // Base post-process
  59000. 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));
  59001. var depthValues = BABYLON.Vector2.Zero();
  59002. this.volumetricLightPostProcess.onApply = function (effect) {
  59003. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  59004. var generator = _this.sourceLight.getShadowGenerator();
  59005. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  59006. effect.setTexture("positionSampler", geometry.textures[2]);
  59007. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  59008. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  59009. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  59010. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  59011. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  59012. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  59013. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  59014. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  59015. effect.setVector2("depthValues", depthValues);
  59016. }
  59017. };
  59018. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  59019. // Smooth
  59020. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  59021. // Merge
  59022. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  59023. this.volumetricLightMergePostProces.onApply = function (effect) {
  59024. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  59025. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  59026. };
  59027. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  59028. };
  59029. // Create luminance
  59030. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  59031. var _this = this;
  59032. // Create luminance
  59033. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  59034. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  59035. var offsets = [];
  59036. this.luminancePostProcess.onApply = function (effect) {
  59037. var sU = (1.0 / _this.luminancePostProcess.width);
  59038. var sV = (1.0 / _this.luminancePostProcess.height);
  59039. offsets[0] = -0.5 * sU;
  59040. offsets[1] = 0.5 * sV;
  59041. offsets[2] = 0.5 * sU;
  59042. offsets[3] = 0.5 * sV;
  59043. offsets[4] = -0.5 * sU;
  59044. offsets[5] = -0.5 * sV;
  59045. offsets[6] = 0.5 * sU;
  59046. offsets[7] = -0.5 * sV;
  59047. effect.setArray2("lumOffsets", offsets);
  59048. };
  59049. // Add to pipeline
  59050. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  59051. // Create down sample luminance
  59052. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  59053. var size = Math.pow(3, i);
  59054. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  59055. if (i === 0) {
  59056. defines += "#define FINAL_DOWN_SAMPLER";
  59057. }
  59058. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  59059. this.luminanceDownSamplePostProcesses.push(postProcess);
  59060. }
  59061. // Create callbacks and add effects
  59062. var lastLuminance = this.luminancePostProcess;
  59063. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  59064. var downSampleOffsets = new Array(18);
  59065. pp.onApply = function (effect) {
  59066. if (!lastLuminance) {
  59067. return;
  59068. }
  59069. var id = 0;
  59070. for (var x = -1; x < 2; x++) {
  59071. for (var y = -1; y < 2; y++) {
  59072. downSampleOffsets[id] = x / lastLuminance.width;
  59073. downSampleOffsets[id + 1] = y / lastLuminance.height;
  59074. id += 2;
  59075. }
  59076. }
  59077. effect.setArray2("dsOffsets", downSampleOffsets);
  59078. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  59079. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59080. lastLuminance = _this.luminancePostProcess;
  59081. }
  59082. else {
  59083. lastLuminance = pp;
  59084. }
  59085. };
  59086. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  59087. pp.onAfterRender = function (effect) {
  59088. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  59089. 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);
  59090. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  59091. };
  59092. }
  59093. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  59094. });
  59095. };
  59096. // Create HDR post-process
  59097. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  59098. var _this = this;
  59099. 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);
  59100. var outputLiminance = 1;
  59101. var time = 0;
  59102. var lastTime = 0;
  59103. this.hdrPostProcess.onApply = function (effect) {
  59104. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  59105. time += scene.getEngine().getDeltaTime();
  59106. if (outputLiminance < 0) {
  59107. outputLiminance = _this._hdrCurrentLuminance;
  59108. }
  59109. else {
  59110. var dt = (lastTime - time) / 1000.0;
  59111. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  59112. outputLiminance += _this.hdrDecreaseRate * dt;
  59113. }
  59114. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  59115. outputLiminance -= _this.hdrIncreaseRate * dt;
  59116. }
  59117. else {
  59118. outputLiminance = _this._hdrCurrentLuminance;
  59119. }
  59120. }
  59121. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  59122. effect.setFloat("averageLuminance", outputLiminance);
  59123. lastTime = time;
  59124. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  59125. };
  59126. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  59127. };
  59128. // Create lens flare post-process
  59129. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  59130. var _this = this;
  59131. 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);
  59132. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  59133. this._createBlurPostProcesses(scene, ratio / 4, 2);
  59134. 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);
  59135. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  59136. var resolution = new BABYLON.Vector2(0, 0);
  59137. // Lens flare
  59138. this.lensFlarePostProcess.onApply = function (effect) {
  59139. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  59140. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  59141. effect.setFloat("strength", _this.lensFlareStrength);
  59142. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  59143. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  59144. // Shift
  59145. resolution.x = _this.lensFlarePostProcess.width;
  59146. resolution.y = _this.lensFlarePostProcess.height;
  59147. effect.setVector2("resolution", resolution);
  59148. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  59149. };
  59150. // Compose
  59151. 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);
  59152. 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);
  59153. this.lensFlareComposePostProcess.onApply = function (effect) {
  59154. if (!_this._scene.activeCamera) {
  59155. return;
  59156. }
  59157. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59158. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  59159. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  59160. // Lens start rotation matrix
  59161. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  59162. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  59163. 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));
  59164. camRot *= 4.0;
  59165. 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);
  59166. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  59167. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  59168. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  59169. };
  59170. };
  59171. // Create depth-of-field post-process
  59172. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  59173. var _this = this;
  59174. 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);
  59175. this.depthOfFieldPostProcess.onApply = function (effect) {
  59176. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  59177. effect.setTexture("depthSampler", _this._getDepthTexture());
  59178. effect.setFloat("distance", _this.depthOfFieldDistance);
  59179. };
  59180. // Add to pipeline
  59181. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  59182. };
  59183. // Create motion blur post-process
  59184. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  59185. var _this = this;
  59186. 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);
  59187. var motionScale = 0;
  59188. var prevViewProjection = BABYLON.Matrix.Identity();
  59189. var invViewProjection = BABYLON.Matrix.Identity();
  59190. var viewProjection = BABYLON.Matrix.Identity();
  59191. var screenSize = BABYLON.Vector2.Zero();
  59192. this.motionBlurPostProcess.onApply = function (effect) {
  59193. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  59194. viewProjection.invertToRef(invViewProjection);
  59195. effect.setMatrix("inverseViewProjection", invViewProjection);
  59196. effect.setMatrix("prevViewProjection", prevViewProjection);
  59197. prevViewProjection = viewProjection;
  59198. screenSize.x = _this.motionBlurPostProcess.width;
  59199. screenSize.y = _this.motionBlurPostProcess.height;
  59200. effect.setVector2("screenSize", screenSize);
  59201. motionScale = scene.getEngine().getFps() / 60.0;
  59202. effect.setFloat("motionScale", motionScale);
  59203. effect.setFloat("motionStrength", _this.motionStrength);
  59204. effect.setTexture("depthSampler", _this._getDepthTexture());
  59205. };
  59206. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  59207. };
  59208. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  59209. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  59210. var renderer = this._scene.enableGeometryBufferRenderer();
  59211. return renderer.getGBuffer().textures[0];
  59212. }
  59213. return this._scene.enableDepthRenderer().getDepthMap();
  59214. };
  59215. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  59216. for (var i = 0; i < this._cameras.length; i++) {
  59217. var camera = this._cameras[i];
  59218. if (this.originalPostProcess) {
  59219. this.originalPostProcess.dispose(camera);
  59220. }
  59221. if (this.downSampleX4PostProcess) {
  59222. this.downSampleX4PostProcess.dispose(camera);
  59223. }
  59224. if (this.brightPassPostProcess) {
  59225. this.brightPassPostProcess.dispose(camera);
  59226. }
  59227. if (this.textureAdderPostProcess) {
  59228. this.textureAdderPostProcess.dispose(camera);
  59229. }
  59230. if (this.textureAdderFinalPostProcess) {
  59231. this.textureAdderFinalPostProcess.dispose(camera);
  59232. }
  59233. if (this.volumetricLightPostProcess) {
  59234. this.volumetricLightPostProcess.dispose(camera);
  59235. }
  59236. if (this.volumetricLightSmoothXPostProcess) {
  59237. this.volumetricLightSmoothXPostProcess.dispose(camera);
  59238. }
  59239. if (this.volumetricLightSmoothYPostProcess) {
  59240. this.volumetricLightSmoothYPostProcess.dispose(camera);
  59241. }
  59242. if (this.volumetricLightMergePostProces) {
  59243. this.volumetricLightMergePostProces.dispose(camera);
  59244. }
  59245. if (this.volumetricLightFinalPostProcess) {
  59246. this.volumetricLightFinalPostProcess.dispose(camera);
  59247. }
  59248. if (this.lensFlarePostProcess) {
  59249. this.lensFlarePostProcess.dispose(camera);
  59250. }
  59251. if (this.lensFlareComposePostProcess) {
  59252. this.lensFlareComposePostProcess.dispose(camera);
  59253. }
  59254. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  59255. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  59256. }
  59257. if (this.luminancePostProcess) {
  59258. this.luminancePostProcess.dispose(camera);
  59259. }
  59260. if (this.hdrPostProcess) {
  59261. this.hdrPostProcess.dispose(camera);
  59262. }
  59263. if (this.hdrFinalPostProcess) {
  59264. this.hdrFinalPostProcess.dispose(camera);
  59265. }
  59266. if (this.depthOfFieldPostProcess) {
  59267. this.depthOfFieldPostProcess.dispose(camera);
  59268. }
  59269. if (this.motionBlurPostProcess) {
  59270. this.motionBlurPostProcess.dispose(camera);
  59271. }
  59272. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  59273. this.blurHPostProcesses[j].dispose(camera);
  59274. }
  59275. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  59276. this.blurVPostProcesses[j].dispose(camera);
  59277. }
  59278. }
  59279. this.originalPostProcess = null;
  59280. this.downSampleX4PostProcess = null;
  59281. this.brightPassPostProcess = null;
  59282. this.textureAdderPostProcess = null;
  59283. this.textureAdderFinalPostProcess = null;
  59284. this.volumetricLightPostProcess = null;
  59285. this.volumetricLightSmoothXPostProcess = null;
  59286. this.volumetricLightSmoothYPostProcess = null;
  59287. this.volumetricLightMergePostProces = null;
  59288. this.volumetricLightFinalPostProcess = null;
  59289. this.lensFlarePostProcess = null;
  59290. this.lensFlareComposePostProcess = null;
  59291. this.luminancePostProcess = null;
  59292. this.hdrPostProcess = null;
  59293. this.hdrFinalPostProcess = null;
  59294. this.depthOfFieldPostProcess = null;
  59295. this.motionBlurPostProcess = null;
  59296. this.luminanceDownSamplePostProcesses = [];
  59297. this.blurHPostProcesses = [];
  59298. this.blurVPostProcesses = [];
  59299. };
  59300. // Dispose
  59301. StandardRenderingPipeline.prototype.dispose = function () {
  59302. this._disposePostProcesses();
  59303. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59304. _super.prototype.dispose.call(this);
  59305. };
  59306. // Serialize rendering pipeline
  59307. StandardRenderingPipeline.prototype.serialize = function () {
  59308. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59309. serializationObject.customType = "StandardRenderingPipeline";
  59310. return serializationObject;
  59311. };
  59312. /**
  59313. * Static members
  59314. */
  59315. // Parse serialized pipeline
  59316. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59317. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  59318. };
  59319. // Luminance steps
  59320. StandardRenderingPipeline.LuminanceSteps = 6;
  59321. __decorate([
  59322. BABYLON.serialize()
  59323. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  59324. __decorate([
  59325. BABYLON.serialize()
  59326. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  59327. __decorate([
  59328. BABYLON.serialize()
  59329. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  59330. __decorate([
  59331. BABYLON.serialize()
  59332. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  59333. __decorate([
  59334. BABYLON.serializeAsTexture("lensTexture")
  59335. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  59336. __decorate([
  59337. BABYLON.serialize()
  59338. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  59339. __decorate([
  59340. BABYLON.serialize()
  59341. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  59342. __decorate([
  59343. BABYLON.serialize()
  59344. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  59345. __decorate([
  59346. BABYLON.serialize()
  59347. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  59348. __decorate([
  59349. BABYLON.serialize()
  59350. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  59351. __decorate([
  59352. BABYLON.serialize()
  59353. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  59354. __decorate([
  59355. BABYLON.serializeAsTexture("lensColorTexture")
  59356. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  59357. __decorate([
  59358. BABYLON.serialize()
  59359. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  59360. __decorate([
  59361. BABYLON.serialize()
  59362. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  59363. __decorate([
  59364. BABYLON.serialize()
  59365. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  59366. __decorate([
  59367. BABYLON.serialize()
  59368. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  59369. __decorate([
  59370. BABYLON.serializeAsTexture("lensStarTexture")
  59371. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  59372. __decorate([
  59373. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  59374. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  59375. __decorate([
  59376. BABYLON.serialize()
  59377. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  59378. __decorate([
  59379. BABYLON.serialize()
  59380. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  59381. __decorate([
  59382. BABYLON.serialize()
  59383. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  59384. __decorate([
  59385. BABYLON.serialize()
  59386. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  59387. __decorate([
  59388. BABYLON.serialize()
  59389. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  59390. __decorate([
  59391. BABYLON.serialize()
  59392. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  59393. __decorate([
  59394. BABYLON.serialize()
  59395. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  59396. __decorate([
  59397. BABYLON.serialize()
  59398. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  59399. __decorate([
  59400. BABYLON.serialize()
  59401. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  59402. __decorate([
  59403. BABYLON.serialize()
  59404. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  59405. __decorate([
  59406. BABYLON.serialize()
  59407. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  59408. return StandardRenderingPipeline;
  59409. }(BABYLON.PostProcessRenderPipeline));
  59410. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  59411. })(BABYLON || (BABYLON = {}));
  59412. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  59413. var BABYLON;
  59414. (function (BABYLON) {
  59415. var FxaaPostProcess = /** @class */ (function (_super) {
  59416. __extends(FxaaPostProcess, _super);
  59417. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59418. if (camera === void 0) { camera = null; }
  59419. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59420. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  59421. _this.onApplyObservable.add(function (effect) {
  59422. var texelSize = _this.texelSize;
  59423. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  59424. });
  59425. return _this;
  59426. }
  59427. return FxaaPostProcess;
  59428. }(BABYLON.PostProcess));
  59429. BABYLON.FxaaPostProcess = FxaaPostProcess;
  59430. })(BABYLON || (BABYLON = {}));
  59431. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  59432. var BABYLON;
  59433. (function (BABYLON) {
  59434. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  59435. __extends(DefaultRenderingPipeline, _super);
  59436. /**
  59437. * @constructor
  59438. * @param {string} name - The rendering pipeline name
  59439. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59440. * @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)
  59441. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59442. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  59443. */
  59444. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  59445. if (automaticBuild === void 0) { automaticBuild = true; }
  59446. var _this = _super.call(this, scene.getEngine(), name) || this;
  59447. _this.PassPostProcessId = "PassPostProcessEffect";
  59448. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  59449. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  59450. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  59451. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  59452. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  59453. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  59454. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  59455. // IAnimatable
  59456. _this.animations = [];
  59457. // Values
  59458. _this._bloomEnabled = false;
  59459. _this._fxaaEnabled = false;
  59460. _this._imageProcessingEnabled = true;
  59461. _this._bloomScale = 0.6;
  59462. _this._buildAllowed = true;
  59463. /**
  59464. * Specifies the size of the bloom blur kernel, relative to the final output size
  59465. */
  59466. _this.bloomKernel = 64;
  59467. /**
  59468. * Specifies the weight of the bloom in the final rendering
  59469. */
  59470. _this._bloomWeight = 0.15;
  59471. _this._cameras = cameras || [];
  59472. _this._buildAllowed = automaticBuild;
  59473. // Initialize
  59474. _this._scene = scene;
  59475. var caps = _this._scene.getEngine().getCaps();
  59476. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  59477. // Misc
  59478. if (_this._hdr) {
  59479. if (caps.textureHalfFloatRender) {
  59480. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59481. }
  59482. else if (caps.textureFloatRender) {
  59483. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59484. }
  59485. }
  59486. else {
  59487. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59488. }
  59489. // Attach
  59490. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59491. _this._buildPipeline();
  59492. return _this;
  59493. }
  59494. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  59495. get: function () {
  59496. return this._bloomWeight;
  59497. },
  59498. set: function (value) {
  59499. if (this._bloomWeight === value) {
  59500. return;
  59501. }
  59502. this._bloomWeight = value;
  59503. if (this._hdr && this.copyBack) {
  59504. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  59505. }
  59506. },
  59507. enumerable: true,
  59508. configurable: true
  59509. });
  59510. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  59511. get: function () {
  59512. return this._bloomScale;
  59513. },
  59514. set: function (value) {
  59515. if (this._bloomScale === value) {
  59516. return;
  59517. }
  59518. this._bloomScale = value;
  59519. this._buildPipeline();
  59520. },
  59521. enumerable: true,
  59522. configurable: true
  59523. });
  59524. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  59525. get: function () {
  59526. return this._bloomEnabled;
  59527. },
  59528. set: function (enabled) {
  59529. if (this._bloomEnabled === enabled) {
  59530. return;
  59531. }
  59532. this._bloomEnabled = enabled;
  59533. this._buildPipeline();
  59534. },
  59535. enumerable: true,
  59536. configurable: true
  59537. });
  59538. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  59539. get: function () {
  59540. return this._fxaaEnabled;
  59541. },
  59542. set: function (enabled) {
  59543. if (this._fxaaEnabled === enabled) {
  59544. return;
  59545. }
  59546. this._fxaaEnabled = enabled;
  59547. this._buildPipeline();
  59548. },
  59549. enumerable: true,
  59550. configurable: true
  59551. });
  59552. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  59553. get: function () {
  59554. return this._imageProcessingEnabled;
  59555. },
  59556. set: function (enabled) {
  59557. if (this._imageProcessingEnabled === enabled) {
  59558. return;
  59559. }
  59560. this._imageProcessingEnabled = enabled;
  59561. this._buildPipeline();
  59562. },
  59563. enumerable: true,
  59564. configurable: true
  59565. });
  59566. /**
  59567. * Force the compilation of the entire pipeline.
  59568. */
  59569. DefaultRenderingPipeline.prototype.prepare = function () {
  59570. var previousState = this._buildAllowed;
  59571. this._buildAllowed = true;
  59572. this._buildPipeline();
  59573. this._buildAllowed = previousState;
  59574. };
  59575. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  59576. var _this = this;
  59577. if (!this._buildAllowed) {
  59578. return;
  59579. }
  59580. var engine = this._scene.getEngine();
  59581. this._disposePostProcesses();
  59582. this._reset();
  59583. if (this.bloomEnabled) {
  59584. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59585. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  59586. if (!this._hdr) {
  59587. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59588. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  59589. this.highlights.autoClear = false;
  59590. this.highlights.alwaysForcePOT = true;
  59591. }
  59592. 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);
  59593. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  59594. this.blurX.alwaysForcePOT = true;
  59595. this.blurX.autoClear = false;
  59596. this.blurX.onActivateObservable.add(function () {
  59597. var dw = _this.blurX.width / engine.getRenderWidth(true);
  59598. _this.blurX.kernel = _this.bloomKernel * dw;
  59599. });
  59600. 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);
  59601. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  59602. this.blurY.alwaysForcePOT = true;
  59603. this.blurY.autoClear = false;
  59604. this.blurY.onActivateObservable.add(function () {
  59605. var dh = _this.blurY.height / engine.getRenderHeight(true);
  59606. _this.blurY.kernel = _this.bloomKernel * dh;
  59607. });
  59608. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59609. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  59610. this.copyBack.alwaysForcePOT = true;
  59611. if (this._hdr) {
  59612. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  59613. var w = this.bloomWeight;
  59614. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  59615. }
  59616. else {
  59617. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  59618. }
  59619. this.copyBack.autoClear = false;
  59620. }
  59621. if (this._imageProcessingEnabled) {
  59622. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59623. if (this._hdr) {
  59624. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  59625. }
  59626. else {
  59627. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  59628. }
  59629. }
  59630. if (this.fxaaEnabled) {
  59631. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59632. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  59633. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59634. }
  59635. else {
  59636. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59637. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  59638. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59639. }
  59640. if (this.bloomEnabled) {
  59641. if (this._hdr) {
  59642. this.copyBack.shareOutputWith(this.blurX);
  59643. if (this.imageProcessing) {
  59644. this.imageProcessing.shareOutputWith(this.pass);
  59645. this.imageProcessing.autoClear = false;
  59646. }
  59647. else if (this.fxaa) {
  59648. this.fxaa.shareOutputWith(this.pass);
  59649. }
  59650. else {
  59651. this.finalMerge.shareOutputWith(this.pass);
  59652. }
  59653. }
  59654. else {
  59655. if (this.fxaa) {
  59656. this.fxaa.shareOutputWith(this.pass);
  59657. }
  59658. else {
  59659. this.finalMerge.shareOutputWith(this.pass);
  59660. }
  59661. }
  59662. }
  59663. if (this._cameras !== null) {
  59664. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59665. }
  59666. };
  59667. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  59668. for (var i = 0; i < this._cameras.length; i++) {
  59669. var camera = this._cameras[i];
  59670. if (this.pass) {
  59671. this.pass.dispose(camera);
  59672. }
  59673. if (this.highlights) {
  59674. this.highlights.dispose(camera);
  59675. }
  59676. if (this.blurX) {
  59677. this.blurX.dispose(camera);
  59678. }
  59679. if (this.blurY) {
  59680. this.blurY.dispose(camera);
  59681. }
  59682. if (this.copyBack) {
  59683. this.copyBack.dispose(camera);
  59684. }
  59685. if (this.imageProcessing) {
  59686. this.imageProcessing.dispose(camera);
  59687. }
  59688. if (this.fxaa) {
  59689. this.fxaa.dispose(camera);
  59690. }
  59691. if (this.finalMerge) {
  59692. this.finalMerge.dispose(camera);
  59693. }
  59694. }
  59695. this.pass = null;
  59696. this.highlights = null;
  59697. this.blurX = null;
  59698. this.blurY = null;
  59699. this.copyBack = null;
  59700. this.imageProcessing = null;
  59701. this.fxaa = null;
  59702. this.finalMerge = null;
  59703. };
  59704. // Dispose
  59705. DefaultRenderingPipeline.prototype.dispose = function () {
  59706. this._disposePostProcesses();
  59707. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59708. _super.prototype.dispose.call(this);
  59709. };
  59710. // Serialize rendering pipeline
  59711. DefaultRenderingPipeline.prototype.serialize = function () {
  59712. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59713. serializationObject.customType = "DefaultRenderingPipeline";
  59714. return serializationObject;
  59715. };
  59716. // Parse serialized pipeline
  59717. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59718. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  59719. };
  59720. __decorate([
  59721. BABYLON.serialize()
  59722. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  59723. __decorate([
  59724. BABYLON.serialize()
  59725. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  59726. __decorate([
  59727. BABYLON.serialize()
  59728. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  59729. __decorate([
  59730. BABYLON.serialize()
  59731. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  59732. __decorate([
  59733. BABYLON.serialize()
  59734. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  59735. __decorate([
  59736. BABYLON.serialize()
  59737. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  59738. __decorate([
  59739. BABYLON.serialize()
  59740. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  59741. __decorate([
  59742. BABYLON.serialize()
  59743. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  59744. return DefaultRenderingPipeline;
  59745. }(BABYLON.PostProcessRenderPipeline));
  59746. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  59747. })(BABYLON || (BABYLON = {}));
  59748. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  59749. var BABYLON;
  59750. (function (BABYLON) {
  59751. var GeometryBufferRenderer = /** @class */ (function () {
  59752. function GeometryBufferRenderer(scene, ratio) {
  59753. if (ratio === void 0) { ratio = 1; }
  59754. this._enablePosition = false;
  59755. this._scene = scene;
  59756. this._ratio = ratio;
  59757. // Render target
  59758. this._createRenderTargets();
  59759. }
  59760. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  59761. set: function (meshes) {
  59762. this._multiRenderTarget.renderList = meshes;
  59763. },
  59764. enumerable: true,
  59765. configurable: true
  59766. });
  59767. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  59768. get: function () {
  59769. return this._multiRenderTarget.isSupported;
  59770. },
  59771. enumerable: true,
  59772. configurable: true
  59773. });
  59774. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  59775. get: function () {
  59776. return this._enablePosition;
  59777. },
  59778. set: function (enable) {
  59779. this._enablePosition = enable;
  59780. this.dispose();
  59781. this._createRenderTargets();
  59782. },
  59783. enumerable: true,
  59784. configurable: true
  59785. });
  59786. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  59787. var material = subMesh.getMaterial();
  59788. if (material && material.disableDepthWrite) {
  59789. return false;
  59790. }
  59791. var defines = [];
  59792. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  59793. var mesh = subMesh.getMesh();
  59794. // Alpha test
  59795. if (material && material.needAlphaTesting()) {
  59796. defines.push("#define ALPHATEST");
  59797. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59798. attribs.push(BABYLON.VertexBuffer.UVKind);
  59799. defines.push("#define UV1");
  59800. }
  59801. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59802. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59803. defines.push("#define UV2");
  59804. }
  59805. }
  59806. // Buffers
  59807. if (this._enablePosition) {
  59808. defines.push("#define POSITION");
  59809. }
  59810. // Bones
  59811. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59812. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59813. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59814. if (mesh.numBoneInfluencers > 4) {
  59815. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59816. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59817. }
  59818. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59819. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59820. }
  59821. else {
  59822. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59823. }
  59824. // Instances
  59825. if (useInstances) {
  59826. defines.push("#define INSTANCES");
  59827. attribs.push("world0");
  59828. attribs.push("world1");
  59829. attribs.push("world2");
  59830. attribs.push("world3");
  59831. }
  59832. // Get correct effect
  59833. var join = defines.join("\n");
  59834. if (this._cachedDefines !== join) {
  59835. this._cachedDefines = join;
  59836. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  59837. }
  59838. return this._effect.isReady();
  59839. };
  59840. GeometryBufferRenderer.prototype.getGBuffer = function () {
  59841. return this._multiRenderTarget;
  59842. };
  59843. // Methods
  59844. GeometryBufferRenderer.prototype.dispose = function () {
  59845. this.getGBuffer().dispose();
  59846. };
  59847. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  59848. var _this = this;
  59849. var engine = this._scene.getEngine();
  59850. var count = this._enablePosition ? 3 : 2;
  59851. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  59852. if (!this.isSupported) {
  59853. return;
  59854. }
  59855. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59856. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59857. this._multiRenderTarget.refreshRate = 1;
  59858. this._multiRenderTarget.renderParticles = false;
  59859. this._multiRenderTarget.renderList = null;
  59860. // set default depth value to 1.0 (far away)
  59861. this._multiRenderTarget.onClearObservable.add(function (engine) {
  59862. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  59863. });
  59864. // Custom render function
  59865. var renderSubMesh = function (subMesh) {
  59866. var mesh = subMesh.getRenderingMesh();
  59867. var scene = _this._scene;
  59868. var engine = scene.getEngine();
  59869. var material = subMesh.getMaterial();
  59870. if (!material) {
  59871. return;
  59872. }
  59873. // Culling
  59874. engine.setState(material.backFaceCulling);
  59875. // Managing instances
  59876. var batch = mesh._getInstancesRenderList(subMesh._id);
  59877. if (batch.mustReturn) {
  59878. return;
  59879. }
  59880. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59881. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59882. engine.enableEffect(_this._effect);
  59883. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59884. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59885. _this._effect.setMatrix("view", scene.getViewMatrix());
  59886. // Alpha test
  59887. if (material && material.needAlphaTesting()) {
  59888. var alphaTexture = material.getAlphaTestTexture();
  59889. if (alphaTexture) {
  59890. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59891. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59892. }
  59893. }
  59894. // Bones
  59895. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59896. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59897. }
  59898. // Draw
  59899. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59900. }
  59901. };
  59902. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59903. var index;
  59904. if (depthOnlySubMeshes.length) {
  59905. engine.setColorWrite(false);
  59906. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59907. renderSubMesh(depthOnlySubMeshes.data[index]);
  59908. }
  59909. engine.setColorWrite(true);
  59910. }
  59911. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59912. renderSubMesh(opaqueSubMeshes.data[index]);
  59913. }
  59914. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59915. renderSubMesh(alphaTestSubMeshes.data[index]);
  59916. }
  59917. };
  59918. };
  59919. return GeometryBufferRenderer;
  59920. }());
  59921. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  59922. })(BABYLON || (BABYLON = {}));
  59923. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  59924. var BABYLON;
  59925. (function (BABYLON) {
  59926. var RefractionPostProcess = /** @class */ (function (_super) {
  59927. __extends(RefractionPostProcess, _super);
  59928. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  59929. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  59930. _this.color = color;
  59931. _this.depth = depth;
  59932. _this.colorLevel = colorLevel;
  59933. _this.onActivateObservable.add(function (cam) {
  59934. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  59935. });
  59936. _this.onApplyObservable.add(function (effect) {
  59937. effect.setColor3("baseColor", _this.color);
  59938. effect.setFloat("depth", _this.depth);
  59939. effect.setFloat("colorLevel", _this.colorLevel);
  59940. effect.setTexture("refractionSampler", _this._refRexture);
  59941. });
  59942. return _this;
  59943. }
  59944. // Methods
  59945. RefractionPostProcess.prototype.dispose = function (camera) {
  59946. if (this._refRexture) {
  59947. this._refRexture.dispose();
  59948. }
  59949. _super.prototype.dispose.call(this, camera);
  59950. };
  59951. return RefractionPostProcess;
  59952. }(BABYLON.PostProcess));
  59953. BABYLON.RefractionPostProcess = RefractionPostProcess;
  59954. })(BABYLON || (BABYLON = {}));
  59955. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  59956. var BABYLON;
  59957. (function (BABYLON) {
  59958. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  59959. __extends(BlackAndWhitePostProcess, _super);
  59960. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  59961. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  59962. _this.degree = 1;
  59963. _this.onApplyObservable.add(function (effect) {
  59964. effect.setFloat("degree", _this.degree);
  59965. });
  59966. return _this;
  59967. }
  59968. return BlackAndWhitePostProcess;
  59969. }(BABYLON.PostProcess));
  59970. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  59971. })(BABYLON || (BABYLON = {}));
  59972. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  59973. var BABYLON;
  59974. (function (BABYLON) {
  59975. var ConvolutionPostProcess = /** @class */ (function (_super) {
  59976. __extends(ConvolutionPostProcess, _super);
  59977. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  59978. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  59979. _this.kernel = kernel;
  59980. _this.onApply = function (effect) {
  59981. effect.setFloat2("screenSize", _this.width, _this.height);
  59982. effect.setArray("kernel", _this.kernel);
  59983. };
  59984. return _this;
  59985. }
  59986. // Statics
  59987. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  59988. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  59989. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  59990. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  59991. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  59992. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  59993. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  59994. return ConvolutionPostProcess;
  59995. }(BABYLON.PostProcess));
  59996. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  59997. })(BABYLON || (BABYLON = {}));
  59998. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  59999. var BABYLON;
  60000. (function (BABYLON) {
  60001. var FilterPostProcess = /** @class */ (function (_super) {
  60002. __extends(FilterPostProcess, _super);
  60003. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  60004. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  60005. _this.kernelMatrix = kernelMatrix;
  60006. _this.onApply = function (effect) {
  60007. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  60008. };
  60009. return _this;
  60010. }
  60011. return FilterPostProcess;
  60012. }(BABYLON.PostProcess));
  60013. BABYLON.FilterPostProcess = FilterPostProcess;
  60014. })(BABYLON || (BABYLON = {}));
  60015. //# sourceMappingURL=babylon.filterPostProcess.js.map
  60016. var BABYLON;
  60017. (function (BABYLON) {
  60018. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  60019. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  60020. __extends(VolumetricLightScatteringPostProcess, _super);
  60021. /**
  60022. * @constructor
  60023. * @param {string} name - The post-process name
  60024. * @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)
  60025. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  60026. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  60027. * @param {number} samples - The post-process quality, default 100
  60028. * @param {number} samplingMode - The post-process filtering mode
  60029. * @param {BABYLON.Engine} engine - The babylon engine
  60030. * @param {boolean} reusable - If the post-process is reusable
  60031. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  60032. */
  60033. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  60034. if (samples === void 0) { samples = 100; }
  60035. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60036. 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;
  60037. _this._screenCoordinates = BABYLON.Vector2.Zero();
  60038. /**
  60039. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  60040. * @type {Vector3}
  60041. */
  60042. _this.customMeshPosition = BABYLON.Vector3.Zero();
  60043. /**
  60044. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  60045. * @type {boolean}
  60046. */
  60047. _this.useCustomMeshPosition = false;
  60048. /**
  60049. * If the post-process should inverse the light scattering direction
  60050. * @type {boolean}
  60051. */
  60052. _this.invert = true;
  60053. /**
  60054. * Array containing the excluded meshes not rendered in the internal pass
  60055. */
  60056. _this.excludedMeshes = new Array();
  60057. /**
  60058. * Controls the overall intensity of the post-process
  60059. * @type {number}
  60060. */
  60061. _this.exposure = 0.3;
  60062. /**
  60063. * Dissipates each sample's contribution in range [0, 1]
  60064. * @type {number}
  60065. */
  60066. _this.decay = 0.96815;
  60067. /**
  60068. * Controls the overall intensity of each sample
  60069. * @type {number}
  60070. */
  60071. _this.weight = 0.58767;
  60072. /**
  60073. * Controls the density of each sample
  60074. * @type {number}
  60075. */
  60076. _this.density = 0.926;
  60077. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  60078. engine = scene.getEngine();
  60079. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  60080. // Configure mesh
  60081. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  60082. // Configure
  60083. _this._createPass(scene, ratio.passRatio || ratio);
  60084. _this.onActivate = function (camera) {
  60085. if (!_this.isSupported) {
  60086. _this.dispose(camera);
  60087. }
  60088. _this.onActivate = null;
  60089. };
  60090. _this.onApplyObservable.add(function (effect) {
  60091. _this._updateMeshScreenCoordinates(scene);
  60092. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  60093. effect.setFloat("exposure", _this.exposure);
  60094. effect.setFloat("decay", _this.decay);
  60095. effect.setFloat("weight", _this.weight);
  60096. effect.setFloat("density", _this.density);
  60097. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  60098. });
  60099. return _this;
  60100. }
  60101. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  60102. get: function () {
  60103. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60104. return false;
  60105. },
  60106. set: function (useDiffuseColor) {
  60107. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  60108. },
  60109. enumerable: true,
  60110. configurable: true
  60111. });
  60112. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  60113. return "VolumetricLightScatteringPostProcess";
  60114. };
  60115. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  60116. var mesh = subMesh.getMesh();
  60117. // Render this.mesh as default
  60118. if (mesh === this.mesh && mesh.material) {
  60119. return mesh.material.isReady(mesh);
  60120. }
  60121. var defines = [];
  60122. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60123. var material = subMesh.getMaterial();
  60124. // Alpha test
  60125. if (material) {
  60126. if (material.needAlphaTesting()) {
  60127. defines.push("#define ALPHATEST");
  60128. }
  60129. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60130. attribs.push(BABYLON.VertexBuffer.UVKind);
  60131. defines.push("#define UV1");
  60132. }
  60133. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60134. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60135. defines.push("#define UV2");
  60136. }
  60137. }
  60138. // Bones
  60139. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60140. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60141. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60142. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60143. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  60144. }
  60145. else {
  60146. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60147. }
  60148. // Instances
  60149. if (useInstances) {
  60150. defines.push("#define INSTANCES");
  60151. attribs.push("world0");
  60152. attribs.push("world1");
  60153. attribs.push("world2");
  60154. attribs.push("world3");
  60155. }
  60156. // Get correct effect
  60157. var join = defines.join("\n");
  60158. if (this._cachedDefines !== join) {
  60159. this._cachedDefines = join;
  60160. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  60161. }
  60162. return this._volumetricLightScatteringPass.isReady();
  60163. };
  60164. /**
  60165. * Sets the new light position for light scattering effect
  60166. * @param {BABYLON.Vector3} The new custom light position
  60167. */
  60168. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  60169. this.customMeshPosition = position;
  60170. };
  60171. /**
  60172. * Returns the light position for light scattering effect
  60173. * @return {BABYLON.Vector3} The custom light position
  60174. */
  60175. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  60176. return this.customMeshPosition;
  60177. };
  60178. /**
  60179. * Disposes the internal assets and detaches the post-process from the camera
  60180. */
  60181. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  60182. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  60183. if (rttIndex !== -1) {
  60184. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  60185. }
  60186. this._volumetricLightScatteringRTT.dispose();
  60187. _super.prototype.dispose.call(this, camera);
  60188. };
  60189. /**
  60190. * Returns the render target texture used by the post-process
  60191. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  60192. */
  60193. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  60194. return this._volumetricLightScatteringRTT;
  60195. };
  60196. // Private methods
  60197. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  60198. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  60199. return true;
  60200. }
  60201. return false;
  60202. };
  60203. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  60204. var _this = this;
  60205. var engine = scene.getEngine();
  60206. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60207. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60208. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60209. this._volumetricLightScatteringRTT.renderList = null;
  60210. this._volumetricLightScatteringRTT.renderParticles = false;
  60211. var camera = this.getCamera();
  60212. if (camera) {
  60213. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60214. }
  60215. else {
  60216. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  60217. }
  60218. // Custom render function for submeshes
  60219. var renderSubMesh = function (subMesh) {
  60220. var mesh = subMesh.getRenderingMesh();
  60221. if (_this._meshExcluded(mesh)) {
  60222. return;
  60223. }
  60224. var material = subMesh.getMaterial();
  60225. if (!material) {
  60226. return;
  60227. }
  60228. var scene = mesh.getScene();
  60229. var engine = scene.getEngine();
  60230. // Culling
  60231. engine.setState(material.backFaceCulling);
  60232. // Managing instances
  60233. var batch = mesh._getInstancesRenderList(subMesh._id);
  60234. if (batch.mustReturn) {
  60235. return;
  60236. }
  60237. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  60238. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  60239. var effect = _this._volumetricLightScatteringPass;
  60240. if (mesh === _this.mesh) {
  60241. if (subMesh.effect) {
  60242. effect = subMesh.effect;
  60243. }
  60244. else {
  60245. effect = material.getEffect();
  60246. }
  60247. }
  60248. engine.enableEffect(effect);
  60249. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  60250. if (mesh === _this.mesh) {
  60251. material.bind(mesh.getWorldMatrix(), mesh);
  60252. }
  60253. else {
  60254. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  60255. // Alpha test
  60256. if (material && material.needAlphaTesting()) {
  60257. var alphaTexture = material.getAlphaTestTexture();
  60258. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  60259. if (alphaTexture) {
  60260. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60261. }
  60262. }
  60263. // Bones
  60264. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60265. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60266. }
  60267. }
  60268. // Draw
  60269. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  60270. }
  60271. };
  60272. // Render target texture callbacks
  60273. var savedSceneClearColor;
  60274. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  60275. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  60276. savedSceneClearColor = scene.clearColor;
  60277. scene.clearColor = sceneClearColor;
  60278. });
  60279. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  60280. scene.clearColor = savedSceneClearColor;
  60281. });
  60282. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60283. var engine = scene.getEngine();
  60284. var index;
  60285. if (depthOnlySubMeshes.length) {
  60286. engine.setColorWrite(false);
  60287. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60288. renderSubMesh(depthOnlySubMeshes.data[index]);
  60289. }
  60290. engine.setColorWrite(true);
  60291. }
  60292. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60293. renderSubMesh(opaqueSubMeshes.data[index]);
  60294. }
  60295. engine.setAlphaTesting(true);
  60296. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60297. renderSubMesh(alphaTestSubMeshes.data[index]);
  60298. }
  60299. engine.setAlphaTesting(false);
  60300. if (transparentSubMeshes.length) {
  60301. // Sort sub meshes
  60302. for (index = 0; index < transparentSubMeshes.length; index++) {
  60303. var submesh = transparentSubMeshes.data[index];
  60304. var boundingInfo = submesh.getBoundingInfo();
  60305. if (boundingInfo && scene.activeCamera) {
  60306. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  60307. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  60308. }
  60309. }
  60310. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  60311. sortedArray.sort(function (a, b) {
  60312. // Alpha index first
  60313. if (a._alphaIndex > b._alphaIndex) {
  60314. return 1;
  60315. }
  60316. if (a._alphaIndex < b._alphaIndex) {
  60317. return -1;
  60318. }
  60319. // Then distance to camera
  60320. if (a._distanceToCamera < b._distanceToCamera) {
  60321. return 1;
  60322. }
  60323. if (a._distanceToCamera > b._distanceToCamera) {
  60324. return -1;
  60325. }
  60326. return 0;
  60327. });
  60328. // Render sub meshes
  60329. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60330. for (index = 0; index < sortedArray.length; index++) {
  60331. renderSubMesh(sortedArray[index]);
  60332. }
  60333. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60334. }
  60335. };
  60336. };
  60337. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  60338. var transform = scene.getTransformMatrix();
  60339. var meshPosition;
  60340. if (this.useCustomMeshPosition) {
  60341. meshPosition = this.customMeshPosition;
  60342. }
  60343. else if (this.attachedNode) {
  60344. meshPosition = this.attachedNode.position;
  60345. }
  60346. else {
  60347. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  60348. }
  60349. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  60350. this._screenCoordinates.x = pos.x / this._viewPort.width;
  60351. this._screenCoordinates.y = pos.y / this._viewPort.height;
  60352. if (this.invert)
  60353. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  60354. };
  60355. // Static methods
  60356. /**
  60357. * Creates a default mesh for the Volumeric Light Scattering post-process
  60358. * @param {string} The mesh name
  60359. * @param {BABYLON.Scene} The scene where to create the mesh
  60360. * @return {BABYLON.Mesh} the default mesh
  60361. */
  60362. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  60363. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  60364. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  60365. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  60366. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  60367. mesh.material = material;
  60368. return mesh;
  60369. };
  60370. __decorate([
  60371. BABYLON.serializeAsVector3()
  60372. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  60373. __decorate([
  60374. BABYLON.serialize()
  60375. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  60376. __decorate([
  60377. BABYLON.serialize()
  60378. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  60379. __decorate([
  60380. BABYLON.serializeAsMeshReference()
  60381. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  60382. __decorate([
  60383. BABYLON.serialize()
  60384. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  60385. __decorate([
  60386. BABYLON.serialize()
  60387. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  60388. __decorate([
  60389. BABYLON.serialize()
  60390. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  60391. __decorate([
  60392. BABYLON.serialize()
  60393. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  60394. __decorate([
  60395. BABYLON.serialize()
  60396. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  60397. return VolumetricLightScatteringPostProcess;
  60398. }(BABYLON.PostProcess));
  60399. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  60400. })(BABYLON || (BABYLON = {}));
  60401. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  60402. //
  60403. // This post-process allows the modification of rendered colors by using
  60404. // a 'look-up table' (LUT). This effect is also called Color Grading.
  60405. //
  60406. // The object needs to be provided an url to a texture containing the color
  60407. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  60408. // Use an image editing software to tweak the LUT to match your needs.
  60409. //
  60410. // For an example of a color LUT, see here:
  60411. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  60412. // For explanations on color grading, see here:
  60413. // http://udn.epicgames.com/Three/ColorGrading.html
  60414. //
  60415. var BABYLON;
  60416. (function (BABYLON) {
  60417. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  60418. __extends(ColorCorrectionPostProcess, _super);
  60419. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  60420. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  60421. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60422. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  60423. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60424. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60425. _this.onApply = function (effect) {
  60426. effect.setTexture("colorTable", _this._colorTableTexture);
  60427. };
  60428. return _this;
  60429. }
  60430. return ColorCorrectionPostProcess;
  60431. }(BABYLON.PostProcess));
  60432. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  60433. })(BABYLON || (BABYLON = {}));
  60434. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  60435. var BABYLON;
  60436. (function (BABYLON) {
  60437. var TonemappingOperator;
  60438. (function (TonemappingOperator) {
  60439. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  60440. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  60441. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  60442. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  60443. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  60444. ;
  60445. var TonemapPostProcess = /** @class */ (function (_super) {
  60446. __extends(TonemapPostProcess, _super);
  60447. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  60448. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60449. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60450. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  60451. _this._operator = _operator;
  60452. _this.exposureAdjustment = exposureAdjustment;
  60453. var defines = "#define ";
  60454. if (_this._operator === TonemappingOperator.Hable)
  60455. defines += "HABLE_TONEMAPPING";
  60456. else if (_this._operator === TonemappingOperator.Reinhard)
  60457. defines += "REINHARD_TONEMAPPING";
  60458. else if (_this._operator === TonemappingOperator.HejiDawson)
  60459. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  60460. else if (_this._operator === TonemappingOperator.Photographic)
  60461. defines += "PHOTOGRAPHIC_TONEMAPPING";
  60462. //sadly a second call to create the effect.
  60463. _this.updateEffect(defines);
  60464. _this.onApply = function (effect) {
  60465. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  60466. };
  60467. return _this;
  60468. }
  60469. return TonemapPostProcess;
  60470. }(BABYLON.PostProcess));
  60471. BABYLON.TonemapPostProcess = TonemapPostProcess;
  60472. })(BABYLON || (BABYLON = {}));
  60473. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  60474. var BABYLON;
  60475. (function (BABYLON) {
  60476. var DisplayPassPostProcess = /** @class */ (function (_super) {
  60477. __extends(DisplayPassPostProcess, _super);
  60478. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  60479. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  60480. }
  60481. return DisplayPassPostProcess;
  60482. }(BABYLON.PostProcess));
  60483. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  60484. })(BABYLON || (BABYLON = {}));
  60485. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  60486. var BABYLON;
  60487. (function (BABYLON) {
  60488. var HighlightsPostProcess = /** @class */ (function (_super) {
  60489. __extends(HighlightsPostProcess, _super);
  60490. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60491. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60492. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  60493. }
  60494. return HighlightsPostProcess;
  60495. }(BABYLON.PostProcess));
  60496. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  60497. })(BABYLON || (BABYLON = {}));
  60498. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  60499. var BABYLON;
  60500. (function (BABYLON) {
  60501. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  60502. __extends(ImageProcessingPostProcess, _super);
  60503. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60504. if (camera === void 0) { camera = null; }
  60505. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60506. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  60507. _this._fromLinearSpace = true;
  60508. /**
  60509. * Defines cache preventing GC.
  60510. */
  60511. _this._defines = {
  60512. IMAGEPROCESSING: false,
  60513. VIGNETTE: false,
  60514. VIGNETTEBLENDMODEMULTIPLY: false,
  60515. VIGNETTEBLENDMODEOPAQUE: false,
  60516. TONEMAPPING: false,
  60517. CONTRAST: false,
  60518. COLORCURVES: false,
  60519. COLORGRADING: false,
  60520. COLORGRADING3D: false,
  60521. FROMLINEARSPACE: false,
  60522. SAMPLER3DGREENDEPTH: false,
  60523. SAMPLER3DBGRMAP: false,
  60524. IMAGEPROCESSINGPOSTPROCESS: false,
  60525. EXPOSURE: false,
  60526. };
  60527. // Setup the default processing configuration to the scene.
  60528. _this._attachImageProcessingConfiguration(null, true);
  60529. _this.imageProcessingConfiguration.applyByPostProcess = true;
  60530. _this.onApply = function (effect) {
  60531. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  60532. };
  60533. return _this;
  60534. }
  60535. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  60536. /**
  60537. * Gets the image processing configuration used either in this material.
  60538. */
  60539. get: function () {
  60540. return this._imageProcessingConfiguration;
  60541. },
  60542. /**
  60543. * Sets the Default image processing configuration used either in the this material.
  60544. *
  60545. * If sets to null, the scene one is in use.
  60546. */
  60547. set: function (value) {
  60548. this._attachImageProcessingConfiguration(value);
  60549. },
  60550. enumerable: true,
  60551. configurable: true
  60552. });
  60553. /**
  60554. * Attaches a new image processing configuration to the PBR Material.
  60555. * @param configuration
  60556. */
  60557. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  60558. var _this = this;
  60559. if (doNotBuild === void 0) { doNotBuild = false; }
  60560. if (configuration === this._imageProcessingConfiguration) {
  60561. return;
  60562. }
  60563. // Detaches observer.
  60564. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60565. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60566. }
  60567. // Pick the scene configuration if needed.
  60568. if (!configuration) {
  60569. var scene = null;
  60570. var engine = this.getEngine();
  60571. var camera = this.getCamera();
  60572. if (camera) {
  60573. scene = camera.getScene();
  60574. }
  60575. else if (engine && engine.scenes) {
  60576. var scenes = engine.scenes;
  60577. scene = scenes[scenes.length - 1];
  60578. }
  60579. else {
  60580. scene = BABYLON.Engine.LastCreatedScene;
  60581. }
  60582. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  60583. }
  60584. else {
  60585. this._imageProcessingConfiguration = configuration;
  60586. }
  60587. // Attaches observer.
  60588. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  60589. _this._updateParameters();
  60590. });
  60591. // Ensure the effect will be rebuilt.
  60592. if (!doNotBuild) {
  60593. this._updateParameters();
  60594. }
  60595. };
  60596. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  60597. /**
  60598. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60599. */
  60600. get: function () {
  60601. return this.imageProcessingConfiguration.colorCurves;
  60602. },
  60603. /**
  60604. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60605. */
  60606. set: function (value) {
  60607. this.imageProcessingConfiguration.colorCurves = value;
  60608. },
  60609. enumerable: true,
  60610. configurable: true
  60611. });
  60612. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  60613. /**
  60614. * Gets wether the color curves effect is enabled.
  60615. */
  60616. get: function () {
  60617. return this.imageProcessingConfiguration.colorCurvesEnabled;
  60618. },
  60619. /**
  60620. * Sets wether the color curves effect is enabled.
  60621. */
  60622. set: function (value) {
  60623. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  60624. },
  60625. enumerable: true,
  60626. configurable: true
  60627. });
  60628. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  60629. /**
  60630. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60631. */
  60632. get: function () {
  60633. return this.imageProcessingConfiguration.colorGradingTexture;
  60634. },
  60635. /**
  60636. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60637. */
  60638. set: function (value) {
  60639. this.imageProcessingConfiguration.colorGradingTexture = value;
  60640. },
  60641. enumerable: true,
  60642. configurable: true
  60643. });
  60644. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  60645. /**
  60646. * Gets wether the color grading effect is enabled.
  60647. */
  60648. get: function () {
  60649. return this.imageProcessingConfiguration.colorGradingEnabled;
  60650. },
  60651. /**
  60652. * Gets wether the color grading effect is enabled.
  60653. */
  60654. set: function (value) {
  60655. this.imageProcessingConfiguration.colorGradingEnabled = value;
  60656. },
  60657. enumerable: true,
  60658. configurable: true
  60659. });
  60660. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  60661. /**
  60662. * Gets exposure used in the effect.
  60663. */
  60664. get: function () {
  60665. return this.imageProcessingConfiguration.exposure;
  60666. },
  60667. /**
  60668. * Sets exposure used in the effect.
  60669. */
  60670. set: function (value) {
  60671. this.imageProcessingConfiguration.exposure = value;
  60672. },
  60673. enumerable: true,
  60674. configurable: true
  60675. });
  60676. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  60677. /**
  60678. * Gets wether tonemapping is enabled or not.
  60679. */
  60680. get: function () {
  60681. return this._imageProcessingConfiguration.toneMappingEnabled;
  60682. },
  60683. /**
  60684. * Sets wether tonemapping is enabled or not
  60685. */
  60686. set: function (value) {
  60687. this._imageProcessingConfiguration.toneMappingEnabled = value;
  60688. },
  60689. enumerable: true,
  60690. configurable: true
  60691. });
  60692. ;
  60693. ;
  60694. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  60695. /**
  60696. * Gets contrast used in the effect.
  60697. */
  60698. get: function () {
  60699. return this.imageProcessingConfiguration.contrast;
  60700. },
  60701. /**
  60702. * Sets contrast used in the effect.
  60703. */
  60704. set: function (value) {
  60705. this.imageProcessingConfiguration.contrast = value;
  60706. },
  60707. enumerable: true,
  60708. configurable: true
  60709. });
  60710. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  60711. /**
  60712. * Gets Vignette stretch size.
  60713. */
  60714. get: function () {
  60715. return this.imageProcessingConfiguration.vignetteStretch;
  60716. },
  60717. /**
  60718. * Sets Vignette stretch size.
  60719. */
  60720. set: function (value) {
  60721. this.imageProcessingConfiguration.vignetteStretch = value;
  60722. },
  60723. enumerable: true,
  60724. configurable: true
  60725. });
  60726. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  60727. /**
  60728. * Gets Vignette centre X Offset.
  60729. */
  60730. get: function () {
  60731. return this.imageProcessingConfiguration.vignetteCentreX;
  60732. },
  60733. /**
  60734. * Sets Vignette centre X Offset.
  60735. */
  60736. set: function (value) {
  60737. this.imageProcessingConfiguration.vignetteCentreX = value;
  60738. },
  60739. enumerable: true,
  60740. configurable: true
  60741. });
  60742. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  60743. /**
  60744. * Gets Vignette centre Y Offset.
  60745. */
  60746. get: function () {
  60747. return this.imageProcessingConfiguration.vignetteCentreY;
  60748. },
  60749. /**
  60750. * Sets Vignette centre Y Offset.
  60751. */
  60752. set: function (value) {
  60753. this.imageProcessingConfiguration.vignetteCentreY = value;
  60754. },
  60755. enumerable: true,
  60756. configurable: true
  60757. });
  60758. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  60759. /**
  60760. * Gets Vignette weight or intensity of the vignette effect.
  60761. */
  60762. get: function () {
  60763. return this.imageProcessingConfiguration.vignetteWeight;
  60764. },
  60765. /**
  60766. * Sets Vignette weight or intensity of the vignette effect.
  60767. */
  60768. set: function (value) {
  60769. this.imageProcessingConfiguration.vignetteWeight = value;
  60770. },
  60771. enumerable: true,
  60772. configurable: true
  60773. });
  60774. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  60775. /**
  60776. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60777. * if vignetteEnabled is set to true.
  60778. */
  60779. get: function () {
  60780. return this.imageProcessingConfiguration.vignetteColor;
  60781. },
  60782. /**
  60783. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60784. * if vignetteEnabled is set to true.
  60785. */
  60786. set: function (value) {
  60787. this.imageProcessingConfiguration.vignetteColor = value;
  60788. },
  60789. enumerable: true,
  60790. configurable: true
  60791. });
  60792. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  60793. /**
  60794. * Gets Camera field of view used by the Vignette effect.
  60795. */
  60796. get: function () {
  60797. return this.imageProcessingConfiguration.vignetteCameraFov;
  60798. },
  60799. /**
  60800. * Sets Camera field of view used by the Vignette effect.
  60801. */
  60802. set: function (value) {
  60803. this.imageProcessingConfiguration.vignetteCameraFov = value;
  60804. },
  60805. enumerable: true,
  60806. configurable: true
  60807. });
  60808. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  60809. /**
  60810. * Gets the vignette blend mode allowing different kind of effect.
  60811. */
  60812. get: function () {
  60813. return this.imageProcessingConfiguration.vignetteBlendMode;
  60814. },
  60815. /**
  60816. * Sets the vignette blend mode allowing different kind of effect.
  60817. */
  60818. set: function (value) {
  60819. this.imageProcessingConfiguration.vignetteBlendMode = value;
  60820. },
  60821. enumerable: true,
  60822. configurable: true
  60823. });
  60824. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  60825. /**
  60826. * Gets wether the vignette effect is enabled.
  60827. */
  60828. get: function () {
  60829. return this.imageProcessingConfiguration.vignetteEnabled;
  60830. },
  60831. /**
  60832. * Sets wether the vignette effect is enabled.
  60833. */
  60834. set: function (value) {
  60835. this.imageProcessingConfiguration.vignetteEnabled = value;
  60836. },
  60837. enumerable: true,
  60838. configurable: true
  60839. });
  60840. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  60841. /**
  60842. * Gets wether the input of the processing is in Gamma or Linear Space.
  60843. */
  60844. get: function () {
  60845. return this._fromLinearSpace;
  60846. },
  60847. /**
  60848. * Sets wether the input of the processing is in Gamma or Linear Space.
  60849. */
  60850. set: function (value) {
  60851. if (this._fromLinearSpace === value) {
  60852. return;
  60853. }
  60854. this._fromLinearSpace = value;
  60855. this._updateParameters();
  60856. },
  60857. enumerable: true,
  60858. configurable: true
  60859. });
  60860. ImageProcessingPostProcess.prototype.getClassName = function () {
  60861. return "ImageProcessingPostProcess";
  60862. };
  60863. ImageProcessingPostProcess.prototype._updateParameters = function () {
  60864. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  60865. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  60866. var defines = "";
  60867. for (var define in this._defines) {
  60868. if (this._defines[define]) {
  60869. defines += "#define " + define + ";\r\n";
  60870. }
  60871. }
  60872. var samplers = ["textureSampler"];
  60873. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  60874. var uniforms = ["scale"];
  60875. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  60876. this.updateEffect(defines, uniforms, samplers);
  60877. };
  60878. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  60879. _super.prototype.dispose.call(this, camera);
  60880. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60881. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60882. }
  60883. this.imageProcessingConfiguration.applyByPostProcess = false;
  60884. };
  60885. __decorate([
  60886. BABYLON.serialize()
  60887. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  60888. return ImageProcessingPostProcess;
  60889. }(BABYLON.PostProcess));
  60890. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  60891. })(BABYLON || (BABYLON = {}));
  60892. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  60893. var BABYLON;
  60894. (function (BABYLON) {
  60895. var BlurPostProcess = /** @class */ (function (_super) {
  60896. __extends(BlurPostProcess, _super);
  60897. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  60898. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60899. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60900. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  60901. _this.direction = direction;
  60902. _this._packedFloat = false;
  60903. _this.onApplyObservable.add(function (effect) {
  60904. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  60905. });
  60906. _this.kernel = kernel;
  60907. return _this;
  60908. }
  60909. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  60910. /**
  60911. * Gets the length in pixels of the blur sample region
  60912. */
  60913. get: function () {
  60914. return this._idealKernel;
  60915. },
  60916. /**
  60917. * Sets the length in pixels of the blur sample region
  60918. */
  60919. set: function (v) {
  60920. if (this._idealKernel === v) {
  60921. return;
  60922. }
  60923. v = Math.max(v, 1);
  60924. this._idealKernel = v;
  60925. this._kernel = this._nearestBestKernel(v);
  60926. this._updateParameters();
  60927. },
  60928. enumerable: true,
  60929. configurable: true
  60930. });
  60931. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  60932. /**
  60933. * Gets wether or not the blur is unpacking/repacking floats
  60934. */
  60935. get: function () {
  60936. return this._packedFloat;
  60937. },
  60938. /**
  60939. * Sets wether or not the blur needs to unpack/repack floats
  60940. */
  60941. set: function (v) {
  60942. if (this._packedFloat === v) {
  60943. return;
  60944. }
  60945. this._packedFloat = v;
  60946. this._updateParameters();
  60947. },
  60948. enumerable: true,
  60949. configurable: true
  60950. });
  60951. BlurPostProcess.prototype._updateParameters = function () {
  60952. // Generate sampling offsets and weights
  60953. var N = this._kernel;
  60954. var centerIndex = (N - 1) / 2;
  60955. // Generate Gaussian sampling weights over kernel
  60956. var offsets = [];
  60957. var weights = [];
  60958. var totalWeight = 0;
  60959. for (var i = 0; i < N; i++) {
  60960. var u = i / (N - 1);
  60961. var w = this._gaussianWeight(u * 2.0 - 1);
  60962. offsets[i] = (i - centerIndex);
  60963. weights[i] = w;
  60964. totalWeight += w;
  60965. }
  60966. // Normalize weights
  60967. for (var i = 0; i < weights.length; i++) {
  60968. weights[i] /= totalWeight;
  60969. }
  60970. // Optimize: combine samples to take advantage of hardware linear sampling
  60971. // Walk from left to center, combining pairs (symmetrically)
  60972. var linearSamplingWeights = [];
  60973. var linearSamplingOffsets = [];
  60974. var linearSamplingMap = [];
  60975. for (var i = 0; i <= centerIndex; i += 2) {
  60976. var j = Math.min(i + 1, Math.floor(centerIndex));
  60977. var singleCenterSample = i === j;
  60978. if (singleCenterSample) {
  60979. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60980. }
  60981. else {
  60982. var sharedCell = j === centerIndex;
  60983. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  60984. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  60985. if (offsetLinear === 0) {
  60986. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60987. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  60988. }
  60989. else {
  60990. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  60991. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  60992. }
  60993. }
  60994. }
  60995. for (var i = 0; i < linearSamplingMap.length; i++) {
  60996. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  60997. linearSamplingWeights[i] = linearSamplingMap[i].w;
  60998. }
  60999. // Replace with optimized
  61000. offsets = linearSamplingOffsets;
  61001. weights = linearSamplingWeights;
  61002. // Generate shaders
  61003. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  61004. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  61005. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  61006. var defines = "";
  61007. for (var i = 0; i < varyingCount; i++) {
  61008. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  61009. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  61010. }
  61011. var depCount = 0;
  61012. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  61013. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  61014. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  61015. depCount++;
  61016. }
  61017. if (this.packedFloat) {
  61018. defines += "#define PACKEDFLOAT 1";
  61019. }
  61020. this.updateEffect(defines, null, null, {
  61021. varyingCount: varyingCount,
  61022. depCount: depCount
  61023. });
  61024. };
  61025. /**
  61026. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  61027. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  61028. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  61029. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  61030. * The gaps between physical kernels are compensated for in the weighting of the samples
  61031. * @param idealKernel Ideal blur kernel.
  61032. * @return Nearest best kernel.
  61033. */
  61034. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  61035. var v = Math.round(idealKernel);
  61036. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  61037. var k = _a[_i];
  61038. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  61039. return Math.max(k, 3);
  61040. }
  61041. }
  61042. return Math.max(v, 3);
  61043. };
  61044. /**
  61045. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  61046. * @param x The point on the Gaussian distribution to sample.
  61047. * @return the value of the Gaussian function at x.
  61048. */
  61049. BlurPostProcess.prototype._gaussianWeight = function (x) {
  61050. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  61051. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  61052. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  61053. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  61054. // truncated at around 1.3% of peak strength.
  61055. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  61056. var sigma = (1 / 3);
  61057. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  61058. var exponent = -((x * x) / (2.0 * sigma * sigma));
  61059. var weight = (1.0 / denominator) * Math.exp(exponent);
  61060. return weight;
  61061. };
  61062. /**
  61063. * Generates a string that can be used as a floating point number in GLSL.
  61064. * @param x Value to print.
  61065. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  61066. * @return GLSL float string.
  61067. */
  61068. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  61069. if (decimalFigures === void 0) { decimalFigures = 8; }
  61070. return x.toFixed(decimalFigures).replace(/0+$/, '');
  61071. };
  61072. return BlurPostProcess;
  61073. }(BABYLON.PostProcess));
  61074. BABYLON.BlurPostProcess = BlurPostProcess;
  61075. })(BABYLON || (BABYLON = {}));
  61076. //# sourceMappingURL=babylon.blurPostProcess.js.map
  61077. var BABYLON;
  61078. (function (BABYLON) {
  61079. var Bone = /** @class */ (function (_super) {
  61080. __extends(Bone, _super);
  61081. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  61082. if (parentBone === void 0) { parentBone = null; }
  61083. if (localMatrix === void 0) { localMatrix = null; }
  61084. if (restPose === void 0) { restPose = null; }
  61085. if (baseMatrix === void 0) { baseMatrix = null; }
  61086. if (index === void 0) { index = null; }
  61087. var _this = _super.call(this, name, skeleton.getScene()) || this;
  61088. _this.name = name;
  61089. _this.children = new Array();
  61090. _this.animations = new Array();
  61091. // Set this value to map this bone to a different index in the transform matrices.
  61092. // Set this value to -1 to exclude the bone from the transform matrices.
  61093. _this._index = null;
  61094. _this._worldTransform = new BABYLON.Matrix();
  61095. _this._absoluteTransform = new BABYLON.Matrix();
  61096. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  61097. _this._scaleMatrix = BABYLON.Matrix.Identity();
  61098. _this._scaleVector = BABYLON.Vector3.One();
  61099. _this._negateScaleChildren = BABYLON.Vector3.One();
  61100. _this._scalingDeterminant = 1;
  61101. _this._skeleton = skeleton;
  61102. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  61103. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  61104. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  61105. _this._index = index;
  61106. skeleton.bones.push(_this);
  61107. _this.setParent(parentBone, false);
  61108. _this._updateDifferenceMatrix();
  61109. return _this;
  61110. }
  61111. Object.defineProperty(Bone.prototype, "_matrix", {
  61112. get: function () {
  61113. return this._localMatrix;
  61114. },
  61115. set: function (val) {
  61116. if (this._localMatrix) {
  61117. this._localMatrix.copyFrom(val);
  61118. }
  61119. else {
  61120. this._localMatrix = val;
  61121. }
  61122. },
  61123. enumerable: true,
  61124. configurable: true
  61125. });
  61126. // Members
  61127. Bone.prototype.getSkeleton = function () {
  61128. return this._skeleton;
  61129. };
  61130. Bone.prototype.getParent = function () {
  61131. return this._parent;
  61132. };
  61133. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  61134. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61135. if (this._parent === parent) {
  61136. return;
  61137. }
  61138. if (this._parent) {
  61139. var index = this._parent.children.indexOf(this);
  61140. if (index !== -1) {
  61141. this._parent.children.splice(index, 1);
  61142. }
  61143. }
  61144. this._parent = parent;
  61145. if (this._parent) {
  61146. this._parent.children.push(this);
  61147. }
  61148. if (updateDifferenceMatrix) {
  61149. this._updateDifferenceMatrix();
  61150. }
  61151. };
  61152. Bone.prototype.getLocalMatrix = function () {
  61153. return this._localMatrix;
  61154. };
  61155. Bone.prototype.getBaseMatrix = function () {
  61156. return this._baseMatrix;
  61157. };
  61158. Bone.prototype.getRestPose = function () {
  61159. return this._restPose;
  61160. };
  61161. Bone.prototype.returnToRest = function () {
  61162. this.updateMatrix(this._restPose.clone());
  61163. };
  61164. Bone.prototype.getWorldMatrix = function () {
  61165. return this._worldTransform;
  61166. };
  61167. Bone.prototype.getInvertedAbsoluteTransform = function () {
  61168. return this._invertedAbsoluteTransform;
  61169. };
  61170. Bone.prototype.getAbsoluteTransform = function () {
  61171. return this._absoluteTransform;
  61172. };
  61173. Object.defineProperty(Bone.prototype, "position", {
  61174. // Properties (matches AbstractMesh properties)
  61175. get: function () {
  61176. return this.getPosition();
  61177. },
  61178. set: function (newPosition) {
  61179. this.setPosition(newPosition);
  61180. },
  61181. enumerable: true,
  61182. configurable: true
  61183. });
  61184. Object.defineProperty(Bone.prototype, "rotation", {
  61185. get: function () {
  61186. return this.getRotation();
  61187. },
  61188. set: function (newRotation) {
  61189. this.setRotation(newRotation);
  61190. },
  61191. enumerable: true,
  61192. configurable: true
  61193. });
  61194. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  61195. get: function () {
  61196. return this.getRotationQuaternion();
  61197. },
  61198. set: function (newRotation) {
  61199. this.setRotationQuaternion(newRotation);
  61200. },
  61201. enumerable: true,
  61202. configurable: true
  61203. });
  61204. Object.defineProperty(Bone.prototype, "scaling", {
  61205. get: function () {
  61206. return this.getScale();
  61207. },
  61208. set: function (newScaling) {
  61209. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  61210. },
  61211. enumerable: true,
  61212. configurable: true
  61213. });
  61214. // Methods
  61215. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  61216. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  61217. this._baseMatrix = matrix.clone();
  61218. this._localMatrix = matrix.clone();
  61219. this._skeleton._markAsDirty();
  61220. if (updateDifferenceMatrix) {
  61221. this._updateDifferenceMatrix();
  61222. }
  61223. };
  61224. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  61225. if (!rootMatrix) {
  61226. rootMatrix = this._baseMatrix;
  61227. }
  61228. if (this._parent) {
  61229. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61230. }
  61231. else {
  61232. this._absoluteTransform.copyFrom(rootMatrix);
  61233. }
  61234. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  61235. for (var index = 0; index < this.children.length; index++) {
  61236. this.children[index]._updateDifferenceMatrix();
  61237. }
  61238. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  61239. };
  61240. Bone.prototype.markAsDirty = function () {
  61241. this._currentRenderId++;
  61242. this._skeleton._markAsDirty();
  61243. };
  61244. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  61245. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  61246. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  61247. // all animation may be coming from a library skeleton, so may need to create animation
  61248. if (this.animations.length === 0) {
  61249. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  61250. this.animations[0].setKeys([]);
  61251. }
  61252. // get animation info / verify there is such a range from the source bone
  61253. var sourceRange = source.animations[0].getRange(rangeName);
  61254. if (!sourceRange) {
  61255. return false;
  61256. }
  61257. var from = sourceRange.from;
  61258. var to = sourceRange.to;
  61259. var sourceKeys = source.animations[0].getKeys();
  61260. // rescaling prep
  61261. var sourceBoneLength = source.length;
  61262. var sourceParent = source.getParent();
  61263. var parent = this.getParent();
  61264. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  61265. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  61266. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  61267. var destKeys = this.animations[0].getKeys();
  61268. // loop vars declaration
  61269. var orig;
  61270. var origTranslation;
  61271. var mat;
  61272. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  61273. orig = sourceKeys[key];
  61274. if (orig.frame >= from && orig.frame <= to) {
  61275. if (rescaleAsRequired) {
  61276. mat = orig.value.clone();
  61277. // scale based on parent ratio, when bone has parent
  61278. if (parentScalingReqd) {
  61279. origTranslation = mat.getTranslation();
  61280. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  61281. // scale based on skeleton dimension ratio when root bone, and value is passed
  61282. }
  61283. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  61284. origTranslation = mat.getTranslation();
  61285. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  61286. // use original when root bone, and no data for skelDimensionsRatio
  61287. }
  61288. else {
  61289. mat = orig.value;
  61290. }
  61291. }
  61292. else {
  61293. mat = orig.value;
  61294. }
  61295. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  61296. }
  61297. }
  61298. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  61299. return true;
  61300. };
  61301. /**
  61302. * Translate the bone in local or world space.
  61303. * @param vec The amount to translate the bone.
  61304. * @param space The space that the translation is in.
  61305. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61306. */
  61307. Bone.prototype.translate = function (vec, space, mesh) {
  61308. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61309. var lm = this.getLocalMatrix();
  61310. if (space == BABYLON.Space.LOCAL) {
  61311. lm.m[12] += vec.x;
  61312. lm.m[13] += vec.y;
  61313. lm.m[14] += vec.z;
  61314. }
  61315. else {
  61316. var wm = null;
  61317. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61318. if (mesh) {
  61319. wm = mesh.getWorldMatrix();
  61320. }
  61321. this._skeleton.computeAbsoluteTransforms();
  61322. var tmat = Bone._tmpMats[0];
  61323. var tvec = Bone._tmpVecs[0];
  61324. if (this._parent) {
  61325. if (mesh && wm) {
  61326. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61327. tmat.multiplyToRef(wm, tmat);
  61328. }
  61329. else {
  61330. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61331. }
  61332. }
  61333. tmat.m[12] = 0;
  61334. tmat.m[13] = 0;
  61335. tmat.m[14] = 0;
  61336. tmat.invert();
  61337. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  61338. lm.m[12] += tvec.x;
  61339. lm.m[13] += tvec.y;
  61340. lm.m[14] += tvec.z;
  61341. }
  61342. this.markAsDirty();
  61343. };
  61344. /**
  61345. * Set the postion of the bone in local or world space.
  61346. * @param position The position to set the bone.
  61347. * @param space The space that the position is in.
  61348. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61349. */
  61350. Bone.prototype.setPosition = function (position, space, mesh) {
  61351. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61352. var lm = this.getLocalMatrix();
  61353. if (space == BABYLON.Space.LOCAL) {
  61354. lm.m[12] = position.x;
  61355. lm.m[13] = position.y;
  61356. lm.m[14] = position.z;
  61357. }
  61358. else {
  61359. var wm = null;
  61360. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61361. if (mesh) {
  61362. wm = mesh.getWorldMatrix();
  61363. }
  61364. this._skeleton.computeAbsoluteTransforms();
  61365. var tmat = Bone._tmpMats[0];
  61366. var vec = Bone._tmpVecs[0];
  61367. if (this._parent) {
  61368. if (mesh && wm) {
  61369. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61370. tmat.multiplyToRef(wm, tmat);
  61371. }
  61372. else {
  61373. tmat.copyFrom(this._parent.getAbsoluteTransform());
  61374. }
  61375. }
  61376. tmat.invert();
  61377. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  61378. lm.m[12] = vec.x;
  61379. lm.m[13] = vec.y;
  61380. lm.m[14] = vec.z;
  61381. }
  61382. this.markAsDirty();
  61383. };
  61384. /**
  61385. * Set the absolute postion of the bone (world space).
  61386. * @param position The position to set the bone.
  61387. * @param mesh The mesh that this bone is attached to.
  61388. */
  61389. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  61390. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  61391. };
  61392. /**
  61393. * Set the scale of the bone on the x, y and z axes.
  61394. * @param x The scale of the bone on the x axis.
  61395. * @param x The scale of the bone on the y axis.
  61396. * @param z The scale of the bone on the z axis.
  61397. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61398. */
  61399. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  61400. if (scaleChildren === void 0) { scaleChildren = false; }
  61401. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  61402. if (!scaleChildren) {
  61403. this._negateScaleChildren.x = 1 / x;
  61404. this._negateScaleChildren.y = 1 / y;
  61405. this._negateScaleChildren.z = 1 / z;
  61406. }
  61407. this._syncScaleVector();
  61408. }
  61409. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  61410. };
  61411. /**
  61412. * Scale the bone on the x, y and z axes.
  61413. * @param x The amount to scale the bone on the x axis.
  61414. * @param x The amount to scale the bone on the y axis.
  61415. * @param z The amount to scale the bone on the z axis.
  61416. * @param scaleChildren Set this to true if children of the bone should be scaled.
  61417. */
  61418. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  61419. if (scaleChildren === void 0) { scaleChildren = false; }
  61420. var locMat = this.getLocalMatrix();
  61421. var origLocMat = Bone._tmpMats[0];
  61422. origLocMat.copyFrom(locMat);
  61423. var origLocMatInv = Bone._tmpMats[1];
  61424. origLocMatInv.copyFrom(origLocMat);
  61425. origLocMatInv.invert();
  61426. var scaleMat = Bone._tmpMats[2];
  61427. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  61428. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  61429. this._scaleVector.x *= x;
  61430. this._scaleVector.y *= y;
  61431. this._scaleVector.z *= z;
  61432. locMat.multiplyToRef(origLocMatInv, locMat);
  61433. locMat.multiplyToRef(scaleMat, locMat);
  61434. locMat.multiplyToRef(origLocMat, locMat);
  61435. var parent = this.getParent();
  61436. if (parent) {
  61437. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  61438. }
  61439. else {
  61440. this.getAbsoluteTransform().copyFrom(locMat);
  61441. }
  61442. var len = this.children.length;
  61443. scaleMat.invert();
  61444. for (var i = 0; i < len; i++) {
  61445. var child = this.children[i];
  61446. var cm = child.getLocalMatrix();
  61447. cm.multiplyToRef(scaleMat, cm);
  61448. var lm = child.getLocalMatrix();
  61449. lm.m[12] *= x;
  61450. lm.m[13] *= y;
  61451. lm.m[14] *= z;
  61452. }
  61453. this.computeAbsoluteTransforms();
  61454. if (scaleChildren) {
  61455. for (var i = 0; i < len; i++) {
  61456. this.children[i].scale(x, y, z, scaleChildren);
  61457. }
  61458. }
  61459. this.markAsDirty();
  61460. };
  61461. /**
  61462. * Set the yaw, pitch, and roll of the bone in local or world space.
  61463. * @param yaw The rotation of the bone on the y axis.
  61464. * @param pitch The rotation of the bone on the x axis.
  61465. * @param roll The rotation of the bone on the z axis.
  61466. * @param space The space that the axes of rotation are in.
  61467. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61468. */
  61469. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  61470. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61471. var rotMat = Bone._tmpMats[0];
  61472. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  61473. var rotMatInv = Bone._tmpMats[1];
  61474. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61475. rotMatInv.multiplyToRef(rotMat, rotMat);
  61476. this._rotateWithMatrix(rotMat, space, mesh);
  61477. };
  61478. /**
  61479. * Rotate the bone on an axis in local or world space.
  61480. * @param axis The axis to rotate the bone on.
  61481. * @param amount The amount to rotate the bone.
  61482. * @param space The space that the axis is in.
  61483. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61484. */
  61485. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  61486. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61487. var rmat = Bone._tmpMats[0];
  61488. rmat.m[12] = 0;
  61489. rmat.m[13] = 0;
  61490. rmat.m[14] = 0;
  61491. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  61492. this._rotateWithMatrix(rmat, space, mesh);
  61493. };
  61494. /**
  61495. * Set the rotation of the bone to a particular axis angle in local or world space.
  61496. * @param axis The axis to rotate the bone on.
  61497. * @param angle The angle that the bone should be rotated to.
  61498. * @param space The space that the axis is in.
  61499. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61500. */
  61501. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  61502. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61503. var rotMat = Bone._tmpMats[0];
  61504. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  61505. var rotMatInv = Bone._tmpMats[1];
  61506. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61507. rotMatInv.multiplyToRef(rotMat, rotMat);
  61508. this._rotateWithMatrix(rotMat, space, mesh);
  61509. };
  61510. /**
  61511. * Set the euler rotation of the bone in local of world space.
  61512. * @param rotation The euler rotation that the bone should be set to.
  61513. * @param space The space that the rotation is in.
  61514. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61515. */
  61516. Bone.prototype.setRotation = function (rotation, space, mesh) {
  61517. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61518. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  61519. };
  61520. /**
  61521. * Set the quaternion rotation of the bone in local of world space.
  61522. * @param quat The quaternion rotation that the bone should be set to.
  61523. * @param space The space that the rotation is in.
  61524. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61525. */
  61526. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  61527. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61528. var rotMatInv = Bone._tmpMats[0];
  61529. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61530. var rotMat = Bone._tmpMats[1];
  61531. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  61532. rotMatInv.multiplyToRef(rotMat, rotMat);
  61533. this._rotateWithMatrix(rotMat, space, mesh);
  61534. };
  61535. /**
  61536. * Set the rotation matrix of the bone in local of world space.
  61537. * @param rotMat The rotation matrix that the bone should be set to.
  61538. * @param space The space that the rotation is in.
  61539. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61540. */
  61541. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  61542. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61543. var rotMatInv = Bone._tmpMats[0];
  61544. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61545. var rotMat2 = Bone._tmpMats[1];
  61546. rotMat2.copyFrom(rotMat);
  61547. rotMatInv.multiplyToRef(rotMat, rotMat2);
  61548. this._rotateWithMatrix(rotMat2, space, mesh);
  61549. };
  61550. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  61551. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61552. var lmat = this.getLocalMatrix();
  61553. var lx = lmat.m[12];
  61554. var ly = lmat.m[13];
  61555. var lz = lmat.m[14];
  61556. var parent = this.getParent();
  61557. var parentScale = Bone._tmpMats[3];
  61558. var parentScaleInv = Bone._tmpMats[4];
  61559. if (parent) {
  61560. if (space == BABYLON.Space.WORLD) {
  61561. if (mesh) {
  61562. parentScale.copyFrom(mesh.getWorldMatrix());
  61563. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  61564. }
  61565. else {
  61566. parentScale.copyFrom(parent.getAbsoluteTransform());
  61567. }
  61568. }
  61569. else {
  61570. parentScale = parent._scaleMatrix;
  61571. }
  61572. parentScaleInv.copyFrom(parentScale);
  61573. parentScaleInv.invert();
  61574. lmat.multiplyToRef(parentScale, lmat);
  61575. lmat.multiplyToRef(rmat, lmat);
  61576. lmat.multiplyToRef(parentScaleInv, lmat);
  61577. }
  61578. else {
  61579. if (space == BABYLON.Space.WORLD && mesh) {
  61580. parentScale.copyFrom(mesh.getWorldMatrix());
  61581. parentScaleInv.copyFrom(parentScale);
  61582. parentScaleInv.invert();
  61583. lmat.multiplyToRef(parentScale, lmat);
  61584. lmat.multiplyToRef(rmat, lmat);
  61585. lmat.multiplyToRef(parentScaleInv, lmat);
  61586. }
  61587. else {
  61588. lmat.multiplyToRef(rmat, lmat);
  61589. }
  61590. }
  61591. lmat.m[12] = lx;
  61592. lmat.m[13] = ly;
  61593. lmat.m[14] = lz;
  61594. this.computeAbsoluteTransforms();
  61595. this.markAsDirty();
  61596. };
  61597. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  61598. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61599. if (space == BABYLON.Space.WORLD) {
  61600. var scaleMatrix = Bone._tmpMats[2];
  61601. scaleMatrix.copyFrom(this._scaleMatrix);
  61602. rotMatInv.copyFrom(this.getAbsoluteTransform());
  61603. if (mesh) {
  61604. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  61605. var meshScale = Bone._tmpMats[3];
  61606. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  61607. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  61608. }
  61609. rotMatInv.invert();
  61610. scaleMatrix.m[0] *= this._scalingDeterminant;
  61611. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61612. }
  61613. else {
  61614. rotMatInv.copyFrom(this.getLocalMatrix());
  61615. rotMatInv.invert();
  61616. var scaleMatrix = Bone._tmpMats[2];
  61617. scaleMatrix.copyFrom(this._scaleMatrix);
  61618. if (this._parent) {
  61619. var pscaleMatrix = Bone._tmpMats[3];
  61620. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  61621. pscaleMatrix.invert();
  61622. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  61623. }
  61624. else {
  61625. scaleMatrix.m[0] *= this._scalingDeterminant;
  61626. }
  61627. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61628. }
  61629. };
  61630. /**
  61631. * Get the scale of the bone
  61632. * @returns the scale of the bone
  61633. */
  61634. Bone.prototype.getScale = function () {
  61635. return this._scaleVector.clone();
  61636. };
  61637. /**
  61638. * Copy the scale of the bone to a vector3.
  61639. * @param result The vector3 to copy the scale to
  61640. */
  61641. Bone.prototype.getScaleToRef = function (result) {
  61642. result.copyFrom(this._scaleVector);
  61643. };
  61644. /**
  61645. * Get the position of the bone in local or world space.
  61646. * @param space The space that the returned position is in.
  61647. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61648. * @returns The position of the bone
  61649. */
  61650. Bone.prototype.getPosition = function (space, mesh) {
  61651. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61652. if (mesh === void 0) { mesh = null; }
  61653. var pos = BABYLON.Vector3.Zero();
  61654. this.getPositionToRef(space, mesh, pos);
  61655. return pos;
  61656. };
  61657. /**
  61658. * Copy the position of the bone to a vector3 in local or world space.
  61659. * @param space The space that the returned position is in.
  61660. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61661. * @param result The vector3 to copy the position to.
  61662. */
  61663. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  61664. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61665. if (space == BABYLON.Space.LOCAL) {
  61666. var lm = this.getLocalMatrix();
  61667. result.x = lm.m[12];
  61668. result.y = lm.m[13];
  61669. result.z = lm.m[14];
  61670. }
  61671. else {
  61672. var wm = null;
  61673. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61674. if (mesh) {
  61675. wm = mesh.getWorldMatrix();
  61676. }
  61677. this._skeleton.computeAbsoluteTransforms();
  61678. var tmat = Bone._tmpMats[0];
  61679. if (mesh && wm) {
  61680. tmat.copyFrom(this.getAbsoluteTransform());
  61681. tmat.multiplyToRef(wm, tmat);
  61682. }
  61683. else {
  61684. tmat = this.getAbsoluteTransform();
  61685. }
  61686. result.x = tmat.m[12];
  61687. result.y = tmat.m[13];
  61688. result.z = tmat.m[14];
  61689. }
  61690. };
  61691. /**
  61692. * Get the absolute position of the bone (world space).
  61693. * @param mesh The mesh that this bone is attached to.
  61694. * @returns The absolute position of the bone
  61695. */
  61696. Bone.prototype.getAbsolutePosition = function (mesh) {
  61697. if (mesh === void 0) { mesh = null; }
  61698. var pos = BABYLON.Vector3.Zero();
  61699. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  61700. return pos;
  61701. };
  61702. /**
  61703. * Copy the absolute position of the bone (world space) to the result param.
  61704. * @param mesh The mesh that this bone is attached to.
  61705. * @param result The vector3 to copy the absolute position to.
  61706. */
  61707. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  61708. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  61709. };
  61710. /**
  61711. * Compute the absolute transforms of this bone and its children.
  61712. */
  61713. Bone.prototype.computeAbsoluteTransforms = function () {
  61714. if (this._parent) {
  61715. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61716. }
  61717. else {
  61718. this._absoluteTransform.copyFrom(this._localMatrix);
  61719. var poseMatrix = this._skeleton.getPoseMatrix();
  61720. if (poseMatrix) {
  61721. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  61722. }
  61723. }
  61724. var children = this.children;
  61725. var len = children.length;
  61726. for (var i = 0; i < len; i++) {
  61727. children[i].computeAbsoluteTransforms();
  61728. }
  61729. };
  61730. Bone.prototype._syncScaleVector = function () {
  61731. var lm = this.getLocalMatrix();
  61732. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  61733. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  61734. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  61735. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  61736. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  61737. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  61738. this._scaleVector.x = xs * Math.sqrt(xsq);
  61739. this._scaleVector.y = ys * Math.sqrt(ysq);
  61740. this._scaleVector.z = zs * Math.sqrt(zsq);
  61741. if (this._parent) {
  61742. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  61743. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  61744. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  61745. }
  61746. 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);
  61747. };
  61748. /**
  61749. * Get the world direction from an axis that is in the local space of the bone.
  61750. * @param localAxis The local direction that is used to compute the world direction.
  61751. * @param mesh The mesh that this bone is attached to.
  61752. * @returns The world direction
  61753. */
  61754. Bone.prototype.getDirection = function (localAxis, mesh) {
  61755. if (mesh === void 0) { mesh = null; }
  61756. var result = BABYLON.Vector3.Zero();
  61757. this.getDirectionToRef(localAxis, mesh, result);
  61758. return result;
  61759. };
  61760. /**
  61761. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  61762. * @param localAxis The local direction that is used to compute the world direction.
  61763. * @param mesh The mesh that this bone is attached to.
  61764. * @param result The vector3 that the world direction will be copied to.
  61765. */
  61766. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  61767. if (mesh === void 0) { mesh = null; }
  61768. var wm = null;
  61769. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61770. if (mesh) {
  61771. wm = mesh.getWorldMatrix();
  61772. }
  61773. this._skeleton.computeAbsoluteTransforms();
  61774. var mat = Bone._tmpMats[0];
  61775. mat.copyFrom(this.getAbsoluteTransform());
  61776. if (mesh && wm) {
  61777. mat.multiplyToRef(wm, mat);
  61778. }
  61779. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  61780. result.normalize();
  61781. };
  61782. /**
  61783. * Get the euler rotation of the bone in local or world space.
  61784. * @param space The space that the rotation should be in.
  61785. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61786. * @returns The euler rotation
  61787. */
  61788. Bone.prototype.getRotation = function (space, mesh) {
  61789. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61790. if (mesh === void 0) { mesh = null; }
  61791. var result = BABYLON.Vector3.Zero();
  61792. this.getRotationToRef(space, mesh, result);
  61793. return result;
  61794. };
  61795. /**
  61796. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  61797. * @param space The space that the rotation should be in.
  61798. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61799. * @param result The vector3 that the rotation should be copied to.
  61800. */
  61801. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  61802. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61803. if (mesh === void 0) { mesh = null; }
  61804. var quat = Bone._tmpQuat;
  61805. this.getRotationQuaternionToRef(space, mesh, quat);
  61806. quat.toEulerAnglesToRef(result);
  61807. };
  61808. /**
  61809. * Get the quaternion rotation of the bone in either local or world space.
  61810. * @param space The space that the rotation should be in.
  61811. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61812. * @returns The quaternion rotation
  61813. */
  61814. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  61815. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61816. if (mesh === void 0) { mesh = null; }
  61817. var result = BABYLON.Quaternion.Identity();
  61818. this.getRotationQuaternionToRef(space, mesh, result);
  61819. return result;
  61820. };
  61821. /**
  61822. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  61823. * @param space The space that the rotation should be in.
  61824. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61825. * @param result The quaternion that the rotation should be copied to.
  61826. */
  61827. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  61828. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61829. if (mesh === void 0) { mesh = null; }
  61830. if (space == BABYLON.Space.LOCAL) {
  61831. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61832. }
  61833. else {
  61834. var mat = Bone._tmpMats[0];
  61835. var amat = this.getAbsoluteTransform();
  61836. if (mesh) {
  61837. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61838. }
  61839. else {
  61840. mat.copyFrom(amat);
  61841. }
  61842. mat.m[0] *= this._scalingDeterminant;
  61843. mat.m[1] *= this._scalingDeterminant;
  61844. mat.m[2] *= this._scalingDeterminant;
  61845. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61846. }
  61847. };
  61848. /**
  61849. * Get the rotation matrix of the bone in local or world space.
  61850. * @param space The space that the rotation should be in.
  61851. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61852. * @returns The rotation matrix
  61853. */
  61854. Bone.prototype.getRotationMatrix = function (space, mesh) {
  61855. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61856. var result = BABYLON.Matrix.Identity();
  61857. this.getRotationMatrixToRef(space, mesh, result);
  61858. return result;
  61859. };
  61860. /**
  61861. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  61862. * @param space The space that the rotation should be in.
  61863. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61864. * @param result The quaternion that the rotation should be copied to.
  61865. */
  61866. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  61867. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61868. if (space == BABYLON.Space.LOCAL) {
  61869. this.getLocalMatrix().getRotationMatrixToRef(result);
  61870. }
  61871. else {
  61872. var mat = Bone._tmpMats[0];
  61873. var amat = this.getAbsoluteTransform();
  61874. if (mesh) {
  61875. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61876. }
  61877. else {
  61878. mat.copyFrom(amat);
  61879. }
  61880. mat.m[0] *= this._scalingDeterminant;
  61881. mat.m[1] *= this._scalingDeterminant;
  61882. mat.m[2] *= this._scalingDeterminant;
  61883. mat.getRotationMatrixToRef(result);
  61884. }
  61885. };
  61886. /**
  61887. * Get the world position of a point that is in the local space of the bone.
  61888. * @param position The local position
  61889. * @param mesh The mesh that this bone is attached to.
  61890. * @returns The world position
  61891. */
  61892. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  61893. if (mesh === void 0) { mesh = null; }
  61894. var result = BABYLON.Vector3.Zero();
  61895. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  61896. return result;
  61897. };
  61898. /**
  61899. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  61900. * @param position The local position
  61901. * @param mesh The mesh that this bone is attached to.
  61902. * @param result The vector3 that the world position should be copied to.
  61903. */
  61904. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  61905. if (mesh === void 0) { mesh = null; }
  61906. var wm = null;
  61907. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61908. if (mesh) {
  61909. wm = mesh.getWorldMatrix();
  61910. }
  61911. this._skeleton.computeAbsoluteTransforms();
  61912. var tmat = Bone._tmpMats[0];
  61913. if (mesh && wm) {
  61914. tmat.copyFrom(this.getAbsoluteTransform());
  61915. tmat.multiplyToRef(wm, tmat);
  61916. }
  61917. else {
  61918. tmat = this.getAbsoluteTransform();
  61919. }
  61920. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61921. };
  61922. /**
  61923. * Get the local position of a point that is in world space.
  61924. * @param position The world position
  61925. * @param mesh The mesh that this bone is attached to.
  61926. * @returns The local position
  61927. */
  61928. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  61929. if (mesh === void 0) { mesh = null; }
  61930. var result = BABYLON.Vector3.Zero();
  61931. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  61932. return result;
  61933. };
  61934. /**
  61935. * Get the local position of a point that is in world space and copy it to the result param.
  61936. * @param position The world position
  61937. * @param mesh The mesh that this bone is attached to.
  61938. * @param result The vector3 that the local position should be copied to.
  61939. */
  61940. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  61941. if (mesh === void 0) { mesh = null; }
  61942. var wm = null;
  61943. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61944. if (mesh) {
  61945. wm = mesh.getWorldMatrix();
  61946. }
  61947. this._skeleton.computeAbsoluteTransforms();
  61948. var tmat = Bone._tmpMats[0];
  61949. tmat.copyFrom(this.getAbsoluteTransform());
  61950. if (mesh && wm) {
  61951. tmat.multiplyToRef(wm, tmat);
  61952. }
  61953. tmat.invert();
  61954. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61955. };
  61956. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61957. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  61958. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61959. return Bone;
  61960. }(BABYLON.Node));
  61961. BABYLON.Bone = Bone;
  61962. })(BABYLON || (BABYLON = {}));
  61963. //# sourceMappingURL=babylon.bone.js.map
  61964. var BABYLON;
  61965. (function (BABYLON) {
  61966. var BoneIKController = /** @class */ (function () {
  61967. function BoneIKController(mesh, bone, options) {
  61968. this.targetPosition = BABYLON.Vector3.Zero();
  61969. this.poleTargetPosition = BABYLON.Vector3.Zero();
  61970. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  61971. this.poleAngle = 0;
  61972. this.slerpAmount = 1;
  61973. this._bone1Quat = BABYLON.Quaternion.Identity();
  61974. this._bone1Mat = BABYLON.Matrix.Identity();
  61975. this._bone2Ang = Math.PI;
  61976. this._maxAngle = Math.PI;
  61977. this._rightHandedSystem = false;
  61978. this._bendAxis = BABYLON.Vector3.Right();
  61979. this._slerping = false;
  61980. this._adjustRoll = 0;
  61981. this._bone2 = bone;
  61982. this._bone1 = bone.getParent();
  61983. if (!this._bone1) {
  61984. return;
  61985. }
  61986. this.mesh = mesh;
  61987. var bonePos = bone.getPosition();
  61988. if (bone.getAbsoluteTransform().determinant() > 0) {
  61989. this._rightHandedSystem = true;
  61990. this._bendAxis.x = 0;
  61991. this._bendAxis.y = 0;
  61992. this._bendAxis.z = -1;
  61993. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  61994. this._adjustRoll = Math.PI * .5;
  61995. this._bendAxis.z = 1;
  61996. }
  61997. }
  61998. if (this._bone1.length) {
  61999. var boneScale1 = this._bone1.getScale();
  62000. var boneScale2 = this._bone2.getScale();
  62001. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  62002. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  62003. }
  62004. else if (this._bone1.children[0]) {
  62005. mesh.computeWorldMatrix(true);
  62006. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  62007. var pos2 = this._bone2.getAbsolutePosition(mesh);
  62008. var pos3 = this._bone1.getAbsolutePosition(mesh);
  62009. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  62010. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  62011. }
  62012. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  62013. this.maxAngle = Math.PI;
  62014. if (options) {
  62015. if (options.targetMesh) {
  62016. this.targetMesh = options.targetMesh;
  62017. this.targetMesh.computeWorldMatrix(true);
  62018. }
  62019. if (options.poleTargetMesh) {
  62020. this.poleTargetMesh = options.poleTargetMesh;
  62021. this.poleTargetMesh.computeWorldMatrix(true);
  62022. }
  62023. else if (options.poleTargetBone) {
  62024. this.poleTargetBone = options.poleTargetBone;
  62025. }
  62026. else if (this._bone1.getParent()) {
  62027. this.poleTargetBone = this._bone1.getParent();
  62028. }
  62029. if (options.poleTargetLocalOffset) {
  62030. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  62031. }
  62032. if (options.poleAngle) {
  62033. this.poleAngle = options.poleAngle;
  62034. }
  62035. if (options.bendAxis) {
  62036. this._bendAxis.copyFrom(options.bendAxis);
  62037. }
  62038. if (options.maxAngle) {
  62039. this.maxAngle = options.maxAngle;
  62040. }
  62041. if (options.slerpAmount) {
  62042. this.slerpAmount = options.slerpAmount;
  62043. }
  62044. }
  62045. }
  62046. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  62047. get: function () {
  62048. return this._maxAngle;
  62049. },
  62050. set: function (value) {
  62051. this._setMaxAngle(value);
  62052. },
  62053. enumerable: true,
  62054. configurable: true
  62055. });
  62056. BoneIKController.prototype._setMaxAngle = function (ang) {
  62057. if (ang < 0) {
  62058. ang = 0;
  62059. }
  62060. if (ang > Math.PI || ang == undefined) {
  62061. ang = Math.PI;
  62062. }
  62063. this._maxAngle = ang;
  62064. var a = this._bone1Length;
  62065. var b = this._bone2Length;
  62066. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  62067. };
  62068. BoneIKController.prototype.update = function () {
  62069. var bone1 = this._bone1;
  62070. if (!bone1) {
  62071. return;
  62072. }
  62073. var target = this.targetPosition;
  62074. var poleTarget = this.poleTargetPosition;
  62075. var mat1 = BoneIKController._tmpMats[0];
  62076. var mat2 = BoneIKController._tmpMats[1];
  62077. if (this.targetMesh) {
  62078. target.copyFrom(this.targetMesh.getAbsolutePosition());
  62079. }
  62080. if (this.poleTargetBone) {
  62081. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  62082. }
  62083. else if (this.poleTargetMesh) {
  62084. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  62085. }
  62086. var bonePos = BoneIKController._tmpVecs[0];
  62087. var zaxis = BoneIKController._tmpVecs[1];
  62088. var xaxis = BoneIKController._tmpVecs[2];
  62089. var yaxis = BoneIKController._tmpVecs[3];
  62090. var upAxis = BoneIKController._tmpVecs[4];
  62091. var _tmpQuat = BoneIKController._tmpQuat;
  62092. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  62093. poleTarget.subtractToRef(bonePos, upAxis);
  62094. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  62095. upAxis.y = 1;
  62096. }
  62097. else {
  62098. upAxis.normalize();
  62099. }
  62100. target.subtractToRef(bonePos, yaxis);
  62101. yaxis.normalize();
  62102. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  62103. zaxis.normalize();
  62104. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  62105. xaxis.normalize();
  62106. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  62107. var a = this._bone1Length;
  62108. var b = this._bone2Length;
  62109. var c = BABYLON.Vector3.Distance(bonePos, target);
  62110. if (this._maxReach > 0) {
  62111. c = Math.min(this._maxReach, c);
  62112. }
  62113. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  62114. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  62115. if (acosa > 1) {
  62116. acosa = 1;
  62117. }
  62118. if (acosb > 1) {
  62119. acosb = 1;
  62120. }
  62121. if (acosa < -1) {
  62122. acosa = -1;
  62123. }
  62124. if (acosb < -1) {
  62125. acosb = -1;
  62126. }
  62127. var angA = Math.acos(acosa);
  62128. var angB = Math.acos(acosb);
  62129. var angC = -angA - angB;
  62130. if (this._rightHandedSystem) {
  62131. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  62132. mat2.multiplyToRef(mat1, mat1);
  62133. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  62134. mat2.multiplyToRef(mat1, mat1);
  62135. }
  62136. else {
  62137. var _tmpVec = BoneIKController._tmpVecs[5];
  62138. _tmpVec.copyFrom(this._bendAxis);
  62139. _tmpVec.x *= -1;
  62140. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  62141. mat2.multiplyToRef(mat1, mat1);
  62142. }
  62143. if (this.poleAngle) {
  62144. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  62145. mat1.multiplyToRef(mat2, mat1);
  62146. }
  62147. if (this._bone1) {
  62148. if (this.slerpAmount < 1) {
  62149. if (!this._slerping) {
  62150. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  62151. }
  62152. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  62153. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  62154. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  62155. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  62156. this._slerping = true;
  62157. }
  62158. else {
  62159. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  62160. this._bone1Mat.copyFrom(mat1);
  62161. this._slerping = false;
  62162. }
  62163. }
  62164. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  62165. this._bone2Ang = angC;
  62166. };
  62167. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62168. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  62169. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62170. return BoneIKController;
  62171. }());
  62172. BABYLON.BoneIKController = BoneIKController;
  62173. })(BABYLON || (BABYLON = {}));
  62174. //# sourceMappingURL=babylon.boneIKController.js.map
  62175. var BABYLON;
  62176. (function (BABYLON) {
  62177. var BoneLookController = /** @class */ (function () {
  62178. /**
  62179. * Create a BoneLookController
  62180. * @param mesh the mesh that the bone belongs to
  62181. * @param bone the bone that will be looking to the target
  62182. * @param target the target Vector3 to look at
  62183. * @param settings optional settings:
  62184. * - maxYaw: the maximum angle the bone will yaw to
  62185. * - minYaw: the minimum angle the bone will yaw to
  62186. * - maxPitch: the maximum angle the bone will pitch to
  62187. * - minPitch: the minimum angle the bone will yaw to
  62188. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  62189. * - upAxis: the up axis of the coordinate system
  62190. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62191. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  62192. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  62193. * - adjustYaw: used to make an adjustment to the yaw of the bone
  62194. * - adjustPitch: used to make an adjustment to the pitch of the bone
  62195. * - adjustRoll: used to make an adjustment to the roll of the bone
  62196. **/
  62197. function BoneLookController(mesh, bone, target, options) {
  62198. /**
  62199. * The up axis of the coordinate system that is used when the bone is rotated.
  62200. */
  62201. this.upAxis = BABYLON.Vector3.Up();
  62202. /**
  62203. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  62204. */
  62205. this.upAxisSpace = BABYLON.Space.LOCAL;
  62206. /**
  62207. * Used to make an adjustment to the yaw of the bone.
  62208. */
  62209. this.adjustYaw = 0;
  62210. /**
  62211. * Used to make an adjustment to the pitch of the bone.
  62212. */
  62213. this.adjustPitch = 0;
  62214. /**
  62215. * Used to make an adjustment to the roll of the bone.
  62216. */
  62217. this.adjustRoll = 0;
  62218. /**
  62219. * 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).
  62220. */
  62221. this.slerpAmount = 1;
  62222. this._boneQuat = BABYLON.Quaternion.Identity();
  62223. this._slerping = false;
  62224. this._firstFrameSkipped = false;
  62225. this._fowardAxis = BABYLON.Vector3.Forward();
  62226. this.mesh = mesh;
  62227. this.bone = bone;
  62228. this.target = target;
  62229. if (options) {
  62230. if (options.adjustYaw) {
  62231. this.adjustYaw = options.adjustYaw;
  62232. }
  62233. if (options.adjustPitch) {
  62234. this.adjustPitch = options.adjustPitch;
  62235. }
  62236. if (options.adjustRoll) {
  62237. this.adjustRoll = options.adjustRoll;
  62238. }
  62239. if (options.maxYaw != null) {
  62240. this.maxYaw = options.maxYaw;
  62241. }
  62242. else {
  62243. this.maxYaw = Math.PI;
  62244. }
  62245. if (options.minYaw != null) {
  62246. this.minYaw = options.minYaw;
  62247. }
  62248. else {
  62249. this.minYaw = -Math.PI;
  62250. }
  62251. if (options.maxPitch != null) {
  62252. this.maxPitch = options.maxPitch;
  62253. }
  62254. else {
  62255. this.maxPitch = Math.PI;
  62256. }
  62257. if (options.minPitch != null) {
  62258. this.minPitch = options.minPitch;
  62259. }
  62260. else {
  62261. this.minPitch = -Math.PI;
  62262. }
  62263. if (options.slerpAmount != null) {
  62264. this.slerpAmount = options.slerpAmount;
  62265. }
  62266. if (options.upAxis != null) {
  62267. this.upAxis = options.upAxis;
  62268. }
  62269. if (options.upAxisSpace != null) {
  62270. this.upAxisSpace = options.upAxisSpace;
  62271. }
  62272. if (options.yawAxis != null || options.pitchAxis != null) {
  62273. var newYawAxis = BABYLON.Axis.Y;
  62274. var newPitchAxis = BABYLON.Axis.X;
  62275. if (options.yawAxis != null) {
  62276. newYawAxis = options.yawAxis.clone();
  62277. newYawAxis.normalize();
  62278. }
  62279. if (options.pitchAxis != null) {
  62280. newPitchAxis = options.pitchAxis.clone();
  62281. newPitchAxis.normalize();
  62282. }
  62283. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  62284. this._transformYawPitch = BABYLON.Matrix.Identity();
  62285. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  62286. this._transformYawPitchInv = this._transformYawPitch.clone();
  62287. this._transformYawPitch.invert();
  62288. }
  62289. }
  62290. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  62291. this.upAxisSpace = BABYLON.Space.LOCAL;
  62292. }
  62293. }
  62294. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  62295. /**
  62296. * Get/set the minimum yaw angle that the bone can look to.
  62297. */
  62298. get: function () {
  62299. return this._minYaw;
  62300. },
  62301. set: function (value) {
  62302. this._minYaw = value;
  62303. this._minYawSin = Math.sin(value);
  62304. this._minYawCos = Math.cos(value);
  62305. if (this._maxYaw != null) {
  62306. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  62307. this._yawRange = this._maxYaw - this._minYaw;
  62308. }
  62309. },
  62310. enumerable: true,
  62311. configurable: true
  62312. });
  62313. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  62314. /**
  62315. * Get/set the maximum yaw angle that the bone can look to.
  62316. */
  62317. get: function () {
  62318. return this._maxYaw;
  62319. },
  62320. set: function (value) {
  62321. this._maxYaw = value;
  62322. this._maxYawSin = Math.sin(value);
  62323. this._maxYawCos = Math.cos(value);
  62324. if (this._minYaw != null) {
  62325. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  62326. this._yawRange = this._maxYaw - this._minYaw;
  62327. }
  62328. },
  62329. enumerable: true,
  62330. configurable: true
  62331. });
  62332. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  62333. /**
  62334. * Get/set the minimum pitch angle that the bone can look to.
  62335. */
  62336. get: function () {
  62337. return this._minPitch;
  62338. },
  62339. set: function (value) {
  62340. this._minPitch = value;
  62341. this._minPitchTan = Math.tan(value);
  62342. },
  62343. enumerable: true,
  62344. configurable: true
  62345. });
  62346. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  62347. /**
  62348. * Get/set the maximum pitch angle that the bone can look to.
  62349. */
  62350. get: function () {
  62351. return this._maxPitch;
  62352. },
  62353. set: function (value) {
  62354. this._maxPitch = value;
  62355. this._maxPitchTan = Math.tan(value);
  62356. },
  62357. enumerable: true,
  62358. configurable: true
  62359. });
  62360. /**
  62361. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  62362. */
  62363. BoneLookController.prototype.update = function () {
  62364. //skip the first frame when slerping so that the mesh rotation is correct
  62365. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  62366. this._firstFrameSkipped = true;
  62367. return;
  62368. }
  62369. var bone = this.bone;
  62370. var bonePos = BoneLookController._tmpVecs[0];
  62371. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  62372. var target = this.target;
  62373. var _tmpMat1 = BoneLookController._tmpMats[0];
  62374. var _tmpMat2 = BoneLookController._tmpMats[1];
  62375. var mesh = this.mesh;
  62376. var parentBone = bone.getParent();
  62377. var upAxis = BoneLookController._tmpVecs[1];
  62378. upAxis.copyFrom(this.upAxis);
  62379. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  62380. if (this._transformYawPitch) {
  62381. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  62382. }
  62383. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  62384. }
  62385. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  62386. mesh.getDirectionToRef(upAxis, upAxis);
  62387. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  62388. upAxis.normalize();
  62389. }
  62390. }
  62391. var checkYaw = false;
  62392. var checkPitch = false;
  62393. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  62394. checkYaw = true;
  62395. }
  62396. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  62397. checkPitch = true;
  62398. }
  62399. if (checkYaw || checkPitch) {
  62400. var spaceMat = BoneLookController._tmpMats[2];
  62401. var spaceMatInv = BoneLookController._tmpMats[3];
  62402. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  62403. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  62404. }
  62405. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  62406. spaceMat.copyFrom(mesh.getWorldMatrix());
  62407. }
  62408. else {
  62409. var forwardAxis = BoneLookController._tmpVecs[2];
  62410. forwardAxis.copyFrom(this._fowardAxis);
  62411. if (this._transformYawPitch) {
  62412. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  62413. }
  62414. if (parentBone) {
  62415. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  62416. }
  62417. else {
  62418. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  62419. }
  62420. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  62421. rightAxis.normalize();
  62422. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  62423. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  62424. }
  62425. spaceMat.invertToRef(spaceMatInv);
  62426. var xzlen = null;
  62427. if (checkPitch) {
  62428. var localTarget = BoneLookController._tmpVecs[3];
  62429. target.subtractToRef(bonePos, localTarget);
  62430. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  62431. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62432. var pitch = Math.atan2(localTarget.y, xzlen);
  62433. var newPitch = pitch;
  62434. if (pitch > this._maxPitch) {
  62435. localTarget.y = this._maxPitchTan * xzlen;
  62436. newPitch = this._maxPitch;
  62437. }
  62438. else if (pitch < this._minPitch) {
  62439. localTarget.y = this._minPitchTan * xzlen;
  62440. newPitch = this._minPitch;
  62441. }
  62442. if (pitch != newPitch) {
  62443. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62444. localTarget.addInPlace(bonePos);
  62445. target = localTarget;
  62446. }
  62447. }
  62448. if (checkYaw) {
  62449. var localTarget = BoneLookController._tmpVecs[4];
  62450. target.subtractToRef(bonePos, localTarget);
  62451. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  62452. var yaw = Math.atan2(localTarget.x, localTarget.z);
  62453. var newYaw = yaw;
  62454. if (yaw > this._maxYaw || yaw < this._minYaw) {
  62455. if (xzlen == null) {
  62456. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62457. }
  62458. if (this._yawRange > Math.PI) {
  62459. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  62460. localTarget.z = this._maxYawCos * xzlen;
  62461. localTarget.x = this._maxYawSin * xzlen;
  62462. newYaw = this._maxYaw;
  62463. }
  62464. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  62465. localTarget.z = this._minYawCos * xzlen;
  62466. localTarget.x = this._minYawSin * xzlen;
  62467. newYaw = this._minYaw;
  62468. }
  62469. }
  62470. else {
  62471. if (yaw > this._maxYaw) {
  62472. localTarget.z = this._maxYawCos * xzlen;
  62473. localTarget.x = this._maxYawSin * xzlen;
  62474. newYaw = this._maxYaw;
  62475. }
  62476. else if (yaw < this._minYaw) {
  62477. localTarget.z = this._minYawCos * xzlen;
  62478. localTarget.x = this._minYawSin * xzlen;
  62479. newYaw = this._minYaw;
  62480. }
  62481. }
  62482. }
  62483. if (this._slerping && this._yawRange > Math.PI) {
  62484. //are we going to be crossing into the min/max region?
  62485. var boneFwd = BoneLookController._tmpVecs[8];
  62486. boneFwd.copyFrom(BABYLON.Axis.Z);
  62487. if (this._transformYawPitch) {
  62488. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  62489. }
  62490. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  62491. this._boneQuat.toRotationMatrix(boneRotMat);
  62492. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  62493. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  62494. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  62495. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  62496. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  62497. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  62498. if (angBtwTar > angBtwMidYaw) {
  62499. if (xzlen == null) {
  62500. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62501. }
  62502. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  62503. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  62504. if (angBtwMin < angBtwMax) {
  62505. newYaw = boneYaw + Math.PI * .75;
  62506. localTarget.z = Math.cos(newYaw) * xzlen;
  62507. localTarget.x = Math.sin(newYaw) * xzlen;
  62508. }
  62509. else {
  62510. newYaw = boneYaw - Math.PI * .75;
  62511. localTarget.z = Math.cos(newYaw) * xzlen;
  62512. localTarget.x = Math.sin(newYaw) * xzlen;
  62513. }
  62514. }
  62515. }
  62516. if (yaw != newYaw) {
  62517. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62518. localTarget.addInPlace(bonePos);
  62519. target = localTarget;
  62520. }
  62521. }
  62522. }
  62523. var zaxis = BoneLookController._tmpVecs[5];
  62524. var xaxis = BoneLookController._tmpVecs[6];
  62525. var yaxis = BoneLookController._tmpVecs[7];
  62526. var _tmpQuat = BoneLookController._tmpQuat;
  62527. target.subtractToRef(bonePos, zaxis);
  62528. zaxis.normalize();
  62529. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  62530. xaxis.normalize();
  62531. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  62532. yaxis.normalize();
  62533. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  62534. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  62535. return;
  62536. }
  62537. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  62538. return;
  62539. }
  62540. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  62541. return;
  62542. }
  62543. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  62544. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  62545. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  62546. }
  62547. if (this.slerpAmount < 1) {
  62548. if (!this._slerping) {
  62549. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  62550. }
  62551. if (this._transformYawPitch) {
  62552. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62553. }
  62554. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  62555. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  62556. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  62557. this._slerping = true;
  62558. }
  62559. else {
  62560. if (this._transformYawPitch) {
  62561. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62562. }
  62563. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  62564. this._slerping = false;
  62565. }
  62566. };
  62567. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  62568. var angDiff = ang2 - ang1;
  62569. angDiff %= Math.PI * 2;
  62570. if (angDiff > Math.PI) {
  62571. angDiff -= Math.PI * 2;
  62572. }
  62573. else if (angDiff < -Math.PI) {
  62574. angDiff += Math.PI * 2;
  62575. }
  62576. return angDiff;
  62577. };
  62578. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  62579. ang1 %= (2 * Math.PI);
  62580. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62581. ang2 %= (2 * Math.PI);
  62582. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62583. var ab = 0;
  62584. if (ang1 < ang2) {
  62585. ab = ang2 - ang1;
  62586. }
  62587. else {
  62588. ab = ang1 - ang2;
  62589. }
  62590. if (ab > Math.PI) {
  62591. ab = Math.PI * 2 - ab;
  62592. }
  62593. return ab;
  62594. };
  62595. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  62596. ang %= (2 * Math.PI);
  62597. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  62598. ang1 %= (2 * Math.PI);
  62599. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62600. ang2 %= (2 * Math.PI);
  62601. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62602. if (ang1 < ang2) {
  62603. if (ang > ang1 && ang < ang2) {
  62604. return true;
  62605. }
  62606. }
  62607. else {
  62608. if (ang > ang2 && ang < ang1) {
  62609. return true;
  62610. }
  62611. }
  62612. return false;
  62613. };
  62614. 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()];
  62615. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  62616. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62617. return BoneLookController;
  62618. }());
  62619. BABYLON.BoneLookController = BoneLookController;
  62620. })(BABYLON || (BABYLON = {}));
  62621. //# sourceMappingURL=babylon.boneLookController.js.map
  62622. var BABYLON;
  62623. (function (BABYLON) {
  62624. var Skeleton = /** @class */ (function () {
  62625. function Skeleton(name, id, scene) {
  62626. this.name = name;
  62627. this.id = id;
  62628. this.bones = new Array();
  62629. this.needInitialSkinMatrix = false;
  62630. this._isDirty = true;
  62631. this._meshesWithPoseMatrix = new Array();
  62632. this._identity = BABYLON.Matrix.Identity();
  62633. this._ranges = {};
  62634. this._lastAbsoluteTransformsUpdateId = -1;
  62635. // Events
  62636. /**
  62637. * An event triggered before computing the skeleton's matrices
  62638. * @type {BABYLON.Observable}
  62639. */
  62640. this.onBeforeComputeObservable = new BABYLON.Observable();
  62641. this.bones = [];
  62642. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62643. scene.skeletons.push(this);
  62644. //make sure it will recalculate the matrix next time prepare is called.
  62645. this._isDirty = true;
  62646. }
  62647. // Members
  62648. Skeleton.prototype.getTransformMatrices = function (mesh) {
  62649. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  62650. return mesh._bonesTransformMatrices;
  62651. }
  62652. if (!this._transformMatrices) {
  62653. this.prepare();
  62654. }
  62655. return this._transformMatrices;
  62656. };
  62657. Skeleton.prototype.getScene = function () {
  62658. return this._scene;
  62659. };
  62660. // Methods
  62661. /**
  62662. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  62663. */
  62664. Skeleton.prototype.toString = function (fullDetails) {
  62665. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  62666. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  62667. if (fullDetails) {
  62668. ret += ", Ranges: {";
  62669. var first = true;
  62670. for (var name_1 in this._ranges) {
  62671. if (first) {
  62672. ret += ", ";
  62673. first = false;
  62674. }
  62675. ret += name_1;
  62676. }
  62677. ret += "}";
  62678. }
  62679. return ret;
  62680. };
  62681. /**
  62682. * Get bone's index searching by name
  62683. * @param {string} name is bone's name to search for
  62684. * @return {number} Indice of the bone. Returns -1 if not found
  62685. */
  62686. Skeleton.prototype.getBoneIndexByName = function (name) {
  62687. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  62688. if (this.bones[boneIndex].name === name) {
  62689. return boneIndex;
  62690. }
  62691. }
  62692. return -1;
  62693. };
  62694. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  62695. // check name not already in use
  62696. if (!this._ranges[name]) {
  62697. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  62698. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62699. if (this.bones[i].animations[0]) {
  62700. this.bones[i].animations[0].createRange(name, from, to);
  62701. }
  62702. }
  62703. }
  62704. };
  62705. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  62706. if (deleteFrames === void 0) { deleteFrames = true; }
  62707. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62708. if (this.bones[i].animations[0]) {
  62709. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  62710. }
  62711. }
  62712. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  62713. };
  62714. Skeleton.prototype.getAnimationRange = function (name) {
  62715. return this._ranges[name];
  62716. };
  62717. /**
  62718. * Returns as an Array, all AnimationRanges defined on this skeleton
  62719. */
  62720. Skeleton.prototype.getAnimationRanges = function () {
  62721. var animationRanges = [];
  62722. var name;
  62723. var i = 0;
  62724. for (name in this._ranges) {
  62725. animationRanges[i] = this._ranges[name];
  62726. i++;
  62727. }
  62728. return animationRanges;
  62729. };
  62730. /**
  62731. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  62732. */
  62733. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  62734. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  62735. if (this._ranges[name] || !source.getAnimationRange(name)) {
  62736. return false;
  62737. }
  62738. var ret = true;
  62739. var frameOffset = this._getHighestAnimationFrame() + 1;
  62740. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  62741. var boneDict = {};
  62742. var sourceBones = source.bones;
  62743. var nBones;
  62744. var i;
  62745. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  62746. boneDict[sourceBones[i].name] = sourceBones[i];
  62747. }
  62748. if (this.bones.length !== sourceBones.length) {
  62749. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  62750. ret = false;
  62751. }
  62752. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  62753. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  62754. var boneName = this.bones[i].name;
  62755. var sourceBone = boneDict[boneName];
  62756. if (sourceBone) {
  62757. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  62758. }
  62759. else {
  62760. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  62761. ret = false;
  62762. }
  62763. }
  62764. // do not call createAnimationRange(), since it also is done to bones, which was already done
  62765. var range = source.getAnimationRange(name);
  62766. if (range) {
  62767. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  62768. }
  62769. return ret;
  62770. };
  62771. Skeleton.prototype.returnToRest = function () {
  62772. for (var index = 0; index < this.bones.length; index++) {
  62773. this.bones[index].returnToRest();
  62774. }
  62775. };
  62776. Skeleton.prototype._getHighestAnimationFrame = function () {
  62777. var ret = 0;
  62778. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62779. if (this.bones[i].animations[0]) {
  62780. var highest = this.bones[i].animations[0].getHighestFrame();
  62781. if (ret < highest) {
  62782. ret = highest;
  62783. }
  62784. }
  62785. }
  62786. return ret;
  62787. };
  62788. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  62789. var range = this.getAnimationRange(name);
  62790. if (!range) {
  62791. return null;
  62792. }
  62793. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  62794. };
  62795. Skeleton.prototype._markAsDirty = function () {
  62796. this._isDirty = true;
  62797. };
  62798. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  62799. this._meshesWithPoseMatrix.push(mesh);
  62800. };
  62801. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  62802. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  62803. if (index > -1) {
  62804. this._meshesWithPoseMatrix.splice(index, 1);
  62805. }
  62806. };
  62807. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  62808. this.onBeforeComputeObservable.notifyObservers(this);
  62809. for (var index = 0; index < this.bones.length; index++) {
  62810. var bone = this.bones[index];
  62811. var parentBone = bone.getParent();
  62812. if (parentBone) {
  62813. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  62814. }
  62815. else {
  62816. if (initialSkinMatrix) {
  62817. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  62818. }
  62819. else {
  62820. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  62821. }
  62822. }
  62823. if (bone._index !== -1) {
  62824. var mappedIndex = bone._index === null ? index : bone._index;
  62825. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  62826. }
  62827. }
  62828. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  62829. };
  62830. Skeleton.prototype.prepare = function () {
  62831. if (!this._isDirty) {
  62832. return;
  62833. }
  62834. if (this.needInitialSkinMatrix) {
  62835. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  62836. var mesh = this._meshesWithPoseMatrix[index];
  62837. var poseMatrix = mesh.getPoseMatrix();
  62838. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  62839. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62840. }
  62841. if (this._synchronizedWithMesh !== mesh) {
  62842. this._synchronizedWithMesh = mesh;
  62843. // Prepare bones
  62844. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  62845. var bone = this.bones[boneIndex];
  62846. if (!bone.getParent()) {
  62847. var matrix = bone.getBaseMatrix();
  62848. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  62849. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  62850. }
  62851. }
  62852. }
  62853. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  62854. }
  62855. }
  62856. else {
  62857. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  62858. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62859. }
  62860. this._computeTransformMatrices(this._transformMatrices, null);
  62861. }
  62862. this._isDirty = false;
  62863. this._scene._activeBones.addCount(this.bones.length, false);
  62864. };
  62865. Skeleton.prototype.getAnimatables = function () {
  62866. if (!this._animatables || this._animatables.length !== this.bones.length) {
  62867. this._animatables = [];
  62868. for (var index = 0; index < this.bones.length; index++) {
  62869. this._animatables.push(this.bones[index]);
  62870. }
  62871. }
  62872. return this._animatables;
  62873. };
  62874. Skeleton.prototype.clone = function (name, id) {
  62875. var result = new Skeleton(name, id || name, this._scene);
  62876. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62877. for (var index = 0; index < this.bones.length; index++) {
  62878. var source = this.bones[index];
  62879. var parentBone = null;
  62880. var parent_1 = source.getParent();
  62881. if (parent_1) {
  62882. var parentIndex = this.bones.indexOf(parent_1);
  62883. parentBone = result.bones[parentIndex];
  62884. }
  62885. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  62886. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  62887. }
  62888. if (this._ranges) {
  62889. result._ranges = {};
  62890. for (var rangeName in this._ranges) {
  62891. var range = this._ranges[rangeName];
  62892. if (range) {
  62893. result._ranges[rangeName] = range.clone();
  62894. }
  62895. }
  62896. }
  62897. this._isDirty = true;
  62898. return result;
  62899. };
  62900. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  62901. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  62902. this.bones.forEach(function (bone) {
  62903. bone.animations.forEach(function (animation) {
  62904. animation.enableBlending = true;
  62905. animation.blendingSpeed = blendingSpeed;
  62906. });
  62907. });
  62908. };
  62909. Skeleton.prototype.dispose = function () {
  62910. this._meshesWithPoseMatrix = [];
  62911. // Animations
  62912. this.getScene().stopAnimation(this);
  62913. // Remove from scene
  62914. this.getScene().removeSkeleton(this);
  62915. };
  62916. Skeleton.prototype.serialize = function () {
  62917. var serializationObject = {};
  62918. serializationObject.name = this.name;
  62919. serializationObject.id = this.id;
  62920. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  62921. serializationObject.bones = [];
  62922. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62923. for (var index = 0; index < this.bones.length; index++) {
  62924. var bone = this.bones[index];
  62925. var parent_2 = bone.getParent();
  62926. var serializedBone = {
  62927. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  62928. name: bone.name,
  62929. matrix: bone.getBaseMatrix().toArray(),
  62930. rest: bone.getRestPose().toArray()
  62931. };
  62932. serializationObject.bones.push(serializedBone);
  62933. if (bone.length) {
  62934. serializedBone.length = bone.length;
  62935. }
  62936. if (bone.animations && bone.animations.length > 0) {
  62937. serializedBone.animation = bone.animations[0].serialize();
  62938. }
  62939. serializationObject.ranges = [];
  62940. for (var name in this._ranges) {
  62941. var source = this._ranges[name];
  62942. if (!source) {
  62943. continue;
  62944. }
  62945. var range = {};
  62946. range.name = name;
  62947. range.from = source.from;
  62948. range.to = source.to;
  62949. serializationObject.ranges.push(range);
  62950. }
  62951. }
  62952. return serializationObject;
  62953. };
  62954. Skeleton.Parse = function (parsedSkeleton, scene) {
  62955. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  62956. if (parsedSkeleton.dimensionsAtRest) {
  62957. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  62958. }
  62959. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  62960. var index;
  62961. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  62962. var parsedBone = parsedSkeleton.bones[index];
  62963. var parentBone = null;
  62964. if (parsedBone.parentBoneIndex > -1) {
  62965. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  62966. }
  62967. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  62968. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  62969. if (parsedBone.length) {
  62970. bone.length = parsedBone.length;
  62971. }
  62972. if (parsedBone.animation) {
  62973. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  62974. }
  62975. }
  62976. // placed after bones, so createAnimationRange can cascade down
  62977. if (parsedSkeleton.ranges) {
  62978. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  62979. var data = parsedSkeleton.ranges[index];
  62980. skeleton.createAnimationRange(data.name, data.from, data.to);
  62981. }
  62982. }
  62983. return skeleton;
  62984. };
  62985. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  62986. if (forceUpdate === void 0) { forceUpdate = false; }
  62987. var renderId = this._scene.getRenderId();
  62988. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  62989. this.bones[0].computeAbsoluteTransforms();
  62990. this._lastAbsoluteTransformsUpdateId = renderId;
  62991. }
  62992. };
  62993. Skeleton.prototype.getPoseMatrix = function () {
  62994. var poseMatrix = null;
  62995. if (this._meshesWithPoseMatrix.length > 0) {
  62996. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  62997. }
  62998. return poseMatrix;
  62999. };
  63000. Skeleton.prototype.sortBones = function () {
  63001. var bones = new Array();
  63002. var visited = new Array(this.bones.length);
  63003. for (var index = 0; index < this.bones.length; index++) {
  63004. this._sortBones(index, bones, visited);
  63005. }
  63006. this.bones = bones;
  63007. };
  63008. Skeleton.prototype._sortBones = function (index, bones, visited) {
  63009. if (visited[index]) {
  63010. return;
  63011. }
  63012. visited[index] = true;
  63013. var bone = this.bones[index];
  63014. if (bone._index === undefined) {
  63015. bone._index = index;
  63016. }
  63017. var parentBone = bone.getParent();
  63018. if (parentBone) {
  63019. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  63020. }
  63021. bones.push(bone);
  63022. };
  63023. return Skeleton;
  63024. }());
  63025. BABYLON.Skeleton = Skeleton;
  63026. })(BABYLON || (BABYLON = {}));
  63027. //# sourceMappingURL=babylon.skeleton.js.map
  63028. var BABYLON;
  63029. (function (BABYLON) {
  63030. var SphericalPolynomial = /** @class */ (function () {
  63031. function SphericalPolynomial() {
  63032. this.x = BABYLON.Vector3.Zero();
  63033. this.y = BABYLON.Vector3.Zero();
  63034. this.z = BABYLON.Vector3.Zero();
  63035. this.xx = BABYLON.Vector3.Zero();
  63036. this.yy = BABYLON.Vector3.Zero();
  63037. this.zz = BABYLON.Vector3.Zero();
  63038. this.xy = BABYLON.Vector3.Zero();
  63039. this.yz = BABYLON.Vector3.Zero();
  63040. this.zx = BABYLON.Vector3.Zero();
  63041. }
  63042. SphericalPolynomial.prototype.addAmbient = function (color) {
  63043. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63044. this.xx = this.xx.add(colorVector);
  63045. this.yy = this.yy.add(colorVector);
  63046. this.zz = this.zz.add(colorVector);
  63047. };
  63048. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  63049. var result = new SphericalPolynomial();
  63050. result.x = harmonics.L11.scale(1.02333);
  63051. result.y = harmonics.L1_1.scale(1.02333);
  63052. result.z = harmonics.L10.scale(1.02333);
  63053. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  63054. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  63055. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  63056. result.yz = harmonics.L2_1.scale(0.858086);
  63057. result.zx = harmonics.L21.scale(0.858086);
  63058. result.xy = harmonics.L2_2.scale(0.858086);
  63059. result.scale(1.0 / Math.PI);
  63060. return result;
  63061. };
  63062. SphericalPolynomial.prototype.scale = function (scale) {
  63063. this.x = this.x.scale(scale);
  63064. this.y = this.y.scale(scale);
  63065. this.z = this.z.scale(scale);
  63066. this.xx = this.xx.scale(scale);
  63067. this.yy = this.yy.scale(scale);
  63068. this.zz = this.zz.scale(scale);
  63069. this.yz = this.yz.scale(scale);
  63070. this.zx = this.zx.scale(scale);
  63071. this.xy = this.xy.scale(scale);
  63072. };
  63073. return SphericalPolynomial;
  63074. }());
  63075. BABYLON.SphericalPolynomial = SphericalPolynomial;
  63076. var SphericalHarmonics = /** @class */ (function () {
  63077. function SphericalHarmonics() {
  63078. this.L00 = BABYLON.Vector3.Zero();
  63079. this.L1_1 = BABYLON.Vector3.Zero();
  63080. this.L10 = BABYLON.Vector3.Zero();
  63081. this.L11 = BABYLON.Vector3.Zero();
  63082. this.L2_2 = BABYLON.Vector3.Zero();
  63083. this.L2_1 = BABYLON.Vector3.Zero();
  63084. this.L20 = BABYLON.Vector3.Zero();
  63085. this.L21 = BABYLON.Vector3.Zero();
  63086. this.L22 = BABYLON.Vector3.Zero();
  63087. }
  63088. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  63089. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  63090. var c = colorVector.scale(deltaSolidAngle);
  63091. this.L00 = this.L00.add(c.scale(0.282095));
  63092. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  63093. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  63094. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  63095. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  63096. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  63097. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  63098. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  63099. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  63100. };
  63101. SphericalHarmonics.prototype.scale = function (scale) {
  63102. this.L00 = this.L00.scale(scale);
  63103. this.L1_1 = this.L1_1.scale(scale);
  63104. this.L10 = this.L10.scale(scale);
  63105. this.L11 = this.L11.scale(scale);
  63106. this.L2_2 = this.L2_2.scale(scale);
  63107. this.L2_1 = this.L2_1.scale(scale);
  63108. this.L20 = this.L20.scale(scale);
  63109. this.L21 = this.L21.scale(scale);
  63110. this.L22 = this.L22.scale(scale);
  63111. };
  63112. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  63113. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  63114. //
  63115. // E_lm = A_l * L_lm
  63116. //
  63117. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  63118. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  63119. // the scaling factors are given in equation 9.
  63120. // Constant (Band 0)
  63121. this.L00 = this.L00.scale(3.141593);
  63122. // Linear (Band 1)
  63123. this.L1_1 = this.L1_1.scale(2.094395);
  63124. this.L10 = this.L10.scale(2.094395);
  63125. this.L11 = this.L11.scale(2.094395);
  63126. // Quadratic (Band 2)
  63127. this.L2_2 = this.L2_2.scale(0.785398);
  63128. this.L2_1 = this.L2_1.scale(0.785398);
  63129. this.L20 = this.L20.scale(0.785398);
  63130. this.L21 = this.L21.scale(0.785398);
  63131. this.L22 = this.L22.scale(0.785398);
  63132. };
  63133. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  63134. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  63135. // L = (1/pi) * E * rho
  63136. //
  63137. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  63138. this.scale(1.0 / Math.PI);
  63139. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  63140. // (The pixel shader must apply albedo after texture fetches, etc).
  63141. };
  63142. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  63143. var result = new SphericalHarmonics();
  63144. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  63145. result.L1_1 = polynomial.y.scale(0.977204);
  63146. result.L10 = polynomial.z.scale(0.977204);
  63147. result.L11 = polynomial.x.scale(0.977204);
  63148. result.L2_2 = polynomial.xy.scale(1.16538);
  63149. result.L2_1 = polynomial.yz.scale(1.16538);
  63150. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  63151. result.L21 = polynomial.zx.scale(1.16538);
  63152. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  63153. result.scale(Math.PI);
  63154. return result;
  63155. };
  63156. return SphericalHarmonics;
  63157. }());
  63158. BABYLON.SphericalHarmonics = SphericalHarmonics;
  63159. })(BABYLON || (BABYLON = {}));
  63160. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  63161. var BABYLON;
  63162. (function (BABYLON) {
  63163. var Internals;
  63164. (function (Internals) {
  63165. var FileFaceOrientation = /** @class */ (function () {
  63166. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  63167. this.name = name;
  63168. this.worldAxisForNormal = worldAxisForNormal;
  63169. this.worldAxisForFileX = worldAxisForFileX;
  63170. this.worldAxisForFileY = worldAxisForFileY;
  63171. }
  63172. return FileFaceOrientation;
  63173. }());
  63174. ;
  63175. /**
  63176. * Helper class dealing with the extraction of spherical polynomial dataArray
  63177. * from a cube map.
  63178. */
  63179. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  63180. function CubeMapToSphericalPolynomialTools() {
  63181. }
  63182. /**
  63183. * Converts a texture to the according Spherical Polynomial data.
  63184. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63185. *
  63186. * @param texture The texture to extract the information from.
  63187. * @return The Spherical Polynomial data.
  63188. */
  63189. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  63190. if (!texture.isCube) {
  63191. // Only supports cube Textures currently.
  63192. return null;
  63193. }
  63194. var size = texture.getSize().width;
  63195. var right = texture.readPixels(0);
  63196. var left = texture.readPixels(1);
  63197. var up;
  63198. var down;
  63199. if (texture.isRenderTarget) {
  63200. up = texture.readPixels(3);
  63201. down = texture.readPixels(2);
  63202. }
  63203. else {
  63204. up = texture.readPixels(2);
  63205. down = texture.readPixels(3);
  63206. }
  63207. var front = texture.readPixels(4);
  63208. var back = texture.readPixels(5);
  63209. var gammaSpace = texture.gammaSpace;
  63210. // Always read as RGBA.
  63211. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  63212. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63213. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63214. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63215. }
  63216. var cubeInfo = {
  63217. size: size,
  63218. right: right,
  63219. left: left,
  63220. up: up,
  63221. down: down,
  63222. front: front,
  63223. back: back,
  63224. format: format,
  63225. type: type,
  63226. gammaSpace: gammaSpace,
  63227. };
  63228. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  63229. };
  63230. /**
  63231. * Converts a cubemap to the according Spherical Polynomial data.
  63232. * This extracts the first 3 orders only as they are the only one used in the lighting.
  63233. *
  63234. * @param cubeInfo The Cube map to extract the information from.
  63235. * @return The Spherical Polynomial data.
  63236. */
  63237. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  63238. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  63239. var totalSolidAngle = 0.0;
  63240. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  63241. var du = 2.0 / cubeInfo.size;
  63242. var dv = du;
  63243. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  63244. var minUV = du * 0.5 - 1.0;
  63245. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63246. var fileFace = this.FileFaces[faceIndex];
  63247. var dataArray = cubeInfo[fileFace.name];
  63248. var v = minUV;
  63249. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  63250. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  63251. // Because SP is still linear, so summation is fine in that basis.
  63252. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  63253. for (var y = 0; y < cubeInfo.size; y++) {
  63254. var u = minUV;
  63255. for (var x = 0; x < cubeInfo.size; x++) {
  63256. // World direction (not normalised)
  63257. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  63258. worldDirection.normalize();
  63259. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  63260. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  63261. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  63262. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  63263. // Handle Integer types.
  63264. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  63265. r /= 255;
  63266. g /= 255;
  63267. b /= 255;
  63268. }
  63269. // Handle Gamma space textures.
  63270. if (cubeInfo.gammaSpace) {
  63271. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  63272. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  63273. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  63274. }
  63275. var color = new BABYLON.Color3(r, g, b);
  63276. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  63277. totalSolidAngle += deltaSolidAngle;
  63278. u += du;
  63279. }
  63280. v += dv;
  63281. }
  63282. }
  63283. // Solid angle for entire sphere is 4*pi
  63284. var sphereSolidAngle = 4.0 * Math.PI;
  63285. // Adjust the solid angle to allow for how many faces we processed.
  63286. var facesProcessed = 6.0;
  63287. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  63288. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  63289. // This is needed because the numerical integration over the cube uses a
  63290. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  63291. // and also to compensate for accumulative error due to float precision in the summation.
  63292. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  63293. sphericalHarmonics.scale(correctionFactor);
  63294. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  63295. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  63296. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  63297. };
  63298. CubeMapToSphericalPolynomialTools.FileFaces = [
  63299. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  63300. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  63301. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  63302. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  63303. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  63304. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  63305. ];
  63306. return CubeMapToSphericalPolynomialTools;
  63307. }());
  63308. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  63309. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63310. })(BABYLON || (BABYLON = {}));
  63311. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  63312. var BABYLON;
  63313. (function (BABYLON) {
  63314. var Internals;
  63315. (function (Internals) {
  63316. /**
  63317. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  63318. */
  63319. var PanoramaToCubeMapTools = /** @class */ (function () {
  63320. function PanoramaToCubeMapTools() {
  63321. }
  63322. /**
  63323. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  63324. *
  63325. * @param float32Array The source data.
  63326. * @param inputWidth The width of the input panorama.
  63327. * @param inputhHeight The height of the input panorama.
  63328. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  63329. * @return The cubemap data
  63330. */
  63331. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  63332. if (!float32Array) {
  63333. throw "ConvertPanoramaToCubemap: input cannot be null";
  63334. }
  63335. if (float32Array.length != inputWidth * inputHeight * 3) {
  63336. throw "ConvertPanoramaToCubemap: input size is wrong";
  63337. }
  63338. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  63339. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  63340. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  63341. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  63342. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  63343. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  63344. return {
  63345. front: textureFront,
  63346. back: textureBack,
  63347. left: textureLeft,
  63348. right: textureRight,
  63349. up: textureUp,
  63350. down: textureDown,
  63351. size: size,
  63352. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  63353. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  63354. gammaSpace: false,
  63355. };
  63356. };
  63357. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  63358. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  63359. var textureArray = new Float32Array(buffer);
  63360. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  63361. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  63362. var dy = 1 / texSize;
  63363. var fy = 0;
  63364. for (var y = 0; y < texSize; y++) {
  63365. var xv1 = faceData[0];
  63366. var xv2 = faceData[2];
  63367. for (var x = 0; x < texSize; x++) {
  63368. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  63369. v.normalize();
  63370. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  63371. // 3 channels per pixels
  63372. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  63373. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  63374. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  63375. xv1 = xv1.add(rotDX1);
  63376. xv2 = xv2.add(rotDX2);
  63377. }
  63378. fy += dy;
  63379. }
  63380. return textureArray;
  63381. };
  63382. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  63383. var theta = Math.atan2(vDir.z, vDir.x);
  63384. var phi = Math.acos(vDir.y);
  63385. while (theta < -Math.PI)
  63386. theta += 2 * Math.PI;
  63387. while (theta > Math.PI)
  63388. theta -= 2 * Math.PI;
  63389. var dx = theta / Math.PI;
  63390. var dy = phi / Math.PI;
  63391. // recenter.
  63392. dx = dx * 0.5 + 0.5;
  63393. var px = Math.round(dx * inputWidth);
  63394. if (px < 0)
  63395. px = 0;
  63396. else if (px >= inputWidth)
  63397. px = inputWidth - 1;
  63398. var py = Math.round(dy * inputHeight);
  63399. if (py < 0)
  63400. py = 0;
  63401. else if (py >= inputHeight)
  63402. py = inputHeight - 1;
  63403. var inputY = (inputHeight - py - 1);
  63404. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  63405. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  63406. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  63407. return {
  63408. r: r,
  63409. g: g,
  63410. b: b
  63411. };
  63412. };
  63413. PanoramaToCubeMapTools.FACE_FRONT = [
  63414. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63415. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63416. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63417. new BABYLON.Vector3(1.0, 1.0, -1.0)
  63418. ];
  63419. PanoramaToCubeMapTools.FACE_BACK = [
  63420. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63421. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63422. new BABYLON.Vector3(1.0, 1.0, 1.0),
  63423. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  63424. ];
  63425. PanoramaToCubeMapTools.FACE_RIGHT = [
  63426. new BABYLON.Vector3(1.0, -1.0, -1.0),
  63427. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63428. new BABYLON.Vector3(1.0, 1.0, -1.0),
  63429. new BABYLON.Vector3(1.0, 1.0, 1.0)
  63430. ];
  63431. PanoramaToCubeMapTools.FACE_LEFT = [
  63432. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63433. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63434. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  63435. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  63436. ];
  63437. PanoramaToCubeMapTools.FACE_DOWN = [
  63438. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  63439. new BABYLON.Vector3(1.0, 1.0, -1.0),
  63440. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  63441. new BABYLON.Vector3(1.0, 1.0, 1.0)
  63442. ];
  63443. PanoramaToCubeMapTools.FACE_UP = [
  63444. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  63445. new BABYLON.Vector3(1.0, -1.0, 1.0),
  63446. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  63447. new BABYLON.Vector3(1.0, -1.0, -1.0)
  63448. ];
  63449. return PanoramaToCubeMapTools;
  63450. }());
  63451. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  63452. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63453. })(BABYLON || (BABYLON = {}));
  63454. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  63455. var BABYLON;
  63456. (function (BABYLON) {
  63457. var Internals;
  63458. (function (Internals) {
  63459. ;
  63460. /**
  63461. * This groups tools to convert HDR texture to native colors array.
  63462. */
  63463. var HDRTools = /** @class */ (function () {
  63464. function HDRTools() {
  63465. }
  63466. HDRTools.Ldexp = function (mantissa, exponent) {
  63467. if (exponent > 1023) {
  63468. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  63469. }
  63470. if (exponent < -1074) {
  63471. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  63472. }
  63473. return mantissa * Math.pow(2, exponent);
  63474. };
  63475. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  63476. if (exponent > 0) {
  63477. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  63478. float32array[index + 0] = red * exponent;
  63479. float32array[index + 1] = green * exponent;
  63480. float32array[index + 2] = blue * exponent;
  63481. }
  63482. else {
  63483. float32array[index + 0] = 0;
  63484. float32array[index + 1] = 0;
  63485. float32array[index + 2] = 0;
  63486. }
  63487. };
  63488. HDRTools.readStringLine = function (uint8array, startIndex) {
  63489. var line = "";
  63490. var character = "";
  63491. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  63492. character = String.fromCharCode(uint8array[i]);
  63493. if (character == "\n") {
  63494. break;
  63495. }
  63496. line += character;
  63497. }
  63498. return line;
  63499. };
  63500. /**
  63501. * Reads header information from an RGBE texture stored in a native array.
  63502. * More information on this format are available here:
  63503. * https://en.wikipedia.org/wiki/RGBE_image_format
  63504. *
  63505. * @param uint8array The binary file stored in native array.
  63506. * @return The header information.
  63507. */
  63508. HDRTools.RGBE_ReadHeader = function (uint8array) {
  63509. var height = 0;
  63510. var width = 0;
  63511. var line = this.readStringLine(uint8array, 0);
  63512. if (line[0] != '#' || line[1] != '?') {
  63513. throw "Bad HDR Format.";
  63514. }
  63515. var endOfHeader = false;
  63516. var findFormat = false;
  63517. var lineIndex = 0;
  63518. do {
  63519. lineIndex += (line.length + 1);
  63520. line = this.readStringLine(uint8array, lineIndex);
  63521. if (line == "FORMAT=32-bit_rle_rgbe") {
  63522. findFormat = true;
  63523. }
  63524. else if (line.length == 0) {
  63525. endOfHeader = true;
  63526. }
  63527. } while (!endOfHeader);
  63528. if (!findFormat) {
  63529. throw "HDR Bad header format, unsupported FORMAT";
  63530. }
  63531. lineIndex += (line.length + 1);
  63532. line = this.readStringLine(uint8array, lineIndex);
  63533. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  63534. var match = sizeRegexp.exec(line);
  63535. // TODO. Support +Y and -X if needed.
  63536. if (!match || match.length < 3) {
  63537. throw "HDR Bad header format, no size";
  63538. }
  63539. width = parseInt(match[2]);
  63540. height = parseInt(match[1]);
  63541. if (width < 8 || width > 0x7fff) {
  63542. throw "HDR Bad header format, unsupported size";
  63543. }
  63544. lineIndex += (line.length + 1);
  63545. return {
  63546. height: height,
  63547. width: width,
  63548. dataPosition: lineIndex
  63549. };
  63550. };
  63551. /**
  63552. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  63553. * This RGBE texture needs to store the information as a panorama.
  63554. *
  63555. * More information on this format are available here:
  63556. * https://en.wikipedia.org/wiki/RGBE_image_format
  63557. *
  63558. * @param buffer The binary file stored in an array buffer.
  63559. * @param size The expected size of the extracted cubemap.
  63560. * @return The Cube Map information.
  63561. */
  63562. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  63563. var uint8array = new Uint8Array(buffer);
  63564. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  63565. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63566. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  63567. return cubeMapData;
  63568. };
  63569. /**
  63570. * Returns the pixels data extracted from an RGBE texture.
  63571. * This pixels will be stored left to right up to down in the R G B order in one array.
  63572. *
  63573. * More information on this format are available here:
  63574. * https://en.wikipedia.org/wiki/RGBE_image_format
  63575. *
  63576. * @param uint8array The binary file stored in an array buffer.
  63577. * @param hdrInfo The header information of the file.
  63578. * @return The pixels data in RGB right to left up to down order.
  63579. */
  63580. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  63581. // Keep for multi format supports.
  63582. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63583. };
  63584. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  63585. var num_scanlines = hdrInfo.height;
  63586. var scanline_width = hdrInfo.width;
  63587. var a, b, c, d, count;
  63588. var dataIndex = hdrInfo.dataPosition;
  63589. var index = 0, endIndex = 0, i = 0;
  63590. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  63591. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  63592. // 3 channels of 4 bytes per pixel in float.
  63593. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  63594. var resultArray = new Float32Array(resultBuffer);
  63595. // read in each successive scanline
  63596. while (num_scanlines > 0) {
  63597. a = uint8array[dataIndex++];
  63598. b = uint8array[dataIndex++];
  63599. c = uint8array[dataIndex++];
  63600. d = uint8array[dataIndex++];
  63601. if (a != 2 || b != 2 || (c & 0x80)) {
  63602. // this file is not run length encoded
  63603. throw "HDR Bad header format, not RLE";
  63604. }
  63605. if (((c << 8) | d) != scanline_width) {
  63606. throw "HDR Bad header format, wrong scan line width";
  63607. }
  63608. index = 0;
  63609. // read each of the four channels for the scanline into the buffer
  63610. for (i = 0; i < 4; i++) {
  63611. endIndex = (i + 1) * scanline_width;
  63612. while (index < endIndex) {
  63613. a = uint8array[dataIndex++];
  63614. b = uint8array[dataIndex++];
  63615. if (a > 128) {
  63616. // a run of the same value
  63617. count = a - 128;
  63618. if ((count == 0) || (count > endIndex - index)) {
  63619. throw "HDR Bad Format, bad scanline data (run)";
  63620. }
  63621. while (count-- > 0) {
  63622. scanLineArray[index++] = b;
  63623. }
  63624. }
  63625. else {
  63626. // a non-run
  63627. count = a;
  63628. if ((count == 0) || (count > endIndex - index)) {
  63629. throw "HDR Bad Format, bad scanline data (non-run)";
  63630. }
  63631. scanLineArray[index++] = b;
  63632. if (--count > 0) {
  63633. for (var j = 0; j < count; j++) {
  63634. scanLineArray[index++] = uint8array[dataIndex++];
  63635. }
  63636. }
  63637. }
  63638. }
  63639. }
  63640. // now convert data from buffer into floats
  63641. for (i = 0; i < scanline_width; i++) {
  63642. a = scanLineArray[i];
  63643. b = scanLineArray[i + scanline_width];
  63644. c = scanLineArray[i + 2 * scanline_width];
  63645. d = scanLineArray[i + 3 * scanline_width];
  63646. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  63647. }
  63648. num_scanlines--;
  63649. }
  63650. return resultArray;
  63651. };
  63652. return HDRTools;
  63653. }());
  63654. Internals.HDRTools = HDRTools;
  63655. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63656. })(BABYLON || (BABYLON = {}));
  63657. //# sourceMappingURL=babylon.hdr.js.map
  63658. var BABYLON;
  63659. (function (BABYLON) {
  63660. /**
  63661. * This represents a texture coming from an HDR input.
  63662. *
  63663. * The only supported format is currently panorama picture stored in RGBE format.
  63664. * Example of such files can be found on HDRLib: http://hdrlib.com/
  63665. */
  63666. var HDRCubeTexture = /** @class */ (function (_super) {
  63667. __extends(HDRCubeTexture, _super);
  63668. /**
  63669. * Instantiates an HDRTexture from the following parameters.
  63670. *
  63671. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  63672. * @param scene The scene the texture will be used in
  63673. * @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.
  63674. * @param noMipmap Forces to not generate the mipmap if true
  63675. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  63676. * @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)
  63677. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  63678. */
  63679. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  63680. if (noMipmap === void 0) { noMipmap = false; }
  63681. if (generateHarmonics === void 0) { generateHarmonics = true; }
  63682. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  63683. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  63684. if (onLoad === void 0) { onLoad = null; }
  63685. if (onError === void 0) { onError = null; }
  63686. var _this = _super.call(this, scene) || this;
  63687. _this._useInGammaSpace = false;
  63688. _this._generateHarmonics = true;
  63689. _this._isBABYLONPreprocessed = false;
  63690. _this._onLoad = null;
  63691. _this._onError = null;
  63692. /**
  63693. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  63694. */
  63695. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63696. /**
  63697. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  63698. * This is usefull at run time to apply the good shader.
  63699. */
  63700. _this.isPMREM = false;
  63701. _this._isBlocking = true;
  63702. if (!url) {
  63703. return _this;
  63704. }
  63705. _this.name = url;
  63706. _this.url = url;
  63707. _this.hasAlpha = false;
  63708. _this.isCube = true;
  63709. _this._textureMatrix = BABYLON.Matrix.Identity();
  63710. _this._onLoad = onLoad;
  63711. _this._onError = onError;
  63712. _this.gammaSpace = false;
  63713. var caps = scene.getEngine().getCaps();
  63714. if (size) {
  63715. _this._isBABYLONPreprocessed = false;
  63716. _this._noMipmap = noMipmap;
  63717. _this._size = size;
  63718. _this._useInGammaSpace = useInGammaSpace;
  63719. _this._usePMREMGenerator = usePMREMGenerator &&
  63720. caps.textureLOD &&
  63721. caps.textureFloat &&
  63722. !_this._useInGammaSpace;
  63723. }
  63724. else {
  63725. _this._isBABYLONPreprocessed = true;
  63726. _this._noMipmap = false;
  63727. _this._useInGammaSpace = false;
  63728. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  63729. !_this._useInGammaSpace;
  63730. }
  63731. _this.isPMREM = _this._usePMREMGenerator;
  63732. _this._texture = _this._getFromCache(url, _this._noMipmap);
  63733. if (!_this._texture) {
  63734. if (!scene.useDelayedTextureLoading) {
  63735. _this.loadTexture();
  63736. }
  63737. else {
  63738. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63739. }
  63740. }
  63741. return _this;
  63742. }
  63743. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  63744. /**
  63745. * Gets wether or not the texture is blocking during loading.
  63746. */
  63747. get: function () {
  63748. return this._isBlocking;
  63749. },
  63750. /**
  63751. * Sets wether or not the texture is blocking during loading.
  63752. */
  63753. set: function (value) {
  63754. this._isBlocking = value;
  63755. },
  63756. enumerable: true,
  63757. configurable: true
  63758. });
  63759. /**
  63760. * Occurs when the file is a preprocessed .babylon.hdr file.
  63761. */
  63762. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  63763. var _this = this;
  63764. var mipLevels = 0;
  63765. var floatArrayView = null;
  63766. var scene = this.getScene();
  63767. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  63768. var mips = new Array();
  63769. if (!floatArrayView) {
  63770. return mips;
  63771. }
  63772. var startIndex = 30;
  63773. for (var level = 0; level < mipLevels; level++) {
  63774. mips.push([]);
  63775. // Fill each pixel of the mip level.
  63776. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  63777. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63778. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  63779. mips[level].push(faceData);
  63780. startIndex += faceSize;
  63781. }
  63782. }
  63783. return mips;
  63784. } : null;
  63785. var callback = function (buffer) {
  63786. var scene = _this.getScene();
  63787. if (!scene) {
  63788. return null;
  63789. }
  63790. // Create Native Array Views
  63791. var intArrayView = new Int32Array(buffer);
  63792. floatArrayView = new Float32Array(buffer);
  63793. // Fill header.
  63794. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  63795. _this._size = intArrayView[1]; // CubeMap max mip face size.
  63796. // Update Texture Information.
  63797. if (!_this._texture) {
  63798. return null;
  63799. }
  63800. _this._texture.updateSize(_this._size, _this._size);
  63801. // Fill polynomial information.
  63802. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  63803. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  63804. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  63805. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  63806. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  63807. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  63808. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  63809. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  63810. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  63811. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  63812. _this.sphericalPolynomial = sphericalPolynomial;
  63813. // Fill pixel data.
  63814. mipLevels = intArrayView[29]; // Number of mip levels.
  63815. var startIndex = 30;
  63816. var data = [];
  63817. var faceSize = Math.pow(_this._size, 2) * 3;
  63818. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63819. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  63820. startIndex += faceSize;
  63821. }
  63822. var results = [];
  63823. var byteArray = null;
  63824. // Push each faces.
  63825. for (var k = 0; k < 6; k++) {
  63826. var dataFace = null;
  63827. // To be deprecated.
  63828. if (version === 1) {
  63829. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  63830. dataFace = data[j];
  63831. }
  63832. // If special cases.
  63833. if (!mipmapGenerator && dataFace) {
  63834. if (!scene.getEngine().getCaps().textureFloat) {
  63835. // 3 channels of 1 bytes per pixel in bytes.
  63836. var byteBuffer = new ArrayBuffer(faceSize);
  63837. byteArray = new Uint8Array(byteBuffer);
  63838. }
  63839. for (var i = 0; i < _this._size * _this._size; i++) {
  63840. // Put in gamma space if requested.
  63841. if (_this._useInGammaSpace) {
  63842. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63843. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63844. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63845. }
  63846. // Convert to int texture for fallback.
  63847. if (byteArray) {
  63848. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63849. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63850. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63851. // May use luminance instead if the result is not accurate.
  63852. var max = Math.max(Math.max(r, g), b);
  63853. if (max > 255) {
  63854. var scale = 255 / max;
  63855. r *= scale;
  63856. g *= scale;
  63857. b *= scale;
  63858. }
  63859. byteArray[(i * 3) + 0] = r;
  63860. byteArray[(i * 3) + 1] = g;
  63861. byteArray[(i * 3) + 2] = b;
  63862. }
  63863. }
  63864. }
  63865. // Fill the array accordingly.
  63866. if (byteArray) {
  63867. results.push(byteArray);
  63868. }
  63869. else {
  63870. results.push(dataFace);
  63871. }
  63872. }
  63873. return results;
  63874. };
  63875. if (scene) {
  63876. 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);
  63877. }
  63878. };
  63879. /**
  63880. * Occurs when the file is raw .hdr file.
  63881. */
  63882. HDRCubeTexture.prototype.loadHDRTexture = function () {
  63883. var _this = this;
  63884. var callback = function (buffer) {
  63885. var scene = _this.getScene();
  63886. if (!scene) {
  63887. return null;
  63888. }
  63889. // Extract the raw linear data.
  63890. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  63891. // Generate harmonics if needed.
  63892. if (_this._generateHarmonics) {
  63893. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  63894. _this.sphericalPolynomial = sphericalPolynomial;
  63895. }
  63896. var results = [];
  63897. var byteArray = null;
  63898. // Push each faces.
  63899. for (var j = 0; j < 6; j++) {
  63900. // Create uintarray fallback.
  63901. if (!scene.getEngine().getCaps().textureFloat) {
  63902. // 3 channels of 1 bytes per pixel in bytes.
  63903. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  63904. byteArray = new Uint8Array(byteBuffer);
  63905. }
  63906. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  63907. // If special cases.
  63908. if (_this._useInGammaSpace || byteArray) {
  63909. for (var i = 0; i < _this._size * _this._size; i++) {
  63910. // Put in gamma space if requested.
  63911. if (_this._useInGammaSpace) {
  63912. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63913. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63914. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63915. }
  63916. // Convert to int texture for fallback.
  63917. if (byteArray) {
  63918. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63919. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63920. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63921. // May use luminance instead if the result is not accurate.
  63922. var max = Math.max(Math.max(r, g), b);
  63923. if (max > 255) {
  63924. var scale = 255 / max;
  63925. r *= scale;
  63926. g *= scale;
  63927. b *= scale;
  63928. }
  63929. byteArray[(i * 3) + 0] = r;
  63930. byteArray[(i * 3) + 1] = g;
  63931. byteArray[(i * 3) + 2] = b;
  63932. }
  63933. }
  63934. }
  63935. if (byteArray) {
  63936. results.push(byteArray);
  63937. }
  63938. else {
  63939. results.push(dataFace);
  63940. }
  63941. }
  63942. return results;
  63943. };
  63944. var mipmapGenerator = null;
  63945. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  63946. // if (!this._noMipmap &&
  63947. // this._usePMREMGenerator) {
  63948. // mipmapGenerator = (data: ArrayBufferView[]) => {
  63949. // // Custom setup of the generator matching with the PBR shader values.
  63950. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  63951. // this._size,
  63952. // this._size,
  63953. // 0,
  63954. // 3,
  63955. // this.getScene().getEngine().getCaps().textureFloat,
  63956. // 2048,
  63957. // 0.25,
  63958. // false,
  63959. // true);
  63960. // return generator.filterCubeMap();
  63961. // };
  63962. // }
  63963. var scene = this.getScene();
  63964. if (scene) {
  63965. 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);
  63966. }
  63967. };
  63968. /**
  63969. * Starts the loading process of the texture.
  63970. */
  63971. HDRCubeTexture.prototype.loadTexture = function () {
  63972. if (this._isBABYLONPreprocessed) {
  63973. this.loadBabylonTexture();
  63974. }
  63975. else {
  63976. this.loadHDRTexture();
  63977. }
  63978. };
  63979. HDRCubeTexture.prototype.clone = function () {
  63980. var scene = this.getScene();
  63981. if (!scene) {
  63982. return this;
  63983. }
  63984. var size = (this._isBABYLONPreprocessed ? null : this._size);
  63985. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  63986. // Base texture
  63987. newTexture.level = this.level;
  63988. newTexture.wrapU = this.wrapU;
  63989. newTexture.wrapV = this.wrapV;
  63990. newTexture.coordinatesIndex = this.coordinatesIndex;
  63991. newTexture.coordinatesMode = this.coordinatesMode;
  63992. return newTexture;
  63993. };
  63994. // Methods
  63995. HDRCubeTexture.prototype.delayLoad = function () {
  63996. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63997. return;
  63998. }
  63999. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64000. this._texture = this._getFromCache(this.url, this._noMipmap);
  64001. if (!this._texture) {
  64002. this.loadTexture();
  64003. }
  64004. };
  64005. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  64006. return this._textureMatrix;
  64007. };
  64008. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64009. this._textureMatrix = value;
  64010. };
  64011. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64012. var texture = null;
  64013. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  64014. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  64015. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  64016. texture.name = parsedTexture.name;
  64017. texture.hasAlpha = parsedTexture.hasAlpha;
  64018. texture.level = parsedTexture.level;
  64019. texture.coordinatesMode = parsedTexture.coordinatesMode;
  64020. texture.isBlocking = parsedTexture.isBlocking;
  64021. }
  64022. return texture;
  64023. };
  64024. HDRCubeTexture.prototype.serialize = function () {
  64025. if (!this.name) {
  64026. return null;
  64027. }
  64028. var serializationObject = {};
  64029. serializationObject.name = this.name;
  64030. serializationObject.hasAlpha = this.hasAlpha;
  64031. serializationObject.isCube = true;
  64032. serializationObject.level = this.level;
  64033. serializationObject.size = this._size;
  64034. serializationObject.coordinatesMode = this.coordinatesMode;
  64035. serializationObject.useInGammaSpace = this._useInGammaSpace;
  64036. serializationObject.generateHarmonics = this._generateHarmonics;
  64037. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  64038. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  64039. serializationObject.customType = "BABYLON.HDRCubeTexture";
  64040. serializationObject.noMipmap = this._noMipmap;
  64041. serializationObject.isBlocking = this._isBlocking;
  64042. return serializationObject;
  64043. };
  64044. /**
  64045. * Saves as a file the data contained in the texture in a binary format.
  64046. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64047. * as the spherical used in the lighting.
  64048. * @param url The HDR file url.
  64049. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64050. * @param onError Method called if any error happens during download.
  64051. * @return The packed binary data.
  64052. */
  64053. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  64054. if (onError === void 0) { onError = null; }
  64055. var callback = function (buffer) {
  64056. var data = new Blob([buffer], { type: 'application/octet-stream' });
  64057. // Returns a URL you can use as a href.
  64058. var objUrl = window.URL.createObjectURL(data);
  64059. // Simulates a link to it and click to dowload.
  64060. var a = document.createElement("a");
  64061. document.body.appendChild(a);
  64062. a.style.display = "none";
  64063. a.href = objUrl;
  64064. a.download = "envmap.babylon.hdr";
  64065. a.click();
  64066. };
  64067. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  64068. };
  64069. /**
  64070. * Serializes the data contained in the texture in a binary format.
  64071. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  64072. * as the spherical used in the lighting.
  64073. * @param url The HDR file url.
  64074. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  64075. * @param onError Method called if any error happens during download.
  64076. * @return The packed binary data.
  64077. */
  64078. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  64079. if (onError === void 0) { onError = null; }
  64080. // Needs the url tho create the texture.
  64081. if (!url) {
  64082. return;
  64083. }
  64084. // Check Power of two size.
  64085. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  64086. return;
  64087. }
  64088. // Coming Back in 3.x.
  64089. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  64090. };
  64091. HDRCubeTexture._facesMapping = [
  64092. "right",
  64093. "left",
  64094. "up",
  64095. "down",
  64096. "front",
  64097. "back"
  64098. ];
  64099. return HDRCubeTexture;
  64100. }(BABYLON.BaseTexture));
  64101. BABYLON.HDRCubeTexture = HDRCubeTexture;
  64102. })(BABYLON || (BABYLON = {}));
  64103. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  64104. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  64105. // Huge respect for a such great lib.
  64106. // Earcut license:
  64107. // Copyright (c) 2016, Mapbox
  64108. //
  64109. // Permission to use, copy, modify, and/or distribute this software for any purpose
  64110. // with or without fee is hereby granted, provided that the above copyright notice
  64111. // and this permission notice appear in all copies.
  64112. //
  64113. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  64114. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  64115. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  64116. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  64117. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  64118. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  64119. // THIS SOFTWARE.
  64120. var Earcut;
  64121. (function (Earcut) {
  64122. /**
  64123. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  64124. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  64125. * @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).
  64126. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  64127. */
  64128. function earcut(data, holeIndices, dim) {
  64129. dim = dim || 2;
  64130. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  64131. if (!outerNode)
  64132. return triangles;
  64133. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  64134. if (hasHoles)
  64135. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  64136. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  64137. if (data.length > 80 * dim) {
  64138. minX = maxX = data[0];
  64139. minY = maxY = data[1];
  64140. for (var i = dim; i < outerLen; i += dim) {
  64141. x = data[i];
  64142. y = data[i + 1];
  64143. if (x < minX)
  64144. minX = x;
  64145. if (y < minY)
  64146. minY = y;
  64147. if (x > maxX)
  64148. maxX = x;
  64149. if (y > maxY)
  64150. maxY = y;
  64151. }
  64152. // minX, minY and size are later used to transform coords into integers for z-order calculation
  64153. size = Math.max(maxX - minX, maxY - minY);
  64154. }
  64155. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  64156. return triangles;
  64157. }
  64158. Earcut.earcut = earcut;
  64159. var Node = /** @class */ (function () {
  64160. function Node(i, x, y) {
  64161. this.i = i;
  64162. this.x = x;
  64163. this.y = y;
  64164. this.prev = null;
  64165. this.next = null;
  64166. this.z = null;
  64167. this.prevZ = null;
  64168. this.nextZ = null;
  64169. this.steiner = false;
  64170. }
  64171. return Node;
  64172. }());
  64173. // create a circular doubly linked list from polygon points in the specified winding order
  64174. function linkedList(data, start, end, dim, clockwise) {
  64175. var i, last = null;
  64176. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  64177. for (i = start; i < end; i += dim)
  64178. last = insertNode(i, data[i], data[i + 1], last);
  64179. }
  64180. else {
  64181. for (i = end - dim; i >= start; i -= dim)
  64182. last = insertNode(i, data[i], data[i + 1], last);
  64183. }
  64184. if (last && equals(last, last.next)) {
  64185. removeNode(last);
  64186. last = last.next;
  64187. }
  64188. return last;
  64189. }
  64190. // eliminate colinear or duplicate points
  64191. function filterPoints(start, end) {
  64192. if (!start)
  64193. return start;
  64194. if (!end)
  64195. end = start;
  64196. var p = start, again;
  64197. do {
  64198. again = false;
  64199. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  64200. removeNode(p);
  64201. p = end = p.prev;
  64202. if (p === p.next)
  64203. return undefined;
  64204. again = true;
  64205. }
  64206. else {
  64207. p = p.next;
  64208. }
  64209. } while (again || p !== end);
  64210. return end;
  64211. }
  64212. // main ear slicing loop which triangulates a polygon (given as a linked list)
  64213. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  64214. if (!ear)
  64215. return;
  64216. // interlink polygon nodes in z-order
  64217. if (!pass && size)
  64218. indexCurve(ear, minX, minY, size);
  64219. var stop = ear, prev, next;
  64220. // iterate through ears, slicing them one by one
  64221. while (ear.prev !== ear.next) {
  64222. prev = ear.prev;
  64223. next = ear.next;
  64224. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  64225. // cut off the triangle
  64226. triangles.push(prev.i / dim);
  64227. triangles.push(ear.i / dim);
  64228. triangles.push(next.i / dim);
  64229. removeNode(ear);
  64230. // skipping the next vertice leads to less sliver triangles
  64231. ear = next.next;
  64232. stop = next.next;
  64233. continue;
  64234. }
  64235. ear = next;
  64236. // if we looped through the whole remaining polygon and can't find any more ears
  64237. if (ear === stop) {
  64238. // try filtering points and slicing again
  64239. if (!pass) {
  64240. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  64241. // if this didn't work, try curing all small self-intersections locally
  64242. }
  64243. else if (pass === 1) {
  64244. ear = cureLocalIntersections(ear, triangles, dim);
  64245. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  64246. // as a last resort, try splitting the remaining polygon into two
  64247. }
  64248. else if (pass === 2) {
  64249. splitEarcut(ear, triangles, dim, minX, minY, size);
  64250. }
  64251. break;
  64252. }
  64253. }
  64254. }
  64255. // check whether a polygon node forms a valid ear with adjacent nodes
  64256. function isEar(ear) {
  64257. var a = ear.prev, b = ear, c = ear.next;
  64258. if (area(a, b, c) >= 0)
  64259. return false; // reflex, can't be an ear
  64260. // now make sure we don't have other points inside the potential ear
  64261. var p = ear.next.next;
  64262. while (p !== ear.prev) {
  64263. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64264. area(p.prev, p, p.next) >= 0)
  64265. return false;
  64266. p = p.next;
  64267. }
  64268. return true;
  64269. }
  64270. function isEarHashed(ear, minX, minY, size) {
  64271. var a = ear.prev, b = ear, c = ear.next;
  64272. if (area(a, b, c) >= 0)
  64273. return false; // reflex, can't be an ear
  64274. // triangle bbox; min & max are calculated like this for speed
  64275. 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);
  64276. // z-order range for the current triangle bbox;
  64277. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  64278. // first look for points inside the triangle in increasing z-order
  64279. var p = ear.nextZ;
  64280. while (p && p.z <= maxZ) {
  64281. if (p !== ear.prev &&
  64282. p !== ear.next &&
  64283. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64284. area(p.prev, p, p.next) >= 0)
  64285. return false;
  64286. p = p.nextZ;
  64287. }
  64288. // then look for points in decreasing z-order
  64289. p = ear.prevZ;
  64290. while (p && p.z >= minZ) {
  64291. if (p !== ear.prev &&
  64292. p !== ear.next &&
  64293. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  64294. area(p.prev, p, p.next) >= 0)
  64295. return false;
  64296. p = p.prevZ;
  64297. }
  64298. return true;
  64299. }
  64300. // go through all polygon nodes and cure small local self-intersections
  64301. function cureLocalIntersections(start, triangles, dim) {
  64302. var p = start;
  64303. do {
  64304. var a = p.prev, b = p.next.next;
  64305. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  64306. triangles.push(a.i / dim);
  64307. triangles.push(p.i / dim);
  64308. triangles.push(b.i / dim);
  64309. // remove two nodes involved
  64310. removeNode(p);
  64311. removeNode(p.next);
  64312. p = start = b;
  64313. }
  64314. p = p.next;
  64315. } while (p !== start);
  64316. return p;
  64317. }
  64318. // try splitting polygon into two and triangulate them independently
  64319. function splitEarcut(start, triangles, dim, minX, minY, size) {
  64320. // look for a valid diagonal that divides the polygon into two
  64321. var a = start;
  64322. do {
  64323. var b = a.next.next;
  64324. while (b !== a.prev) {
  64325. if (a.i !== b.i && isValidDiagonal(a, b)) {
  64326. // split the polygon in two by the diagonal
  64327. var c = splitPolygon(a, b);
  64328. // filter colinear points around the cuts
  64329. a = filterPoints(a, a.next);
  64330. c = filterPoints(c, c.next);
  64331. // run earcut on each half
  64332. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  64333. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  64334. return;
  64335. }
  64336. b = b.next;
  64337. }
  64338. a = a.next;
  64339. } while (a !== start);
  64340. }
  64341. // link every hole into the outer loop, producing a single-ring polygon without holes
  64342. function eliminateHoles(data, holeIndices, outerNode, dim) {
  64343. var queue = [], i, len, start, end, list;
  64344. for (i = 0, len = holeIndices.length; i < len; i++) {
  64345. start = holeIndices[i] * dim;
  64346. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64347. list = linkedList(data, start, end, dim, false);
  64348. if (list === list.next)
  64349. list.steiner = true;
  64350. queue.push(getLeftmost(list));
  64351. }
  64352. queue.sort(compareX);
  64353. // process holes from left to right
  64354. for (i = 0; i < queue.length; i++) {
  64355. eliminateHole(queue[i], outerNode);
  64356. outerNode = filterPoints(outerNode, outerNode.next);
  64357. }
  64358. return outerNode;
  64359. }
  64360. function compareX(a, b) {
  64361. return a.x - b.x;
  64362. }
  64363. // find a bridge between vertices that connects hole with an outer ring and and link it
  64364. function eliminateHole(hole, outerNode) {
  64365. outerNode = findHoleBridge(hole, outerNode);
  64366. if (outerNode) {
  64367. var b = splitPolygon(outerNode, hole);
  64368. filterPoints(b, b.next);
  64369. }
  64370. }
  64371. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  64372. function findHoleBridge(hole, outerNode) {
  64373. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  64374. // find a segment intersected by a ray from the hole's leftmost point to the left;
  64375. // segment's endpoint with lesser x will be potential connection point
  64376. do {
  64377. if (hy <= p.y && hy >= p.next.y) {
  64378. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  64379. if (x <= hx && x > qx) {
  64380. qx = x;
  64381. if (x === hx) {
  64382. if (hy === p.y)
  64383. return p;
  64384. if (hy === p.next.y)
  64385. return p.next;
  64386. }
  64387. m = p.x < p.next.x ? p : p.next;
  64388. }
  64389. }
  64390. p = p.next;
  64391. } while (p !== outerNode);
  64392. if (!m)
  64393. return null;
  64394. if (hx === qx)
  64395. return m.prev; // hole touches outer segment; pick lower endpoint
  64396. // look for points inside the triangle of hole point, segment intersection and endpoint;
  64397. // if there are no points found, we have a valid connection;
  64398. // otherwise choose the point of the minimum angle with the ray as connection point
  64399. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  64400. p = m.next;
  64401. while (p !== stop) {
  64402. if (hx >= p.x &&
  64403. p.x >= mx &&
  64404. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  64405. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  64406. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  64407. m = p;
  64408. tanMin = tan;
  64409. }
  64410. }
  64411. p = p.next;
  64412. }
  64413. return m;
  64414. }
  64415. // interlink polygon nodes in z-order
  64416. function indexCurve(start, minX, minY, size) {
  64417. var p = start;
  64418. do {
  64419. if (p.z === null)
  64420. p.z = zOrder(p.x, p.y, minX, minY, size);
  64421. p.prevZ = p.prev;
  64422. p.nextZ = p.next;
  64423. p = p.next;
  64424. } while (p !== start);
  64425. p.prevZ.nextZ = null;
  64426. p.prevZ = null;
  64427. sortLinked(p);
  64428. }
  64429. // Simon Tatham's linked list merge sort algorithm
  64430. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  64431. function sortLinked(list) {
  64432. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  64433. do {
  64434. p = list;
  64435. list = null;
  64436. tail = null;
  64437. numMerges = 0;
  64438. while (p) {
  64439. numMerges++;
  64440. q = p;
  64441. pSize = 0;
  64442. for (i = 0; i < inSize; i++) {
  64443. pSize++;
  64444. q = q.nextZ;
  64445. if (!q)
  64446. break;
  64447. }
  64448. qSize = inSize;
  64449. while (pSize > 0 || (qSize > 0 && q)) {
  64450. if (pSize === 0) {
  64451. e = q;
  64452. q = q.nextZ;
  64453. qSize--;
  64454. }
  64455. else if (qSize === 0 || !q) {
  64456. e = p;
  64457. p = p.nextZ;
  64458. pSize--;
  64459. }
  64460. else if (p.z <= q.z) {
  64461. e = p;
  64462. p = p.nextZ;
  64463. pSize--;
  64464. }
  64465. else {
  64466. e = q;
  64467. q = q.nextZ;
  64468. qSize--;
  64469. }
  64470. if (tail)
  64471. tail.nextZ = e;
  64472. else
  64473. list = e;
  64474. e.prevZ = tail;
  64475. tail = e;
  64476. }
  64477. p = q;
  64478. }
  64479. tail.nextZ = null;
  64480. inSize *= 2;
  64481. } while (numMerges > 1);
  64482. return list;
  64483. }
  64484. // z-order of a point given coords and size of the data bounding box
  64485. function zOrder(x, y, minX, minY, size) {
  64486. // coords are transformed into non-negative 15-bit integer range
  64487. x = 32767 * (x - minX) / size;
  64488. y = 32767 * (y - minY) / size;
  64489. x = (x | (x << 8)) & 0x00FF00FF;
  64490. x = (x | (x << 4)) & 0x0F0F0F0F;
  64491. x = (x | (x << 2)) & 0x33333333;
  64492. x = (x | (x << 1)) & 0x55555555;
  64493. y = (y | (y << 8)) & 0x00FF00FF;
  64494. y = (y | (y << 4)) & 0x0F0F0F0F;
  64495. y = (y | (y << 2)) & 0x33333333;
  64496. y = (y | (y << 1)) & 0x55555555;
  64497. return x | (y << 1);
  64498. }
  64499. // find the leftmost node of a polygon ring
  64500. function getLeftmost(start) {
  64501. var p = start, leftmost = start;
  64502. do {
  64503. if (p.x < leftmost.x)
  64504. leftmost = p;
  64505. p = p.next;
  64506. } while (p !== start);
  64507. return leftmost;
  64508. }
  64509. // check if a point lies within a convex triangle
  64510. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  64511. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  64512. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  64513. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  64514. }
  64515. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  64516. function isValidDiagonal(a, b) {
  64517. return a.next.i !== b.i &&
  64518. a.prev.i !== b.i &&
  64519. !intersectsPolygon(a, b) &&
  64520. locallyInside(a, b) &&
  64521. locallyInside(b, a) &&
  64522. middleInside(a, b);
  64523. }
  64524. // signed area of a triangle
  64525. function area(p, q, r) {
  64526. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  64527. }
  64528. // check if two points are equal
  64529. function equals(p1, p2) {
  64530. return p1.x === p2.x && p1.y === p2.y;
  64531. }
  64532. // check if two segments intersect
  64533. function intersects(p1, q1, p2, q2) {
  64534. if ((equals(p1, q1) && equals(p2, q2)) ||
  64535. (equals(p1, q2) && equals(p2, q1)))
  64536. return true;
  64537. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  64538. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  64539. }
  64540. // check if a polygon diagonal intersects any polygon segments
  64541. function intersectsPolygon(a, b) {
  64542. var p = a;
  64543. do {
  64544. if (p.i !== a.i &&
  64545. p.next.i !== a.i &&
  64546. p.i !== b.i &&
  64547. p.next.i !== b.i &&
  64548. intersects(p, p.next, a, b))
  64549. return true;
  64550. p = p.next;
  64551. } while (p !== a);
  64552. return false;
  64553. }
  64554. // check if a polygon diagonal is locally inside the polygon
  64555. function locallyInside(a, b) {
  64556. return area(a.prev, a, a.next) < 0
  64557. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  64558. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  64559. }
  64560. // check if the middle point of a polygon diagonal is inside the polygon
  64561. function middleInside(a, b) {
  64562. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  64563. do {
  64564. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  64565. inside = !inside;
  64566. p = p.next;
  64567. } while (p !== a);
  64568. return inside;
  64569. }
  64570. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  64571. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  64572. function splitPolygon(a, b) {
  64573. 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;
  64574. a.next = b;
  64575. b.prev = a;
  64576. a2.next = an;
  64577. an.prev = a2;
  64578. b2.next = a2;
  64579. a2.prev = b2;
  64580. bp.next = b2;
  64581. b2.prev = bp;
  64582. return b2;
  64583. }
  64584. // create a node and optionally link it with previous one (in a circular doubly linked list)
  64585. function insertNode(i, x, y, last) {
  64586. var p = new Node(i, x, y);
  64587. if (!last) {
  64588. p.prev = p;
  64589. p.next = p;
  64590. }
  64591. else {
  64592. p.next = last.next;
  64593. p.prev = last;
  64594. last.next.prev = p;
  64595. last.next = p;
  64596. }
  64597. return p;
  64598. }
  64599. function removeNode(p) {
  64600. p.next.prev = p.prev;
  64601. p.prev.next = p.next;
  64602. if (p.prevZ)
  64603. p.prevZ.nextZ = p.nextZ;
  64604. if (p.nextZ)
  64605. p.nextZ.prevZ = p.prevZ;
  64606. }
  64607. /**
  64608. * return a percentage difference between the polygon area and its triangulation area;
  64609. * used to verify correctness of triangulation
  64610. */
  64611. function deviation(data, holeIndices, dim, triangles) {
  64612. var hasHoles = holeIndices && holeIndices.length;
  64613. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  64614. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  64615. if (hasHoles) {
  64616. for (var i = 0, len = holeIndices.length; i < len; i++) {
  64617. var start = holeIndices[i] * dim;
  64618. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64619. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  64620. }
  64621. }
  64622. var trianglesArea = 0;
  64623. for (i = 0; i < triangles.length; i += 3) {
  64624. var a = triangles[i] * dim;
  64625. var b = triangles[i + 1] * dim;
  64626. var c = triangles[i + 2] * dim;
  64627. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  64628. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  64629. }
  64630. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  64631. }
  64632. Earcut.deviation = deviation;
  64633. ;
  64634. function signedArea(data, start, end, dim) {
  64635. var sum = 0;
  64636. for (var i = start, j = end - dim; i < end; i += dim) {
  64637. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  64638. j = i;
  64639. }
  64640. return sum;
  64641. }
  64642. /**
  64643. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  64644. */
  64645. function flatten(data) {
  64646. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  64647. for (var i = 0; i < data.length; i++) {
  64648. for (var j = 0; j < data[i].length; j++) {
  64649. for (var d = 0; d < dim; d++)
  64650. result.vertices.push(data[i][j][d]);
  64651. }
  64652. if (i > 0) {
  64653. holeIndex += data[i - 1].length;
  64654. result.holes.push(holeIndex);
  64655. }
  64656. }
  64657. return result;
  64658. }
  64659. Earcut.flatten = flatten;
  64660. ;
  64661. })(Earcut || (Earcut = {}));
  64662. //# sourceMappingURL=babylon.earcut.js.map
  64663. var BABYLON;
  64664. (function (BABYLON) {
  64665. var IndexedVector2 = /** @class */ (function (_super) {
  64666. __extends(IndexedVector2, _super);
  64667. function IndexedVector2(original, index) {
  64668. var _this = _super.call(this, original.x, original.y) || this;
  64669. _this.index = index;
  64670. return _this;
  64671. }
  64672. return IndexedVector2;
  64673. }(BABYLON.Vector2));
  64674. var PolygonPoints = /** @class */ (function () {
  64675. function PolygonPoints() {
  64676. this.elements = new Array();
  64677. }
  64678. PolygonPoints.prototype.add = function (originalPoints) {
  64679. var _this = this;
  64680. var result = new Array();
  64681. originalPoints.forEach(function (point) {
  64682. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  64683. var newPoint = new IndexedVector2(point, _this.elements.length);
  64684. result.push(newPoint);
  64685. _this.elements.push(newPoint);
  64686. }
  64687. });
  64688. return result;
  64689. };
  64690. PolygonPoints.prototype.computeBounds = function () {
  64691. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64692. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64693. this.elements.forEach(function (point) {
  64694. // x
  64695. if (point.x < lmin.x) {
  64696. lmin.x = point.x;
  64697. }
  64698. else if (point.x > lmax.x) {
  64699. lmax.x = point.x;
  64700. }
  64701. // y
  64702. if (point.y < lmin.y) {
  64703. lmin.y = point.y;
  64704. }
  64705. else if (point.y > lmax.y) {
  64706. lmax.y = point.y;
  64707. }
  64708. });
  64709. return {
  64710. min: lmin,
  64711. max: lmax,
  64712. width: lmax.x - lmin.x,
  64713. height: lmax.y - lmin.y
  64714. };
  64715. };
  64716. return PolygonPoints;
  64717. }());
  64718. var Polygon = /** @class */ (function () {
  64719. function Polygon() {
  64720. }
  64721. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  64722. return [
  64723. new BABYLON.Vector2(xmin, ymin),
  64724. new BABYLON.Vector2(xmax, ymin),
  64725. new BABYLON.Vector2(xmax, ymax),
  64726. new BABYLON.Vector2(xmin, ymax)
  64727. ];
  64728. };
  64729. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  64730. if (cx === void 0) { cx = 0; }
  64731. if (cy === void 0) { cy = 0; }
  64732. if (numberOfSides === void 0) { numberOfSides = 32; }
  64733. var result = new Array();
  64734. var angle = 0;
  64735. var increment = (Math.PI * 2) / numberOfSides;
  64736. for (var i = 0; i < numberOfSides; i++) {
  64737. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  64738. angle -= increment;
  64739. }
  64740. return result;
  64741. };
  64742. Polygon.Parse = function (input) {
  64743. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  64744. var i, result = [];
  64745. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  64746. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  64747. }
  64748. return result;
  64749. };
  64750. Polygon.StartingAt = function (x, y) {
  64751. return BABYLON.Path2.StartingAt(x, y);
  64752. };
  64753. return Polygon;
  64754. }());
  64755. BABYLON.Polygon = Polygon;
  64756. var PolygonMeshBuilder = /** @class */ (function () {
  64757. function PolygonMeshBuilder(name, contours, scene) {
  64758. this._points = new PolygonPoints();
  64759. this._outlinepoints = new PolygonPoints();
  64760. this._holes = new Array();
  64761. this._epoints = new Array();
  64762. this._eholes = new Array();
  64763. this._name = name;
  64764. this._scene = scene;
  64765. var points;
  64766. if (contours instanceof BABYLON.Path2) {
  64767. points = contours.getPoints();
  64768. }
  64769. else {
  64770. points = contours;
  64771. }
  64772. this._addToepoint(points);
  64773. this._points.add(points);
  64774. this._outlinepoints.add(points);
  64775. }
  64776. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  64777. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  64778. var p = points_1[_i];
  64779. this._epoints.push(p.x, p.y);
  64780. }
  64781. };
  64782. PolygonMeshBuilder.prototype.addHole = function (hole) {
  64783. this._points.add(hole);
  64784. var holepoints = new PolygonPoints();
  64785. holepoints.add(hole);
  64786. this._holes.push(holepoints);
  64787. this._eholes.push(this._epoints.length / 2);
  64788. this._addToepoint(hole);
  64789. return this;
  64790. };
  64791. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  64792. var _this = this;
  64793. if (updatable === void 0) { updatable = false; }
  64794. if (depth === void 0) { depth = 0; }
  64795. var result = new BABYLON.Mesh(this._name, this._scene);
  64796. var normals = new Array();
  64797. var positions = new Array();
  64798. var uvs = new Array();
  64799. var bounds = this._points.computeBounds();
  64800. this._points.elements.forEach(function (p) {
  64801. normals.push(0, 1.0, 0);
  64802. positions.push(p.x, 0, p.y);
  64803. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  64804. });
  64805. var indices = new Array();
  64806. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  64807. for (var i = 0; i < res.length; i++) {
  64808. indices.push(res[i]);
  64809. }
  64810. if (depth > 0) {
  64811. var positionscount = (positions.length / 3); //get the current pointcount
  64812. this._points.elements.forEach(function (p) {
  64813. normals.push(0, -1.0, 0);
  64814. positions.push(p.x, -depth, p.y);
  64815. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  64816. });
  64817. var totalCount = indices.length;
  64818. for (var i = 0; i < totalCount; i += 3) {
  64819. var i0 = indices[i + 0];
  64820. var i1 = indices[i + 1];
  64821. var i2 = indices[i + 2];
  64822. indices.push(i2 + positionscount);
  64823. indices.push(i1 + positionscount);
  64824. indices.push(i0 + positionscount);
  64825. }
  64826. //Add the sides
  64827. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  64828. this._holes.forEach(function (hole) {
  64829. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  64830. });
  64831. }
  64832. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  64833. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  64834. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  64835. result.setIndices(indices);
  64836. return result;
  64837. };
  64838. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  64839. var StartIndex = positions.length / 3;
  64840. var ulength = 0;
  64841. for (var i = 0; i < points.elements.length; i++) {
  64842. var p = points.elements[i];
  64843. var p1;
  64844. if ((i + 1) > points.elements.length - 1) {
  64845. p1 = points.elements[0];
  64846. }
  64847. else {
  64848. p1 = points.elements[i + 1];
  64849. }
  64850. positions.push(p.x, 0, p.y);
  64851. positions.push(p.x, -depth, p.y);
  64852. positions.push(p1.x, 0, p1.y);
  64853. positions.push(p1.x, -depth, p1.y);
  64854. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  64855. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  64856. var v3 = v2.subtract(v1);
  64857. var v4 = new BABYLON.Vector3(0, 1, 0);
  64858. var vn = BABYLON.Vector3.Cross(v3, v4);
  64859. vn = vn.normalize();
  64860. uvs.push(ulength / bounds.width, 0);
  64861. uvs.push(ulength / bounds.width, 1);
  64862. ulength += v3.length();
  64863. uvs.push((ulength / bounds.width), 0);
  64864. uvs.push((ulength / bounds.width), 1);
  64865. if (!flip) {
  64866. normals.push(-vn.x, -vn.y, -vn.z);
  64867. normals.push(-vn.x, -vn.y, -vn.z);
  64868. normals.push(-vn.x, -vn.y, -vn.z);
  64869. normals.push(-vn.x, -vn.y, -vn.z);
  64870. indices.push(StartIndex);
  64871. indices.push(StartIndex + 1);
  64872. indices.push(StartIndex + 2);
  64873. indices.push(StartIndex + 1);
  64874. indices.push(StartIndex + 3);
  64875. indices.push(StartIndex + 2);
  64876. }
  64877. else {
  64878. normals.push(vn.x, vn.y, vn.z);
  64879. normals.push(vn.x, vn.y, vn.z);
  64880. normals.push(vn.x, vn.y, vn.z);
  64881. normals.push(vn.x, vn.y, vn.z);
  64882. indices.push(StartIndex);
  64883. indices.push(StartIndex + 2);
  64884. indices.push(StartIndex + 1);
  64885. indices.push(StartIndex + 1);
  64886. indices.push(StartIndex + 2);
  64887. indices.push(StartIndex + 3);
  64888. }
  64889. StartIndex += 4;
  64890. }
  64891. ;
  64892. };
  64893. return PolygonMeshBuilder;
  64894. }());
  64895. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  64896. })(BABYLON || (BABYLON = {}));
  64897. //# sourceMappingURL=babylon.polygonMesh.js.map
  64898. var BABYLON;
  64899. (function (BABYLON) {
  64900. // Unique ID when we import meshes from Babylon to CSG
  64901. var currentCSGMeshId = 0;
  64902. // # class Vertex
  64903. // Represents a vertex of a polygon. Use your own vertex class instead of this
  64904. // one to provide additional features like texture coordinates and vertex
  64905. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  64906. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  64907. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  64908. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  64909. // is not used anywhere else.
  64910. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  64911. var Vertex = /** @class */ (function () {
  64912. function Vertex(pos, normal, uv) {
  64913. this.pos = pos;
  64914. this.normal = normal;
  64915. this.uv = uv;
  64916. }
  64917. Vertex.prototype.clone = function () {
  64918. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  64919. };
  64920. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  64921. // orientation of a polygon is flipped.
  64922. Vertex.prototype.flip = function () {
  64923. this.normal = this.normal.scale(-1);
  64924. };
  64925. // Create a new vertex between this vertex and `other` by linearly
  64926. // interpolating all properties using a parameter of `t`. Subclasses should
  64927. // override this to interpolate additional properties.
  64928. Vertex.prototype.interpolate = function (other, t) {
  64929. 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));
  64930. };
  64931. return Vertex;
  64932. }());
  64933. // # class Plane
  64934. // Represents a plane in 3D space.
  64935. var Plane = /** @class */ (function () {
  64936. function Plane(normal, w) {
  64937. this.normal = normal;
  64938. this.w = w;
  64939. }
  64940. Plane.FromPoints = function (a, b, c) {
  64941. var v0 = c.subtract(a);
  64942. var v1 = b.subtract(a);
  64943. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  64944. return null;
  64945. }
  64946. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  64947. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  64948. };
  64949. Plane.prototype.clone = function () {
  64950. return new Plane(this.normal.clone(), this.w);
  64951. };
  64952. Plane.prototype.flip = function () {
  64953. this.normal.scaleInPlace(-1);
  64954. this.w = -this.w;
  64955. };
  64956. // Split `polygon` by this plane if needed, then put the polygon or polygon
  64957. // fragments in the appropriate lists. Coplanar polygons go into either
  64958. // `coplanarFront` or `coplanarBack` depending on their orientation with
  64959. // respect to this plane. Polygons in front or in back of this plane go into
  64960. // either `front` or `back`.
  64961. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  64962. var COPLANAR = 0;
  64963. var FRONT = 1;
  64964. var BACK = 2;
  64965. var SPANNING = 3;
  64966. // Classify each point as well as the entire polygon into one of the above
  64967. // four classes.
  64968. var polygonType = 0;
  64969. var types = [];
  64970. var i;
  64971. var t;
  64972. for (i = 0; i < polygon.vertices.length; i++) {
  64973. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  64974. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  64975. polygonType |= type;
  64976. types.push(type);
  64977. }
  64978. // Put the polygon in the correct list, splitting it when necessary.
  64979. switch (polygonType) {
  64980. case COPLANAR:
  64981. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  64982. break;
  64983. case FRONT:
  64984. front.push(polygon);
  64985. break;
  64986. case BACK:
  64987. back.push(polygon);
  64988. break;
  64989. case SPANNING:
  64990. var f = [], b = [];
  64991. for (i = 0; i < polygon.vertices.length; i++) {
  64992. var j = (i + 1) % polygon.vertices.length;
  64993. var ti = types[i], tj = types[j];
  64994. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  64995. if (ti !== BACK)
  64996. f.push(vi);
  64997. if (ti !== FRONT)
  64998. b.push(ti !== BACK ? vi.clone() : vi);
  64999. if ((ti | tj) === SPANNING) {
  65000. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  65001. var v = vi.interpolate(vj, t);
  65002. f.push(v);
  65003. b.push(v.clone());
  65004. }
  65005. }
  65006. var poly;
  65007. if (f.length >= 3) {
  65008. poly = new Polygon(f, polygon.shared);
  65009. if (poly.plane)
  65010. front.push(poly);
  65011. }
  65012. if (b.length >= 3) {
  65013. poly = new Polygon(b, polygon.shared);
  65014. if (poly.plane)
  65015. back.push(poly);
  65016. }
  65017. break;
  65018. }
  65019. };
  65020. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  65021. // point is on the plane.
  65022. Plane.EPSILON = 1e-5;
  65023. return Plane;
  65024. }());
  65025. // # class Polygon
  65026. // Represents a convex polygon. The vertices used to initialize a polygon must
  65027. // be coplanar and form a convex loop.
  65028. //
  65029. // Each convex polygon has a `shared` property, which is shared between all
  65030. // polygons that are clones of each other or were split from the same polygon.
  65031. // This can be used to define per-polygon properties (such as surface color).
  65032. var Polygon = /** @class */ (function () {
  65033. function Polygon(vertices, shared) {
  65034. this.vertices = vertices;
  65035. this.shared = shared;
  65036. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  65037. }
  65038. Polygon.prototype.clone = function () {
  65039. var vertices = this.vertices.map(function (v) { return v.clone(); });
  65040. return new Polygon(vertices, this.shared);
  65041. };
  65042. Polygon.prototype.flip = function () {
  65043. this.vertices.reverse().map(function (v) { v.flip(); });
  65044. this.plane.flip();
  65045. };
  65046. return Polygon;
  65047. }());
  65048. // # class Node
  65049. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  65050. // by picking a polygon to split along. That polygon (and all other coplanar
  65051. // polygons) are added directly to that node and the other polygons are added to
  65052. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  65053. // no distinction between internal and leaf nodes.
  65054. var Node = /** @class */ (function () {
  65055. function Node(polygons) {
  65056. this.plane = null;
  65057. this.front = null;
  65058. this.back = null;
  65059. this.polygons = new Array();
  65060. if (polygons) {
  65061. this.build(polygons);
  65062. }
  65063. }
  65064. Node.prototype.clone = function () {
  65065. var node = new Node();
  65066. node.plane = this.plane && this.plane.clone();
  65067. node.front = this.front && this.front.clone();
  65068. node.back = this.back && this.back.clone();
  65069. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  65070. return node;
  65071. };
  65072. // Convert solid space to empty space and empty space to solid space.
  65073. Node.prototype.invert = function () {
  65074. for (var i = 0; i < this.polygons.length; i++) {
  65075. this.polygons[i].flip();
  65076. }
  65077. if (this.plane) {
  65078. this.plane.flip();
  65079. }
  65080. if (this.front) {
  65081. this.front.invert();
  65082. }
  65083. if (this.back) {
  65084. this.back.invert();
  65085. }
  65086. var temp = this.front;
  65087. this.front = this.back;
  65088. this.back = temp;
  65089. };
  65090. // Recursively remove all polygons in `polygons` that are inside this BSP
  65091. // tree.
  65092. Node.prototype.clipPolygons = function (polygons) {
  65093. if (!this.plane)
  65094. return polygons.slice();
  65095. var front = new Array(), back = new Array();
  65096. for (var i = 0; i < polygons.length; i++) {
  65097. this.plane.splitPolygon(polygons[i], front, back, front, back);
  65098. }
  65099. if (this.front) {
  65100. front = this.front.clipPolygons(front);
  65101. }
  65102. if (this.back) {
  65103. back = this.back.clipPolygons(back);
  65104. }
  65105. else {
  65106. back = [];
  65107. }
  65108. return front.concat(back);
  65109. };
  65110. // Remove all polygons in this BSP tree that are inside the other BSP tree
  65111. // `bsp`.
  65112. Node.prototype.clipTo = function (bsp) {
  65113. this.polygons = bsp.clipPolygons(this.polygons);
  65114. if (this.front)
  65115. this.front.clipTo(bsp);
  65116. if (this.back)
  65117. this.back.clipTo(bsp);
  65118. };
  65119. // Return a list of all polygons in this BSP tree.
  65120. Node.prototype.allPolygons = function () {
  65121. var polygons = this.polygons.slice();
  65122. if (this.front)
  65123. polygons = polygons.concat(this.front.allPolygons());
  65124. if (this.back)
  65125. polygons = polygons.concat(this.back.allPolygons());
  65126. return polygons;
  65127. };
  65128. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  65129. // new polygons are filtered down to the bottom of the tree and become new
  65130. // nodes there. Each set of polygons is partitioned using the first polygon
  65131. // (no heuristic is used to pick a good split).
  65132. Node.prototype.build = function (polygons) {
  65133. if (!polygons.length)
  65134. return;
  65135. if (!this.plane)
  65136. this.plane = polygons[0].plane.clone();
  65137. var front = new Array(), back = new Array();
  65138. for (var i = 0; i < polygons.length; i++) {
  65139. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  65140. }
  65141. if (front.length) {
  65142. if (!this.front)
  65143. this.front = new Node();
  65144. this.front.build(front);
  65145. }
  65146. if (back.length) {
  65147. if (!this.back)
  65148. this.back = new Node();
  65149. this.back.build(back);
  65150. }
  65151. };
  65152. return Node;
  65153. }());
  65154. var CSG = /** @class */ (function () {
  65155. function CSG() {
  65156. this.polygons = new Array();
  65157. }
  65158. // Convert BABYLON.Mesh to BABYLON.CSG
  65159. CSG.FromMesh = function (mesh) {
  65160. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  65161. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  65162. if (mesh instanceof BABYLON.Mesh) {
  65163. mesh.computeWorldMatrix(true);
  65164. matrix = mesh.getWorldMatrix();
  65165. meshPosition = mesh.position.clone();
  65166. meshRotation = mesh.rotation.clone();
  65167. if (mesh.rotationQuaternion) {
  65168. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  65169. }
  65170. meshScaling = mesh.scaling.clone();
  65171. }
  65172. else {
  65173. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  65174. }
  65175. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65176. var subMeshes = mesh.subMeshes;
  65177. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  65178. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  65179. vertices = [];
  65180. for (var j = 0; j < 3; j++) {
  65181. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  65182. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  65183. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  65184. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  65185. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  65186. vertex = new Vertex(position, normal, uv);
  65187. vertices.push(vertex);
  65188. }
  65189. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  65190. // To handle the case of degenerated triangle
  65191. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  65192. if (polygon.plane)
  65193. polygons.push(polygon);
  65194. }
  65195. }
  65196. var csg = CSG.FromPolygons(polygons);
  65197. csg.matrix = matrix;
  65198. csg.position = meshPosition;
  65199. csg.rotation = meshRotation;
  65200. csg.scaling = meshScaling;
  65201. csg.rotationQuaternion = meshRotationQuaternion;
  65202. currentCSGMeshId++;
  65203. return csg;
  65204. };
  65205. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  65206. CSG.FromPolygons = function (polygons) {
  65207. var csg = new CSG();
  65208. csg.polygons = polygons;
  65209. return csg;
  65210. };
  65211. CSG.prototype.clone = function () {
  65212. var csg = new CSG();
  65213. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  65214. csg.copyTransformAttributes(this);
  65215. return csg;
  65216. };
  65217. CSG.prototype.union = function (csg) {
  65218. var a = new Node(this.clone().polygons);
  65219. var b = new Node(csg.clone().polygons);
  65220. a.clipTo(b);
  65221. b.clipTo(a);
  65222. b.invert();
  65223. b.clipTo(a);
  65224. b.invert();
  65225. a.build(b.allPolygons());
  65226. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65227. };
  65228. CSG.prototype.unionInPlace = function (csg) {
  65229. var a = new Node(this.polygons);
  65230. var b = new Node(csg.polygons);
  65231. a.clipTo(b);
  65232. b.clipTo(a);
  65233. b.invert();
  65234. b.clipTo(a);
  65235. b.invert();
  65236. a.build(b.allPolygons());
  65237. this.polygons = a.allPolygons();
  65238. };
  65239. CSG.prototype.subtract = function (csg) {
  65240. var a = new Node(this.clone().polygons);
  65241. var b = new Node(csg.clone().polygons);
  65242. a.invert();
  65243. a.clipTo(b);
  65244. b.clipTo(a);
  65245. b.invert();
  65246. b.clipTo(a);
  65247. b.invert();
  65248. a.build(b.allPolygons());
  65249. a.invert();
  65250. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65251. };
  65252. CSG.prototype.subtractInPlace = function (csg) {
  65253. var a = new Node(this.polygons);
  65254. var b = new Node(csg.polygons);
  65255. a.invert();
  65256. a.clipTo(b);
  65257. b.clipTo(a);
  65258. b.invert();
  65259. b.clipTo(a);
  65260. b.invert();
  65261. a.build(b.allPolygons());
  65262. a.invert();
  65263. this.polygons = a.allPolygons();
  65264. };
  65265. CSG.prototype.intersect = function (csg) {
  65266. var a = new Node(this.clone().polygons);
  65267. var b = new Node(csg.clone().polygons);
  65268. a.invert();
  65269. b.clipTo(a);
  65270. b.invert();
  65271. a.clipTo(b);
  65272. b.clipTo(a);
  65273. a.build(b.allPolygons());
  65274. a.invert();
  65275. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  65276. };
  65277. CSG.prototype.intersectInPlace = function (csg) {
  65278. var a = new Node(this.polygons);
  65279. var b = new Node(csg.polygons);
  65280. a.invert();
  65281. b.clipTo(a);
  65282. b.invert();
  65283. a.clipTo(b);
  65284. b.clipTo(a);
  65285. a.build(b.allPolygons());
  65286. a.invert();
  65287. this.polygons = a.allPolygons();
  65288. };
  65289. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  65290. // not modified.
  65291. CSG.prototype.inverse = function () {
  65292. var csg = this.clone();
  65293. csg.inverseInPlace();
  65294. return csg;
  65295. };
  65296. CSG.prototype.inverseInPlace = function () {
  65297. this.polygons.map(function (p) { p.flip(); });
  65298. };
  65299. // This is used to keep meshes transformations so they can be restored
  65300. // when we build back a Babylon Mesh
  65301. // NB : All CSG operations are performed in world coordinates
  65302. CSG.prototype.copyTransformAttributes = function (csg) {
  65303. this.matrix = csg.matrix;
  65304. this.position = csg.position;
  65305. this.rotation = csg.rotation;
  65306. this.scaling = csg.scaling;
  65307. this.rotationQuaternion = csg.rotationQuaternion;
  65308. return this;
  65309. };
  65310. // Build Raw mesh from CSG
  65311. // Coordinates here are in world space
  65312. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  65313. var matrix = this.matrix.clone();
  65314. matrix.invert();
  65315. 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;
  65316. if (keepSubMeshes) {
  65317. // Sort Polygons, since subMeshes are indices range
  65318. polygons.sort(function (a, b) {
  65319. if (a.shared.meshId === b.shared.meshId) {
  65320. return a.shared.subMeshId - b.shared.subMeshId;
  65321. }
  65322. else {
  65323. return a.shared.meshId - b.shared.meshId;
  65324. }
  65325. });
  65326. }
  65327. for (var i = 0, il = polygons.length; i < il; i++) {
  65328. polygon = polygons[i];
  65329. // Building SubMeshes
  65330. if (!subMesh_dict[polygon.shared.meshId]) {
  65331. subMesh_dict[polygon.shared.meshId] = {};
  65332. }
  65333. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  65334. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  65335. indexStart: +Infinity,
  65336. indexEnd: -Infinity,
  65337. materialIndex: polygon.shared.materialIndex
  65338. };
  65339. }
  65340. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  65341. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  65342. polygonIndices[0] = 0;
  65343. polygonIndices[1] = j - 1;
  65344. polygonIndices[2] = j;
  65345. for (var k = 0; k < 3; k++) {
  65346. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  65347. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  65348. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  65349. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  65350. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  65351. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  65352. // Check if 2 points can be merged
  65353. if (!(typeof vertex_idx !== 'undefined' &&
  65354. normals[vertex_idx * 3] === localNormal.x &&
  65355. normals[vertex_idx * 3 + 1] === localNormal.y &&
  65356. normals[vertex_idx * 3 + 2] === localNormal.z &&
  65357. uvs[vertex_idx * 2] === uv.x &&
  65358. uvs[vertex_idx * 2 + 1] === uv.y)) {
  65359. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  65360. uvs.push(uv.x, uv.y);
  65361. normals.push(normal.x, normal.y, normal.z);
  65362. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  65363. }
  65364. indices.push(vertex_idx);
  65365. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  65366. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  65367. currentIndex++;
  65368. }
  65369. }
  65370. }
  65371. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  65372. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  65373. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  65374. mesh.setIndices(indices, null);
  65375. if (keepSubMeshes) {
  65376. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  65377. var materialIndexOffset = 0, materialMaxIndex;
  65378. mesh.subMeshes = new Array();
  65379. for (var m in subMesh_dict) {
  65380. materialMaxIndex = -1;
  65381. for (var sm in subMesh_dict[m]) {
  65382. subMesh_obj = subMesh_dict[m][sm];
  65383. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  65384. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  65385. }
  65386. materialIndexOffset += ++materialMaxIndex;
  65387. }
  65388. }
  65389. return mesh;
  65390. };
  65391. // Build Mesh from CSG taking material and transforms into account
  65392. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  65393. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  65394. mesh.material = material;
  65395. mesh.position.copyFrom(this.position);
  65396. mesh.rotation.copyFrom(this.rotation);
  65397. if (this.rotationQuaternion) {
  65398. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  65399. }
  65400. mesh.scaling.copyFrom(this.scaling);
  65401. mesh.computeWorldMatrix(true);
  65402. return mesh;
  65403. };
  65404. return CSG;
  65405. }());
  65406. BABYLON.CSG = CSG;
  65407. })(BABYLON || (BABYLON = {}));
  65408. //# sourceMappingURL=babylon.csg.js.map
  65409. var BABYLON;
  65410. (function (BABYLON) {
  65411. var LensFlare = /** @class */ (function () {
  65412. function LensFlare(size, position, color, imgUrl, system) {
  65413. this.size = size;
  65414. this.position = position;
  65415. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  65416. this.color = color || new BABYLON.Color3(1, 1, 1);
  65417. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  65418. this._system = system;
  65419. system.lensFlares.push(this);
  65420. }
  65421. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  65422. return new LensFlare(size, position, color, imgUrl, system);
  65423. };
  65424. LensFlare.prototype.dispose = function () {
  65425. if (this.texture) {
  65426. this.texture.dispose();
  65427. }
  65428. // Remove from scene
  65429. var index = this._system.lensFlares.indexOf(this);
  65430. this._system.lensFlares.splice(index, 1);
  65431. };
  65432. ;
  65433. return LensFlare;
  65434. }());
  65435. BABYLON.LensFlare = LensFlare;
  65436. })(BABYLON || (BABYLON = {}));
  65437. //# sourceMappingURL=babylon.lensFlare.js.map
  65438. var BABYLON;
  65439. (function (BABYLON) {
  65440. var LensFlareSystem = /** @class */ (function () {
  65441. function LensFlareSystem(name, emitter, scene) {
  65442. this.name = name;
  65443. this.lensFlares = new Array();
  65444. this.borderLimit = 300;
  65445. this.viewportBorder = 0;
  65446. this.layerMask = 0x0FFFFFFF;
  65447. this._vertexBuffers = {};
  65448. this._isEnabled = true;
  65449. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65450. this._emitter = emitter;
  65451. this.id = name;
  65452. scene.lensFlareSystems.push(this);
  65453. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  65454. var engine = scene.getEngine();
  65455. // VBO
  65456. var vertices = [];
  65457. vertices.push(1, 1);
  65458. vertices.push(-1, 1);
  65459. vertices.push(-1, -1);
  65460. vertices.push(1, -1);
  65461. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65462. // Indices
  65463. var indices = [];
  65464. indices.push(0);
  65465. indices.push(1);
  65466. indices.push(2);
  65467. indices.push(0);
  65468. indices.push(2);
  65469. indices.push(3);
  65470. this._indexBuffer = engine.createIndexBuffer(indices);
  65471. // Effects
  65472. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  65473. }
  65474. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  65475. get: function () {
  65476. return this._isEnabled;
  65477. },
  65478. set: function (value) {
  65479. this._isEnabled = value;
  65480. },
  65481. enumerable: true,
  65482. configurable: true
  65483. });
  65484. LensFlareSystem.prototype.getScene = function () {
  65485. return this._scene;
  65486. };
  65487. LensFlareSystem.prototype.getEmitter = function () {
  65488. return this._emitter;
  65489. };
  65490. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  65491. this._emitter = newEmitter;
  65492. };
  65493. LensFlareSystem.prototype.getEmitterPosition = function () {
  65494. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  65495. };
  65496. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  65497. var position = this.getEmitterPosition();
  65498. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  65499. this._positionX = position.x;
  65500. this._positionY = position.y;
  65501. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  65502. if (this.viewportBorder > 0) {
  65503. globalViewport.x -= this.viewportBorder;
  65504. globalViewport.y -= this.viewportBorder;
  65505. globalViewport.width += this.viewportBorder * 2;
  65506. globalViewport.height += this.viewportBorder * 2;
  65507. position.x += this.viewportBorder;
  65508. position.y += this.viewportBorder;
  65509. this._positionX += this.viewportBorder;
  65510. this._positionY += this.viewportBorder;
  65511. }
  65512. if (position.z > 0) {
  65513. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  65514. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  65515. return true;
  65516. }
  65517. return true;
  65518. }
  65519. return false;
  65520. };
  65521. LensFlareSystem.prototype._isVisible = function () {
  65522. if (!this._isEnabled || !this._scene.activeCamera) {
  65523. return false;
  65524. }
  65525. var emitterPosition = this.getEmitterPosition();
  65526. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  65527. var distance = direction.length();
  65528. direction.normalize();
  65529. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  65530. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  65531. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  65532. };
  65533. LensFlareSystem.prototype.render = function () {
  65534. if (!this._effect.isReady() || !this._scene.activeCamera)
  65535. return false;
  65536. var engine = this._scene.getEngine();
  65537. var viewport = this._scene.activeCamera.viewport;
  65538. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  65539. // Position
  65540. if (!this.computeEffectivePosition(globalViewport)) {
  65541. return false;
  65542. }
  65543. // Visibility
  65544. if (!this._isVisible()) {
  65545. return false;
  65546. }
  65547. // Intensity
  65548. var awayX;
  65549. var awayY;
  65550. if (this._positionX < this.borderLimit + globalViewport.x) {
  65551. awayX = this.borderLimit + globalViewport.x - this._positionX;
  65552. }
  65553. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  65554. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  65555. }
  65556. else {
  65557. awayX = 0;
  65558. }
  65559. if (this._positionY < this.borderLimit + globalViewport.y) {
  65560. awayY = this.borderLimit + globalViewport.y - this._positionY;
  65561. }
  65562. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  65563. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  65564. }
  65565. else {
  65566. awayY = 0;
  65567. }
  65568. var away = (awayX > awayY) ? awayX : awayY;
  65569. away -= this.viewportBorder;
  65570. if (away > this.borderLimit) {
  65571. away = this.borderLimit;
  65572. }
  65573. var intensity = 1.0 - (away / this.borderLimit);
  65574. if (intensity < 0) {
  65575. return false;
  65576. }
  65577. if (intensity > 1.0) {
  65578. intensity = 1.0;
  65579. }
  65580. if (this.viewportBorder > 0) {
  65581. globalViewport.x += this.viewportBorder;
  65582. globalViewport.y += this.viewportBorder;
  65583. globalViewport.width -= this.viewportBorder * 2;
  65584. globalViewport.height -= this.viewportBorder * 2;
  65585. this._positionX -= this.viewportBorder;
  65586. this._positionY -= this.viewportBorder;
  65587. }
  65588. // Position
  65589. var centerX = globalViewport.x + globalViewport.width / 2;
  65590. var centerY = globalViewport.y + globalViewport.height / 2;
  65591. var distX = centerX - this._positionX;
  65592. var distY = centerY - this._positionY;
  65593. // Effects
  65594. engine.enableEffect(this._effect);
  65595. engine.setState(false);
  65596. engine.setDepthBuffer(false);
  65597. // VBOs
  65598. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65599. // Flares
  65600. for (var index = 0; index < this.lensFlares.length; index++) {
  65601. var flare = this.lensFlares[index];
  65602. engine.setAlphaMode(flare.alphaMode);
  65603. var x = centerX - (distX * flare.position);
  65604. var y = centerY - (distY * flare.position);
  65605. var cw = flare.size;
  65606. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  65607. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  65608. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  65609. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  65610. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  65611. // Texture
  65612. this._effect.setTexture("textureSampler", flare.texture);
  65613. // Color
  65614. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  65615. // Draw order
  65616. engine.draw(true, 0, 6);
  65617. }
  65618. engine.setDepthBuffer(true);
  65619. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65620. return true;
  65621. };
  65622. LensFlareSystem.prototype.dispose = function () {
  65623. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65624. if (vertexBuffer) {
  65625. vertexBuffer.dispose();
  65626. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65627. }
  65628. if (this._indexBuffer) {
  65629. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65630. this._indexBuffer = null;
  65631. }
  65632. while (this.lensFlares.length) {
  65633. this.lensFlares[0].dispose();
  65634. }
  65635. // Remove from scene
  65636. var index = this._scene.lensFlareSystems.indexOf(this);
  65637. this._scene.lensFlareSystems.splice(index, 1);
  65638. };
  65639. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  65640. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  65641. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  65642. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  65643. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  65644. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  65645. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  65646. var parsedFlare = parsedLensFlareSystem.flares[index];
  65647. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  65648. }
  65649. return lensFlareSystem;
  65650. };
  65651. LensFlareSystem.prototype.serialize = function () {
  65652. var serializationObject = {};
  65653. serializationObject.id = this.id;
  65654. serializationObject.name = this.name;
  65655. serializationObject.emitterId = this.getEmitter().id;
  65656. serializationObject.borderLimit = this.borderLimit;
  65657. serializationObject.flares = [];
  65658. for (var index = 0; index < this.lensFlares.length; index++) {
  65659. var flare = this.lensFlares[index];
  65660. serializationObject.flares.push({
  65661. size: flare.size,
  65662. position: flare.position,
  65663. color: flare.color.asArray(),
  65664. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  65665. });
  65666. }
  65667. return serializationObject;
  65668. };
  65669. return LensFlareSystem;
  65670. }());
  65671. BABYLON.LensFlareSystem = LensFlareSystem;
  65672. })(BABYLON || (BABYLON = {}));
  65673. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  65674. var BABYLON;
  65675. (function (BABYLON) {
  65676. /**
  65677. * This is a holder class for the physics joint created by the physics plugin.
  65678. * It holds a set of functions to control the underlying joint.
  65679. */
  65680. var PhysicsJoint = /** @class */ (function () {
  65681. function PhysicsJoint(type, jointData) {
  65682. this.type = type;
  65683. this.jointData = jointData;
  65684. jointData.nativeParams = jointData.nativeParams || {};
  65685. }
  65686. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  65687. get: function () {
  65688. return this._physicsJoint;
  65689. },
  65690. set: function (newJoint) {
  65691. if (this._physicsJoint) {
  65692. //remove from the wolrd
  65693. }
  65694. this._physicsJoint = newJoint;
  65695. },
  65696. enumerable: true,
  65697. configurable: true
  65698. });
  65699. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  65700. set: function (physicsPlugin) {
  65701. this._physicsPlugin = physicsPlugin;
  65702. },
  65703. enumerable: true,
  65704. configurable: true
  65705. });
  65706. /**
  65707. * Execute a function that is physics-plugin specific.
  65708. * @param {Function} func the function that will be executed.
  65709. * It accepts two parameters: the physics world and the physics joint.
  65710. */
  65711. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  65712. func(this._physicsPlugin.world, this._physicsJoint);
  65713. };
  65714. //TODO check if the native joints are the same
  65715. //Joint Types
  65716. PhysicsJoint.DistanceJoint = 0;
  65717. PhysicsJoint.HingeJoint = 1;
  65718. PhysicsJoint.BallAndSocketJoint = 2;
  65719. PhysicsJoint.WheelJoint = 3;
  65720. PhysicsJoint.SliderJoint = 4;
  65721. //OIMO
  65722. PhysicsJoint.PrismaticJoint = 5;
  65723. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  65724. PhysicsJoint.UniversalJoint = 6;
  65725. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  65726. //Cannon
  65727. //Similar to a Ball-Joint. Different in params
  65728. PhysicsJoint.PointToPointJoint = 8;
  65729. //Cannon only at the moment
  65730. PhysicsJoint.SpringJoint = 9;
  65731. PhysicsJoint.LockJoint = 10;
  65732. return PhysicsJoint;
  65733. }());
  65734. BABYLON.PhysicsJoint = PhysicsJoint;
  65735. /**
  65736. * A class representing a physics distance joint.
  65737. */
  65738. var DistanceJoint = /** @class */ (function (_super) {
  65739. __extends(DistanceJoint, _super);
  65740. function DistanceJoint(jointData) {
  65741. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  65742. }
  65743. /**
  65744. * Update the predefined distance.
  65745. */
  65746. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  65747. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  65748. };
  65749. return DistanceJoint;
  65750. }(PhysicsJoint));
  65751. BABYLON.DistanceJoint = DistanceJoint;
  65752. var MotorEnabledJoint = /** @class */ (function (_super) {
  65753. __extends(MotorEnabledJoint, _super);
  65754. function MotorEnabledJoint(type, jointData) {
  65755. return _super.call(this, type, jointData) || this;
  65756. }
  65757. /**
  65758. * Set the motor values.
  65759. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65760. * @param {number} force the force to apply
  65761. * @param {number} maxForce max force for this motor.
  65762. */
  65763. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  65764. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65765. };
  65766. /**
  65767. * Set the motor's limits.
  65768. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65769. */
  65770. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65771. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65772. };
  65773. return MotorEnabledJoint;
  65774. }(PhysicsJoint));
  65775. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  65776. /**
  65777. * This class represents a single hinge physics joint
  65778. */
  65779. var HingeJoint = /** @class */ (function (_super) {
  65780. __extends(HingeJoint, _super);
  65781. function HingeJoint(jointData) {
  65782. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  65783. }
  65784. /**
  65785. * Set the motor values.
  65786. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65787. * @param {number} force the force to apply
  65788. * @param {number} maxForce max force for this motor.
  65789. */
  65790. HingeJoint.prototype.setMotor = function (force, maxForce) {
  65791. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65792. };
  65793. /**
  65794. * Set the motor's limits.
  65795. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65796. */
  65797. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65798. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65799. };
  65800. return HingeJoint;
  65801. }(MotorEnabledJoint));
  65802. BABYLON.HingeJoint = HingeJoint;
  65803. /**
  65804. * This class represents a dual hinge physics joint (same as wheel joint)
  65805. */
  65806. var Hinge2Joint = /** @class */ (function (_super) {
  65807. __extends(Hinge2Joint, _super);
  65808. function Hinge2Joint(jointData) {
  65809. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  65810. }
  65811. /**
  65812. * Set the motor values.
  65813. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65814. * @param {number} force the force to apply
  65815. * @param {number} maxForce max force for this motor.
  65816. * @param {motorIndex} the motor's index, 0 or 1.
  65817. */
  65818. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  65819. if (motorIndex === void 0) { motorIndex = 0; }
  65820. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  65821. };
  65822. /**
  65823. * Set the motor limits.
  65824. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65825. * @param {number} upperLimit the upper limit
  65826. * @param {number} lowerLimit lower limit
  65827. * @param {motorIndex} the motor's index, 0 or 1.
  65828. */
  65829. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  65830. if (motorIndex === void 0) { motorIndex = 0; }
  65831. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  65832. };
  65833. return Hinge2Joint;
  65834. }(MotorEnabledJoint));
  65835. BABYLON.Hinge2Joint = Hinge2Joint;
  65836. })(BABYLON || (BABYLON = {}));
  65837. //# sourceMappingURL=babylon.physicsJoint.js.map
  65838. var BABYLON;
  65839. (function (BABYLON) {
  65840. var PhysicsImpostor = /** @class */ (function () {
  65841. function PhysicsImpostor(object, type, _options, _scene) {
  65842. if (_options === void 0) { _options = { mass: 0 }; }
  65843. var _this = this;
  65844. this.object = object;
  65845. this.type = type;
  65846. this._options = _options;
  65847. this._scene = _scene;
  65848. this._bodyUpdateRequired = false;
  65849. this._onBeforePhysicsStepCallbacks = new Array();
  65850. this._onAfterPhysicsStepCallbacks = new Array();
  65851. this._onPhysicsCollideCallbacks = [];
  65852. this._deltaPosition = BABYLON.Vector3.Zero();
  65853. this._isDisposed = false;
  65854. //temp variables for parent rotation calculations
  65855. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  65856. this._tmpQuat = new BABYLON.Quaternion();
  65857. this._tmpQuat2 = new BABYLON.Quaternion();
  65858. /**
  65859. * this function is executed by the physics engine.
  65860. */
  65861. this.beforeStep = function () {
  65862. if (!_this._physicsEngine) {
  65863. return;
  65864. }
  65865. _this.object.translate(_this._deltaPosition, -1);
  65866. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  65867. _this.object.computeWorldMatrix(false);
  65868. if (_this.object.parent && _this.object.rotationQuaternion) {
  65869. _this.getParentsRotation();
  65870. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  65871. }
  65872. else {
  65873. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  65874. }
  65875. if (!_this._options.disableBidirectionalTransformation) {
  65876. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  65877. }
  65878. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  65879. func(_this);
  65880. });
  65881. };
  65882. /**
  65883. * this function is executed by the physics engine.
  65884. */
  65885. this.afterStep = function () {
  65886. if (!_this._physicsEngine) {
  65887. return;
  65888. }
  65889. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  65890. func(_this);
  65891. });
  65892. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  65893. // object has now its world rotation. needs to be converted to local.
  65894. if (_this.object.parent && _this.object.rotationQuaternion) {
  65895. _this.getParentsRotation();
  65896. _this._tmpQuat.conjugateInPlace();
  65897. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  65898. }
  65899. // take the position set and make it the absolute position of this object.
  65900. _this.object.setAbsolutePosition(_this.object.position);
  65901. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  65902. _this.object.translate(_this._deltaPosition, 1);
  65903. };
  65904. /**
  65905. * Legacy collision detection event support
  65906. */
  65907. this.onCollideEvent = null;
  65908. //event and body object due to cannon's event-based architecture.
  65909. this.onCollide = function (e) {
  65910. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  65911. return;
  65912. }
  65913. if (!_this._physicsEngine) {
  65914. return;
  65915. }
  65916. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  65917. if (otherImpostor) {
  65918. // Legacy collision detection event support
  65919. if (_this.onCollideEvent) {
  65920. _this.onCollideEvent(_this, otherImpostor);
  65921. }
  65922. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  65923. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  65924. }).forEach(function (obj) {
  65925. obj.callback(_this, otherImpostor);
  65926. });
  65927. }
  65928. };
  65929. //sanity check!
  65930. if (!this.object) {
  65931. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  65932. return;
  65933. }
  65934. //legacy support for old syntax.
  65935. if (!this._scene && object.getScene) {
  65936. this._scene = object.getScene();
  65937. }
  65938. if (!this._scene) {
  65939. return;
  65940. }
  65941. this._physicsEngine = this._scene.getPhysicsEngine();
  65942. if (!this._physicsEngine) {
  65943. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  65944. }
  65945. else {
  65946. //set the object's quaternion, if not set
  65947. if (!this.object.rotationQuaternion) {
  65948. if (this.object.rotation) {
  65949. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  65950. }
  65951. else {
  65952. this.object.rotationQuaternion = new BABYLON.Quaternion();
  65953. }
  65954. }
  65955. //default options params
  65956. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  65957. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  65958. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  65959. this._joints = [];
  65960. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  65961. if (!this.object.parent || this._options.ignoreParent) {
  65962. this._init();
  65963. }
  65964. else if (this.object.parent.physicsImpostor) {
  65965. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  65966. }
  65967. }
  65968. }
  65969. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  65970. get: function () {
  65971. return this._isDisposed;
  65972. },
  65973. enumerable: true,
  65974. configurable: true
  65975. });
  65976. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  65977. get: function () {
  65978. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  65979. },
  65980. set: function (value) {
  65981. this.setMass(value);
  65982. },
  65983. enumerable: true,
  65984. configurable: true
  65985. });
  65986. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  65987. get: function () {
  65988. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  65989. },
  65990. set: function (value) {
  65991. if (!this._physicsEngine) {
  65992. return;
  65993. }
  65994. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  65995. },
  65996. enumerable: true,
  65997. configurable: true
  65998. });
  65999. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  66000. get: function () {
  66001. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  66002. },
  66003. set: function (value) {
  66004. if (!this._physicsEngine) {
  66005. return;
  66006. }
  66007. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  66008. },
  66009. enumerable: true,
  66010. configurable: true
  66011. });
  66012. /**
  66013. * This function will completly initialize this impostor.
  66014. * It will create a new body - but only if this mesh has no parent.
  66015. * If it has, this impostor will not be used other than to define the impostor
  66016. * of the child mesh.
  66017. */
  66018. PhysicsImpostor.prototype._init = function () {
  66019. if (!this._physicsEngine) {
  66020. return;
  66021. }
  66022. this._physicsEngine.removeImpostor(this);
  66023. this.physicsBody = null;
  66024. this._parent = this._parent || this._getPhysicsParent();
  66025. if (!this.parent || this._options.ignoreParent) {
  66026. this._physicsEngine.addImpostor(this);
  66027. }
  66028. };
  66029. PhysicsImpostor.prototype._getPhysicsParent = function () {
  66030. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  66031. var parentMesh = this.object.parent;
  66032. return parentMesh.physicsImpostor;
  66033. }
  66034. return null;
  66035. };
  66036. /**
  66037. * Should a new body be generated.
  66038. */
  66039. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  66040. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  66041. };
  66042. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  66043. this.forceUpdate();
  66044. };
  66045. /**
  66046. * Force a regeneration of this or the parent's impostor's body.
  66047. * Use under cautious - This will remove all joints already implemented.
  66048. */
  66049. PhysicsImpostor.prototype.forceUpdate = function () {
  66050. this._init();
  66051. if (this.parent && !this._options.ignoreParent) {
  66052. this.parent.forceUpdate();
  66053. }
  66054. };
  66055. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  66056. /*public get mesh(): AbstractMesh {
  66057. return this._mesh;
  66058. }*/
  66059. /**
  66060. * Gets the body that holds this impostor. Either its own, or its parent.
  66061. */
  66062. get: function () {
  66063. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  66064. },
  66065. /**
  66066. * Set the physics body. Used mainly by the physics engine/plugin
  66067. */
  66068. set: function (physicsBody) {
  66069. if (this._physicsBody && this._physicsEngine) {
  66070. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  66071. }
  66072. this._physicsBody = physicsBody;
  66073. this.resetUpdateFlags();
  66074. },
  66075. enumerable: true,
  66076. configurable: true
  66077. });
  66078. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  66079. get: function () {
  66080. return !this._options.ignoreParent && this._parent ? this._parent : null;
  66081. },
  66082. set: function (value) {
  66083. this._parent = value;
  66084. },
  66085. enumerable: true,
  66086. configurable: true
  66087. });
  66088. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  66089. this._bodyUpdateRequired = false;
  66090. };
  66091. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  66092. if (this.object.getBoundingInfo) {
  66093. var q = this.object.rotationQuaternion;
  66094. //reset rotation
  66095. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  66096. //calculate the world matrix with no rotation
  66097. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66098. var boundingInfo = this.object.getBoundingInfo();
  66099. var size = void 0;
  66100. if (boundingInfo) {
  66101. size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  66102. }
  66103. else {
  66104. size = BABYLON.Vector3.Zero();
  66105. }
  66106. //bring back the rotation
  66107. this.object.rotationQuaternion = q;
  66108. //calculate the world matrix with the new rotation
  66109. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  66110. return size;
  66111. }
  66112. else {
  66113. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  66114. }
  66115. };
  66116. PhysicsImpostor.prototype.getObjectCenter = function () {
  66117. if (this.object.getBoundingInfo) {
  66118. var boundingInfo = this.object.getBoundingInfo();
  66119. if (!boundingInfo) {
  66120. return this.object.position;
  66121. }
  66122. return boundingInfo.boundingBox.centerWorld;
  66123. }
  66124. else {
  66125. return this.object.position;
  66126. }
  66127. };
  66128. /**
  66129. * Get a specific parametes from the options parameter.
  66130. */
  66131. PhysicsImpostor.prototype.getParam = function (paramName) {
  66132. return this._options[paramName];
  66133. };
  66134. /**
  66135. * Sets a specific parameter in the options given to the physics plugin
  66136. */
  66137. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  66138. this._options[paramName] = value;
  66139. this._bodyUpdateRequired = true;
  66140. };
  66141. /**
  66142. * Specifically change the body's mass option. Won't recreate the physics body object
  66143. */
  66144. PhysicsImpostor.prototype.setMass = function (mass) {
  66145. if (this.getParam("mass") !== mass) {
  66146. this.setParam("mass", mass);
  66147. }
  66148. if (this._physicsEngine) {
  66149. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  66150. }
  66151. };
  66152. PhysicsImpostor.prototype.getLinearVelocity = function () {
  66153. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  66154. };
  66155. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  66156. if (this._physicsEngine) {
  66157. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  66158. }
  66159. };
  66160. PhysicsImpostor.prototype.getAngularVelocity = function () {
  66161. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  66162. };
  66163. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  66164. if (this._physicsEngine) {
  66165. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  66166. }
  66167. };
  66168. /**
  66169. * Execute a function with the physics plugin native code.
  66170. * Provide a function the will have two variables - the world object and the physics body object.
  66171. */
  66172. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  66173. if (this._physicsEngine) {
  66174. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  66175. }
  66176. };
  66177. /**
  66178. * Register a function that will be executed before the physics world is stepping forward.
  66179. */
  66180. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  66181. this._onBeforePhysicsStepCallbacks.push(func);
  66182. };
  66183. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  66184. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  66185. if (index > -1) {
  66186. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  66187. }
  66188. else {
  66189. BABYLON.Tools.Warn("Function to remove was not found");
  66190. }
  66191. };
  66192. /**
  66193. * Register a function that will be executed after the physics step
  66194. */
  66195. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  66196. this._onAfterPhysicsStepCallbacks.push(func);
  66197. };
  66198. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  66199. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  66200. if (index > -1) {
  66201. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  66202. }
  66203. else {
  66204. BABYLON.Tools.Warn("Function to remove was not found");
  66205. }
  66206. };
  66207. /**
  66208. * register a function that will be executed when this impostor collides against a different body.
  66209. */
  66210. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  66211. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66212. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  66213. };
  66214. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  66215. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  66216. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  66217. if (index > -1) {
  66218. this._onPhysicsCollideCallbacks.splice(index, 1);
  66219. }
  66220. else {
  66221. BABYLON.Tools.Warn("Function to remove was not found");
  66222. }
  66223. };
  66224. PhysicsImpostor.prototype.getParentsRotation = function () {
  66225. var parent = this.object.parent;
  66226. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  66227. while (parent) {
  66228. if (parent.rotationQuaternion) {
  66229. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  66230. }
  66231. else {
  66232. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  66233. }
  66234. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  66235. parent = parent.parent;
  66236. }
  66237. return this._tmpQuat;
  66238. };
  66239. /**
  66240. * Apply a force
  66241. */
  66242. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  66243. if (this._physicsEngine) {
  66244. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  66245. }
  66246. return this;
  66247. };
  66248. /**
  66249. * Apply an impulse
  66250. */
  66251. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  66252. if (this._physicsEngine) {
  66253. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  66254. }
  66255. return this;
  66256. };
  66257. /**
  66258. * A help function to create a joint.
  66259. */
  66260. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  66261. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  66262. this.addJoint(otherImpostor, joint);
  66263. return this;
  66264. };
  66265. /**
  66266. * Add a joint to this impostor with a different impostor.
  66267. */
  66268. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  66269. this._joints.push({
  66270. otherImpostor: otherImpostor,
  66271. joint: joint
  66272. });
  66273. if (this._physicsEngine) {
  66274. this._physicsEngine.addJoint(this, otherImpostor, joint);
  66275. }
  66276. return this;
  66277. };
  66278. /**
  66279. * Will keep this body still, in a sleep mode.
  66280. */
  66281. PhysicsImpostor.prototype.sleep = function () {
  66282. if (this._physicsEngine) {
  66283. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  66284. }
  66285. return this;
  66286. };
  66287. /**
  66288. * Wake the body up.
  66289. */
  66290. PhysicsImpostor.prototype.wakeUp = function () {
  66291. if (this._physicsEngine) {
  66292. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  66293. }
  66294. return this;
  66295. };
  66296. PhysicsImpostor.prototype.clone = function (newObject) {
  66297. if (!newObject)
  66298. return null;
  66299. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  66300. };
  66301. PhysicsImpostor.prototype.dispose = function () {
  66302. var _this = this;
  66303. //no dispose if no physics engine is available.
  66304. if (!this._physicsEngine) {
  66305. return;
  66306. }
  66307. this._joints.forEach(function (j) {
  66308. if (_this._physicsEngine) {
  66309. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  66310. }
  66311. });
  66312. //dispose the physics body
  66313. this._physicsEngine.removeImpostor(this);
  66314. if (this.parent) {
  66315. this.parent.forceUpdate();
  66316. }
  66317. else {
  66318. /*this._object.getChildMeshes().forEach(function(mesh) {
  66319. if (mesh.physicsImpostor) {
  66320. if (disposeChildren) {
  66321. mesh.physicsImpostor.dispose();
  66322. mesh.physicsImpostor = null;
  66323. }
  66324. }
  66325. })*/
  66326. }
  66327. this._isDisposed = true;
  66328. };
  66329. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  66330. this._deltaPosition.copyFrom(position);
  66331. };
  66332. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  66333. if (!this._deltaRotation) {
  66334. this._deltaRotation = new BABYLON.Quaternion();
  66335. }
  66336. this._deltaRotation.copyFrom(rotation);
  66337. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  66338. };
  66339. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  66340. if (this._physicsEngine) {
  66341. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  66342. }
  66343. return this;
  66344. };
  66345. PhysicsImpostor.prototype.getRadius = function () {
  66346. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  66347. };
  66348. /**
  66349. * Sync a bone with this impostor
  66350. * @param bone The bone to sync to the impostor.
  66351. * @param boneMesh The mesh that the bone is influencing.
  66352. * @param jointPivot The pivot of the joint / bone in local space.
  66353. * @param distToJoint Optional distance from the impostor to the joint.
  66354. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66355. */
  66356. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  66357. var tempVec = PhysicsImpostor._tmpVecs[0];
  66358. var mesh = this.object;
  66359. if (mesh.rotationQuaternion) {
  66360. if (adjustRotation) {
  66361. var tempQuat = PhysicsImpostor._tmpQuat;
  66362. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  66363. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  66364. }
  66365. else {
  66366. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  66367. }
  66368. }
  66369. tempVec.x = 0;
  66370. tempVec.y = 0;
  66371. tempVec.z = 0;
  66372. if (jointPivot) {
  66373. tempVec.x = jointPivot.x;
  66374. tempVec.y = jointPivot.y;
  66375. tempVec.z = jointPivot.z;
  66376. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  66377. if (distToJoint === undefined || distToJoint === null) {
  66378. distToJoint = jointPivot.length();
  66379. }
  66380. tempVec.x *= distToJoint;
  66381. tempVec.y *= distToJoint;
  66382. tempVec.z *= distToJoint;
  66383. }
  66384. if (bone.getParent()) {
  66385. tempVec.addInPlace(mesh.getAbsolutePosition());
  66386. bone.setAbsolutePosition(tempVec, boneMesh);
  66387. }
  66388. else {
  66389. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  66390. boneMesh.position.x -= tempVec.x;
  66391. boneMesh.position.y -= tempVec.y;
  66392. boneMesh.position.z -= tempVec.z;
  66393. }
  66394. };
  66395. /**
  66396. * Sync impostor to a bone
  66397. * @param bone The bone that the impostor will be synced to.
  66398. * @param boneMesh The mesh that the bone is influencing.
  66399. * @param jointPivot The pivot of the joint / bone in local space.
  66400. * @param distToJoint Optional distance from the impostor to the joint.
  66401. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  66402. * @param boneAxis Optional vector3 axis the bone is aligned with
  66403. */
  66404. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  66405. var mesh = this.object;
  66406. if (mesh.rotationQuaternion) {
  66407. if (adjustRotation) {
  66408. var tempQuat = PhysicsImpostor._tmpQuat;
  66409. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  66410. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  66411. }
  66412. else {
  66413. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  66414. }
  66415. }
  66416. var pos = PhysicsImpostor._tmpVecs[0];
  66417. var boneDir = PhysicsImpostor._tmpVecs[1];
  66418. if (!boneAxis) {
  66419. boneAxis = PhysicsImpostor._tmpVecs[2];
  66420. boneAxis.x = 0;
  66421. boneAxis.y = 1;
  66422. boneAxis.z = 0;
  66423. }
  66424. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  66425. bone.getAbsolutePositionToRef(boneMesh, pos);
  66426. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  66427. distToJoint = jointPivot.length();
  66428. }
  66429. if (distToJoint !== undefined && distToJoint !== null) {
  66430. pos.x += boneDir.x * distToJoint;
  66431. pos.y += boneDir.y * distToJoint;
  66432. pos.z += boneDir.z * distToJoint;
  66433. }
  66434. mesh.setAbsolutePosition(pos);
  66435. };
  66436. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  66437. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  66438. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66439. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  66440. //Impostor types
  66441. PhysicsImpostor.NoImpostor = 0;
  66442. PhysicsImpostor.SphereImpostor = 1;
  66443. PhysicsImpostor.BoxImpostor = 2;
  66444. PhysicsImpostor.PlaneImpostor = 3;
  66445. PhysicsImpostor.MeshImpostor = 4;
  66446. PhysicsImpostor.CylinderImpostor = 7;
  66447. PhysicsImpostor.ParticleImpostor = 8;
  66448. PhysicsImpostor.HeightmapImpostor = 9;
  66449. return PhysicsImpostor;
  66450. }());
  66451. BABYLON.PhysicsImpostor = PhysicsImpostor;
  66452. })(BABYLON || (BABYLON = {}));
  66453. //# sourceMappingURL=babylon.physicsImpostor.js.map
  66454. var BABYLON;
  66455. (function (BABYLON) {
  66456. var PhysicsEngine = /** @class */ (function () {
  66457. function PhysicsEngine(gravity, _physicsPlugin) {
  66458. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  66459. this._physicsPlugin = _physicsPlugin;
  66460. //new methods and parameters
  66461. this._impostors = [];
  66462. this._joints = [];
  66463. if (!this._physicsPlugin.isSupported()) {
  66464. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  66465. + "Please make sure it is included.");
  66466. }
  66467. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  66468. this.setGravity(gravity);
  66469. this.setTimeStep();
  66470. }
  66471. PhysicsEngine.prototype.setGravity = function (gravity) {
  66472. this.gravity = gravity;
  66473. this._physicsPlugin.setGravity(this.gravity);
  66474. };
  66475. /**
  66476. * Set the time step of the physics engine.
  66477. * default is 1/60.
  66478. * To slow it down, enter 1/600 for example.
  66479. * To speed it up, 1/30
  66480. * @param {number} newTimeStep the new timestep to apply to this world.
  66481. */
  66482. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  66483. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  66484. this._physicsPlugin.setTimeStep(newTimeStep);
  66485. };
  66486. /**
  66487. * Get the time step of the physics engine.
  66488. */
  66489. PhysicsEngine.prototype.getTimeStep = function () {
  66490. return this._physicsPlugin.getTimeStep();
  66491. };
  66492. PhysicsEngine.prototype.dispose = function () {
  66493. this._impostors.forEach(function (impostor) {
  66494. impostor.dispose();
  66495. });
  66496. this._physicsPlugin.dispose();
  66497. };
  66498. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  66499. return this._physicsPlugin.name;
  66500. };
  66501. /**
  66502. * Adding a new impostor for the impostor tracking.
  66503. * This will be done by the impostor itself.
  66504. * @param {PhysicsImpostor} impostor the impostor to add
  66505. */
  66506. PhysicsEngine.prototype.addImpostor = function (impostor) {
  66507. impostor.uniqueId = this._impostors.push(impostor);
  66508. //if no parent, generate the body
  66509. if (!impostor.parent) {
  66510. this._physicsPlugin.generatePhysicsBody(impostor);
  66511. }
  66512. };
  66513. /**
  66514. * Remove an impostor from the engine.
  66515. * This impostor and its mesh will not longer be updated by the physics engine.
  66516. * @param {PhysicsImpostor} impostor the impostor to remove
  66517. */
  66518. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  66519. var index = this._impostors.indexOf(impostor);
  66520. if (index > -1) {
  66521. var removed = this._impostors.splice(index, 1);
  66522. //Is it needed?
  66523. if (removed.length) {
  66524. //this will also remove it from the world.
  66525. removed[0].physicsBody = null;
  66526. }
  66527. }
  66528. };
  66529. /**
  66530. * Add a joint to the physics engine
  66531. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  66532. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  66533. * @param {PhysicsJoint} the joint that will connect both impostors.
  66534. */
  66535. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  66536. var impostorJoint = {
  66537. mainImpostor: mainImpostor,
  66538. connectedImpostor: connectedImpostor,
  66539. joint: joint
  66540. };
  66541. joint.physicsPlugin = this._physicsPlugin;
  66542. this._joints.push(impostorJoint);
  66543. this._physicsPlugin.generateJoint(impostorJoint);
  66544. };
  66545. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  66546. var matchingJoints = this._joints.filter(function (impostorJoint) {
  66547. return (impostorJoint.connectedImpostor === connectedImpostor
  66548. && impostorJoint.joint === joint
  66549. && impostorJoint.mainImpostor === mainImpostor);
  66550. });
  66551. if (matchingJoints.length) {
  66552. this._physicsPlugin.removeJoint(matchingJoints[0]);
  66553. //TODO remove it from the list as well
  66554. }
  66555. };
  66556. /**
  66557. * Called by the scene. no need to call it.
  66558. */
  66559. PhysicsEngine.prototype._step = function (delta) {
  66560. var _this = this;
  66561. //check if any mesh has no body / requires an update
  66562. this._impostors.forEach(function (impostor) {
  66563. if (impostor.isBodyInitRequired()) {
  66564. _this._physicsPlugin.generatePhysicsBody(impostor);
  66565. }
  66566. });
  66567. if (delta > 0.1) {
  66568. delta = 0.1;
  66569. }
  66570. else if (delta <= 0) {
  66571. delta = 1.0 / 60.0;
  66572. }
  66573. this._physicsPlugin.executeStep(delta, this._impostors);
  66574. };
  66575. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  66576. return this._physicsPlugin;
  66577. };
  66578. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  66579. for (var i = 0; i < this._impostors.length; ++i) {
  66580. if (this._impostors[i].object === object) {
  66581. return this._impostors[i];
  66582. }
  66583. }
  66584. return null;
  66585. };
  66586. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  66587. for (var i = 0; i < this._impostors.length; ++i) {
  66588. if (this._impostors[i].physicsBody === body) {
  66589. return this._impostors[i];
  66590. }
  66591. }
  66592. return null;
  66593. };
  66594. // Statics
  66595. PhysicsEngine.Epsilon = 0.001;
  66596. return PhysicsEngine;
  66597. }());
  66598. BABYLON.PhysicsEngine = PhysicsEngine;
  66599. })(BABYLON || (BABYLON = {}));
  66600. //# sourceMappingURL=babylon.physicsEngine.js.map
  66601. var BABYLON;
  66602. (function (BABYLON) {
  66603. var CannonJSPlugin = /** @class */ (function () {
  66604. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  66605. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  66606. if (iterations === void 0) { iterations = 10; }
  66607. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  66608. this.name = "CannonJSPlugin";
  66609. this._physicsMaterials = new Array();
  66610. this._fixedTimeStep = 1 / 60;
  66611. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  66612. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(15) : undefined);
  66613. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  66614. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  66615. this._tmpPosition = BABYLON.Vector3.Zero();
  66616. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  66617. this._tmpUnityRotation = new BABYLON.Quaternion();
  66618. if (!this.isSupported()) {
  66619. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  66620. return;
  66621. }
  66622. this.world = new this.BJSCANNON.World();
  66623. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  66624. this.world.solver.iterations = iterations;
  66625. }
  66626. CannonJSPlugin.prototype.setGravity = function (gravity) {
  66627. this.world.gravity.copy(gravity);
  66628. };
  66629. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  66630. this._fixedTimeStep = timeStep;
  66631. };
  66632. CannonJSPlugin.prototype.getTimeStep = function () {
  66633. return this._fixedTimeStep;
  66634. };
  66635. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  66636. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  66637. };
  66638. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66639. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  66640. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  66641. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  66642. };
  66643. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66644. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  66645. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  66646. impostor.physicsBody.applyForce(impulse, worldPoint);
  66647. };
  66648. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66649. //parent-child relationship. Does this impostor has a parent impostor?
  66650. if (impostor.parent) {
  66651. if (impostor.physicsBody) {
  66652. this.removePhysicsBody(impostor);
  66653. //TODO is that needed?
  66654. impostor.forceUpdate();
  66655. }
  66656. return;
  66657. }
  66658. //should a new body be created for this impostor?
  66659. if (impostor.isBodyInitRequired()) {
  66660. var shape = this._createShape(impostor);
  66661. //unregister events, if body is being changed
  66662. var oldBody = impostor.physicsBody;
  66663. if (oldBody) {
  66664. this.removePhysicsBody(impostor);
  66665. }
  66666. //create the body and material
  66667. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  66668. var bodyCreationObject = {
  66669. mass: impostor.getParam("mass"),
  66670. material: material
  66671. };
  66672. // A simple extend, in case native options were used.
  66673. var nativeOptions = impostor.getParam("nativeOptions");
  66674. for (var key in nativeOptions) {
  66675. if (nativeOptions.hasOwnProperty(key)) {
  66676. bodyCreationObject[key] = nativeOptions[key];
  66677. }
  66678. }
  66679. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  66680. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  66681. this.world.addEventListener("preStep", impostor.beforeStep);
  66682. this.world.addEventListener("postStep", impostor.afterStep);
  66683. impostor.physicsBody.addShape(shape);
  66684. this.world.add(impostor.physicsBody);
  66685. //try to keep the body moving in the right direction by taking old properties.
  66686. //Should be tested!
  66687. if (oldBody) {
  66688. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  66689. impostor.physicsBody[param].copy(oldBody[param]);
  66690. });
  66691. }
  66692. this._processChildMeshes(impostor);
  66693. }
  66694. //now update the body's transformation
  66695. this._updatePhysicsBodyTransformation(impostor);
  66696. };
  66697. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  66698. var _this = this;
  66699. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  66700. var currentRotation = mainImpostor.object.rotationQuaternion;
  66701. if (meshChildren.length) {
  66702. var processMesh = function (localPosition, mesh) {
  66703. if (!currentRotation || !mesh.rotationQuaternion) {
  66704. return;
  66705. }
  66706. var childImpostor = mesh.getPhysicsImpostor();
  66707. if (childImpostor) {
  66708. var parent = childImpostor.parent;
  66709. if (parent !== mainImpostor) {
  66710. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  66711. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  66712. if (childImpostor.physicsBody) {
  66713. _this.removePhysicsBody(childImpostor);
  66714. childImpostor.physicsBody = null;
  66715. }
  66716. childImpostor.parent = mainImpostor;
  66717. childImpostor.resetUpdateFlags();
  66718. 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));
  66719. //Add the mass of the children.
  66720. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  66721. }
  66722. }
  66723. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  66724. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  66725. };
  66726. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  66727. }
  66728. };
  66729. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66730. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  66731. this.world.removeEventListener("preStep", impostor.beforeStep);
  66732. this.world.removeEventListener("postStep", impostor.afterStep);
  66733. this.world.remove(impostor.physicsBody);
  66734. };
  66735. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66736. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66737. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66738. if (!mainBody || !connectedBody) {
  66739. return;
  66740. }
  66741. var constraint;
  66742. var jointData = impostorJoint.joint.jointData;
  66743. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  66744. var constraintData = {
  66745. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  66746. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  66747. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  66748. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  66749. maxForce: jointData.nativeParams.maxForce,
  66750. collideConnected: !!jointData.collision
  66751. };
  66752. switch (impostorJoint.joint.type) {
  66753. case BABYLON.PhysicsJoint.HingeJoint:
  66754. case BABYLON.PhysicsJoint.Hinge2Joint:
  66755. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  66756. break;
  66757. case BABYLON.PhysicsJoint.DistanceJoint:
  66758. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  66759. break;
  66760. case BABYLON.PhysicsJoint.SpringJoint:
  66761. var springData = jointData;
  66762. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  66763. restLength: springData.length,
  66764. stiffness: springData.stiffness,
  66765. damping: springData.damping,
  66766. localAnchorA: constraintData.pivotA,
  66767. localAnchorB: constraintData.pivotB
  66768. });
  66769. break;
  66770. case BABYLON.PhysicsJoint.LockJoint:
  66771. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  66772. break;
  66773. case BABYLON.PhysicsJoint.PointToPointJoint:
  66774. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66775. default:
  66776. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  66777. break;
  66778. }
  66779. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  66780. constraint.collideConnected = !!jointData.collision;
  66781. impostorJoint.joint.physicsJoint = constraint;
  66782. //don't add spring as constraint, as it is not one.
  66783. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  66784. this.world.addConstraint(constraint);
  66785. }
  66786. else {
  66787. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  66788. constraint.applyForce();
  66789. });
  66790. }
  66791. };
  66792. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66793. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  66794. };
  66795. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  66796. var index;
  66797. var mat;
  66798. for (index = 0; index < this._physicsMaterials.length; index++) {
  66799. mat = this._physicsMaterials[index];
  66800. if (mat.friction === friction && mat.restitution === restitution) {
  66801. return mat;
  66802. }
  66803. }
  66804. var currentMat = new this.BJSCANNON.Material(name);
  66805. currentMat.friction = friction;
  66806. currentMat.restitution = restitution;
  66807. this._physicsMaterials.push(currentMat);
  66808. return currentMat;
  66809. };
  66810. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  66811. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  66812. };
  66813. CannonJSPlugin.prototype._createShape = function (impostor) {
  66814. var object = impostor.object;
  66815. var returnValue;
  66816. var extendSize = impostor.getObjectExtendSize();
  66817. switch (impostor.type) {
  66818. case BABYLON.PhysicsImpostor.SphereImpostor:
  66819. var radiusX = extendSize.x;
  66820. var radiusY = extendSize.y;
  66821. var radiusZ = extendSize.z;
  66822. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  66823. break;
  66824. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  66825. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66826. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  66827. break;
  66828. case BABYLON.PhysicsImpostor.BoxImpostor:
  66829. var box = extendSize.scale(0.5);
  66830. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  66831. break;
  66832. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66833. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  66834. returnValue = new this.BJSCANNON.Plane();
  66835. break;
  66836. case BABYLON.PhysicsImpostor.MeshImpostor:
  66837. // should transform the vertex data to world coordinates!!
  66838. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  66839. var rawFaces = object.getIndices ? object.getIndices() : [];
  66840. if (!rawVerts)
  66841. return;
  66842. // get only scale! so the object could transform correctly.
  66843. var oldPosition = object.position.clone();
  66844. var oldRotation = object.rotation && object.rotation.clone();
  66845. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  66846. object.position.copyFromFloats(0, 0, 0);
  66847. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66848. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  66849. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  66850. var transform = object.computeWorldMatrix(true);
  66851. // convert rawVerts to object space
  66852. var temp = new Array();
  66853. var index;
  66854. for (index = 0; index < rawVerts.length; index += 3) {
  66855. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  66856. }
  66857. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  66858. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  66859. //now set back the transformation!
  66860. object.position.copyFrom(oldPosition);
  66861. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  66862. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  66863. break;
  66864. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  66865. var oldPosition2 = object.position.clone();
  66866. var oldRotation2 = object.rotation && object.rotation.clone();
  66867. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  66868. object.position.copyFromFloats(0, 0, 0);
  66869. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66870. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  66871. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  66872. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  66873. returnValue = this._createHeightmap(object);
  66874. object.position.copyFrom(oldPosition2);
  66875. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  66876. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  66877. object.computeWorldMatrix(true);
  66878. break;
  66879. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66880. returnValue = new this.BJSCANNON.Particle();
  66881. break;
  66882. }
  66883. return returnValue;
  66884. };
  66885. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  66886. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  66887. var transform = object.computeWorldMatrix(true);
  66888. // convert rawVerts to object space
  66889. var temp = new Array();
  66890. var index;
  66891. for (index = 0; index < pos.length; index += 3) {
  66892. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  66893. }
  66894. pos = temp;
  66895. var matrix = new Array();
  66896. //For now pointDepth will not be used and will be automatically calculated.
  66897. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  66898. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  66899. var boundingInfo = (object.getBoundingInfo());
  66900. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  66901. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  66902. var elementSize = dim * 2 / arraySize;
  66903. for (var i = 0; i < pos.length; i = i + 3) {
  66904. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  66905. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  66906. var y = -pos[i + 2] + minY;
  66907. if (!matrix[x]) {
  66908. matrix[x] = [];
  66909. }
  66910. if (!matrix[x][z]) {
  66911. matrix[x][z] = y;
  66912. }
  66913. matrix[x][z] = Math.max(y, matrix[x][z]);
  66914. }
  66915. for (var x = 0; x <= arraySize; ++x) {
  66916. if (!matrix[x]) {
  66917. var loc = 1;
  66918. while (!matrix[(x + loc) % arraySize]) {
  66919. loc++;
  66920. }
  66921. matrix[x] = matrix[(x + loc) % arraySize].slice();
  66922. //console.log("missing x", x);
  66923. }
  66924. for (var z = 0; z <= arraySize; ++z) {
  66925. if (!matrix[x][z]) {
  66926. var loc = 1;
  66927. var newValue;
  66928. while (newValue === undefined) {
  66929. newValue = matrix[x][(z + loc++) % arraySize];
  66930. }
  66931. matrix[x][z] = newValue;
  66932. }
  66933. }
  66934. }
  66935. var shape = new this.BJSCANNON.Heightfield(matrix, {
  66936. elementSize: elementSize
  66937. });
  66938. //For future reference, needed for body transformation
  66939. shape.minY = minY;
  66940. return shape;
  66941. };
  66942. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  66943. var object = impostor.object;
  66944. //make sure it is updated...
  66945. object.computeWorldMatrix && object.computeWorldMatrix(true);
  66946. // The delta between the mesh position and the mesh bounding box center
  66947. var bInfo = object.getBoundingInfo();
  66948. if (!bInfo)
  66949. return;
  66950. var center = impostor.getObjectCenter();
  66951. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  66952. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  66953. this._tmpPosition.copyFrom(center);
  66954. var quaternion = object.rotationQuaternion;
  66955. if (!quaternion) {
  66956. return;
  66957. }
  66958. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  66959. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  66960. //-90 DEG in X, precalculated
  66961. quaternion = quaternion.multiply(this._minus90X);
  66962. //Invert! (Precalculated, 90 deg in X)
  66963. //No need to clone. this will never change.
  66964. impostor.setDeltaRotation(this._plus90X);
  66965. }
  66966. //If it is a heightfield, if should be centered.
  66967. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  66968. var mesh = object;
  66969. var boundingInfo = mesh.getBoundingInfo();
  66970. //calculate the correct body position:
  66971. var rotationQuaternion = mesh.rotationQuaternion;
  66972. mesh.rotationQuaternion = this._tmpUnityRotation;
  66973. mesh.computeWorldMatrix(true);
  66974. //get original center with no rotation
  66975. var c = center.clone();
  66976. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  66977. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  66978. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  66979. mesh.setPivotMatrix(p);
  66980. mesh.computeWorldMatrix(true);
  66981. //calculate the translation
  66982. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  66983. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  66984. //add it inverted to the delta
  66985. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  66986. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  66987. //rotation is back
  66988. mesh.rotationQuaternion = rotationQuaternion;
  66989. mesh.setPivotMatrix(oldPivot);
  66990. mesh.computeWorldMatrix(true);
  66991. }
  66992. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  66993. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  66994. //this._tmpPosition.copyFrom(object.position);
  66995. }
  66996. impostor.setDeltaPosition(this._tmpDeltaPosition);
  66997. //Now update the impostor object
  66998. impostor.physicsBody.position.copy(this._tmpPosition);
  66999. impostor.physicsBody.quaternion.copy(quaternion);
  67000. };
  67001. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  67002. impostor.object.position.copyFrom(impostor.physicsBody.position);
  67003. if (impostor.object.rotationQuaternion) {
  67004. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  67005. }
  67006. };
  67007. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  67008. impostor.physicsBody.position.copy(newPosition);
  67009. impostor.physicsBody.quaternion.copy(newRotation);
  67010. };
  67011. CannonJSPlugin.prototype.isSupported = function () {
  67012. return this.BJSCANNON !== undefined;
  67013. };
  67014. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  67015. impostor.physicsBody.velocity.copy(velocity);
  67016. };
  67017. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  67018. impostor.physicsBody.angularVelocity.copy(velocity);
  67019. };
  67020. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  67021. var v = impostor.physicsBody.velocity;
  67022. if (!v) {
  67023. return null;
  67024. }
  67025. return new BABYLON.Vector3(v.x, v.y, v.z);
  67026. };
  67027. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  67028. var v = impostor.physicsBody.angularVelocity;
  67029. if (!v) {
  67030. return null;
  67031. }
  67032. return new BABYLON.Vector3(v.x, v.y, v.z);
  67033. };
  67034. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  67035. impostor.physicsBody.mass = mass;
  67036. impostor.physicsBody.updateMassProperties();
  67037. };
  67038. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  67039. return impostor.physicsBody.mass;
  67040. };
  67041. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  67042. return impostor.physicsBody.material.friction;
  67043. };
  67044. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  67045. impostor.physicsBody.material.friction = friction;
  67046. };
  67047. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  67048. return impostor.physicsBody.material.restitution;
  67049. };
  67050. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  67051. impostor.physicsBody.material.restitution = restitution;
  67052. };
  67053. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  67054. impostor.physicsBody.sleep();
  67055. };
  67056. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  67057. impostor.physicsBody.wakeUp();
  67058. };
  67059. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  67060. joint.physicsJoint.distance = maxDistance;
  67061. };
  67062. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  67063. // if (!motorIndex) {
  67064. // joint.physicsJoint.enableMotor();
  67065. // }
  67066. // }
  67067. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  67068. // if (!motorIndex) {
  67069. // joint.physicsJoint.disableMotor();
  67070. // }
  67071. // }
  67072. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  67073. if (!motorIndex) {
  67074. joint.physicsJoint.enableMotor();
  67075. joint.physicsJoint.setMotorSpeed(speed);
  67076. if (maxForce) {
  67077. this.setLimit(joint, maxForce);
  67078. }
  67079. }
  67080. };
  67081. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  67082. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  67083. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  67084. };
  67085. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  67086. var body = impostor.physicsBody;
  67087. mesh.position.x = body.position.x;
  67088. mesh.position.y = body.position.y;
  67089. mesh.position.z = body.position.z;
  67090. if (mesh.rotationQuaternion) {
  67091. mesh.rotationQuaternion.x = body.quaternion.x;
  67092. mesh.rotationQuaternion.y = body.quaternion.y;
  67093. mesh.rotationQuaternion.z = body.quaternion.z;
  67094. mesh.rotationQuaternion.w = body.quaternion.w;
  67095. }
  67096. };
  67097. CannonJSPlugin.prototype.getRadius = function (impostor) {
  67098. var shape = impostor.physicsBody.shapes[0];
  67099. return shape.boundingSphereRadius;
  67100. };
  67101. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  67102. var shape = impostor.physicsBody.shapes[0];
  67103. result.x = shape.halfExtents.x * 2;
  67104. result.y = shape.halfExtents.y * 2;
  67105. result.z = shape.halfExtents.z * 2;
  67106. };
  67107. CannonJSPlugin.prototype.dispose = function () {
  67108. };
  67109. return CannonJSPlugin;
  67110. }());
  67111. BABYLON.CannonJSPlugin = CannonJSPlugin;
  67112. })(BABYLON || (BABYLON = {}));
  67113. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  67114. var BABYLON;
  67115. (function (BABYLON) {
  67116. var OimoJSPlugin = /** @class */ (function () {
  67117. function OimoJSPlugin(iterations) {
  67118. this.name = "OimoJSPlugin";
  67119. this._tmpImpostorsArray = [];
  67120. this._tmpPositionVector = BABYLON.Vector3.Zero();
  67121. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(16) : undefined);
  67122. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  67123. this.world.worldscale(1);
  67124. this.world.clear();
  67125. //making sure no stats are calculated
  67126. this.world.isNoStat = true;
  67127. }
  67128. OimoJSPlugin.prototype.setGravity = function (gravity) {
  67129. this.world.gravity.copy(gravity);
  67130. };
  67131. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  67132. this.world.timeStep = timeStep;
  67133. };
  67134. OimoJSPlugin.prototype.getTimeStep = function () {
  67135. return this.world.timeStep;
  67136. };
  67137. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  67138. var _this = this;
  67139. impostors.forEach(function (impostor) {
  67140. impostor.beforeStep();
  67141. });
  67142. this.world.step();
  67143. impostors.forEach(function (impostor) {
  67144. impostor.afterStep();
  67145. //update the ordered impostors array
  67146. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  67147. });
  67148. //check for collisions
  67149. var contact = this.world.contacts;
  67150. while (contact !== null) {
  67151. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  67152. contact = contact.next;
  67153. continue;
  67154. }
  67155. //is this body colliding with any other? get the impostor
  67156. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  67157. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  67158. if (!mainImpostor || !collidingImpostor) {
  67159. contact = contact.next;
  67160. continue;
  67161. }
  67162. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  67163. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  67164. contact = contact.next;
  67165. }
  67166. };
  67167. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  67168. var mass = impostor.physicsBody.massInfo.mass;
  67169. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  67170. };
  67171. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  67172. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  67173. this.applyImpulse(impostor, force, contactPoint);
  67174. };
  67175. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  67176. var _this = this;
  67177. //parent-child relationship. Does this impostor has a parent impostor?
  67178. if (impostor.parent) {
  67179. if (impostor.physicsBody) {
  67180. this.removePhysicsBody(impostor);
  67181. //TODO is that needed?
  67182. impostor.forceUpdate();
  67183. }
  67184. return;
  67185. }
  67186. if (impostor.isBodyInitRequired()) {
  67187. var bodyConfig = {
  67188. name: impostor.uniqueId,
  67189. //Oimo must have mass, also for static objects.
  67190. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  67191. size: [],
  67192. type: [],
  67193. pos: [],
  67194. rot: [],
  67195. move: impostor.getParam("mass") !== 0,
  67196. //Supporting older versions of Oimo
  67197. world: this.world
  67198. };
  67199. var impostors = [impostor];
  67200. var addToArray = function (parent) {
  67201. if (!parent.getChildMeshes)
  67202. return;
  67203. parent.getChildMeshes().forEach(function (m) {
  67204. if (m.physicsImpostor) {
  67205. impostors.push(m.physicsImpostor);
  67206. //m.physicsImpostor._init();
  67207. }
  67208. });
  67209. };
  67210. addToArray(impostor.object);
  67211. var checkWithEpsilon_1 = function (value) {
  67212. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  67213. };
  67214. impostors.forEach(function (i) {
  67215. if (!impostor.object.rotationQuaternion) {
  67216. return;
  67217. }
  67218. //get the correct bounding box
  67219. var oldQuaternion = i.object.rotationQuaternion;
  67220. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  67221. x: impostor.object.rotationQuaternion.x,
  67222. y: impostor.object.rotationQuaternion.y,
  67223. z: impostor.object.rotationQuaternion.z,
  67224. s: impostor.object.rotationQuaternion.w
  67225. });
  67226. var extendSize = i.getObjectExtendSize();
  67227. if (i === impostor) {
  67228. var center = impostor.getObjectCenter();
  67229. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  67230. //Can also use Array.prototype.push.apply
  67231. bodyConfig.pos.push(center.x);
  67232. bodyConfig.pos.push(center.y);
  67233. bodyConfig.pos.push(center.z);
  67234. //tmp solution
  67235. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67236. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67237. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  67238. }
  67239. else {
  67240. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  67241. bodyConfig.pos.push(localPosition.x);
  67242. bodyConfig.pos.push(localPosition.y);
  67243. bodyConfig.pos.push(localPosition.z);
  67244. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  67245. bodyConfig.rot.push(0);
  67246. bodyConfig.rot.push(0);
  67247. bodyConfig.rot.push(0);
  67248. }
  67249. // register mesh
  67250. switch (i.type) {
  67251. case BABYLON.PhysicsImpostor.ParticleImpostor:
  67252. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  67253. case BABYLON.PhysicsImpostor.SphereImpostor:
  67254. var radiusX = extendSize.x;
  67255. var radiusY = extendSize.y;
  67256. var radiusZ = extendSize.z;
  67257. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  67258. bodyConfig.type.push('sphere');
  67259. //due to the way oimo works with compounds, add 3 times
  67260. bodyConfig.size.push(size);
  67261. bodyConfig.size.push(size);
  67262. bodyConfig.size.push(size);
  67263. break;
  67264. case BABYLON.PhysicsImpostor.CylinderImpostor:
  67265. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  67266. var sizeY = checkWithEpsilon_1(extendSize.y);
  67267. bodyConfig.type.push('cylinder');
  67268. bodyConfig.size.push(sizeX);
  67269. bodyConfig.size.push(sizeY);
  67270. //due to the way oimo works with compounds, add one more value.
  67271. bodyConfig.size.push(sizeY);
  67272. break;
  67273. case BABYLON.PhysicsImpostor.PlaneImpostor:
  67274. case BABYLON.PhysicsImpostor.BoxImpostor:
  67275. default:
  67276. var sizeX = checkWithEpsilon_1(extendSize.x);
  67277. var sizeY = checkWithEpsilon_1(extendSize.y);
  67278. var sizeZ = checkWithEpsilon_1(extendSize.z);
  67279. bodyConfig.type.push('box');
  67280. bodyConfig.size.push(sizeX);
  67281. bodyConfig.size.push(sizeY);
  67282. bodyConfig.size.push(sizeZ);
  67283. break;
  67284. }
  67285. //actually not needed, but hey...
  67286. i.object.rotationQuaternion = oldQuaternion;
  67287. });
  67288. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  67289. }
  67290. else {
  67291. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  67292. }
  67293. impostor.setDeltaPosition(this._tmpPositionVector);
  67294. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  67295. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  67296. };
  67297. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  67298. //impostor.physicsBody.dispose();
  67299. //Same as : (older oimo versions)
  67300. this.world.removeRigidBody(impostor.physicsBody);
  67301. };
  67302. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  67303. var mainBody = impostorJoint.mainImpostor.physicsBody;
  67304. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  67305. if (!mainBody || !connectedBody) {
  67306. return;
  67307. }
  67308. var jointData = impostorJoint.joint.jointData;
  67309. var options = jointData.nativeParams || {};
  67310. var type;
  67311. var nativeJointData = {
  67312. body1: mainBody,
  67313. body2: connectedBody,
  67314. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  67315. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  67316. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  67317. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  67318. min: options.min,
  67319. max: options.max,
  67320. collision: options.collision || jointData.collision,
  67321. spring: options.spring,
  67322. //supporting older version of Oimo
  67323. world: this.world
  67324. };
  67325. switch (impostorJoint.joint.type) {
  67326. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  67327. type = "jointBall";
  67328. break;
  67329. case BABYLON.PhysicsJoint.SpringJoint:
  67330. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  67331. var springData = jointData;
  67332. nativeJointData.min = springData.length || nativeJointData.min;
  67333. //Max should also be set, just make sure it is at least min
  67334. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  67335. case BABYLON.PhysicsJoint.DistanceJoint:
  67336. type = "jointDistance";
  67337. nativeJointData.max = jointData.maxDistance;
  67338. break;
  67339. case BABYLON.PhysicsJoint.PrismaticJoint:
  67340. type = "jointPrisme";
  67341. break;
  67342. case BABYLON.PhysicsJoint.SliderJoint:
  67343. type = "jointSlide";
  67344. break;
  67345. case BABYLON.PhysicsJoint.WheelJoint:
  67346. type = "jointWheel";
  67347. break;
  67348. case BABYLON.PhysicsJoint.HingeJoint:
  67349. default:
  67350. type = "jointHinge";
  67351. break;
  67352. }
  67353. nativeJointData.type = type;
  67354. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  67355. };
  67356. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  67357. //Bug in Oimo prevents us from disposing a joint in the playground
  67358. //joint.joint.physicsJoint.dispose();
  67359. //So we will bruteforce it!
  67360. try {
  67361. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  67362. }
  67363. catch (e) {
  67364. BABYLON.Tools.Warn(e);
  67365. }
  67366. };
  67367. OimoJSPlugin.prototype.isSupported = function () {
  67368. return this.BJSOIMO !== undefined;
  67369. };
  67370. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  67371. if (!impostor.physicsBody.sleeping) {
  67372. //TODO check that
  67373. if (impostor.physicsBody.shapes.next) {
  67374. var parentShape = this._getLastShape(impostor.physicsBody);
  67375. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  67376. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  67377. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  67378. }
  67379. else {
  67380. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  67381. }
  67382. if (impostor.object.rotationQuaternion) {
  67383. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  67384. impostor.object.rotationQuaternion.normalize();
  67385. }
  67386. }
  67387. };
  67388. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  67389. var body = impostor.physicsBody;
  67390. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  67391. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  67392. body.syncShapes();
  67393. body.awake();
  67394. };
  67395. OimoJSPlugin.prototype._getLastShape = function (body) {
  67396. var lastShape = body.shapes;
  67397. while (lastShape.next) {
  67398. lastShape = lastShape.next;
  67399. }
  67400. return lastShape;
  67401. };
  67402. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  67403. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  67404. };
  67405. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  67406. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  67407. };
  67408. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  67409. var v = impostor.physicsBody.linearVelocity;
  67410. if (!v) {
  67411. return null;
  67412. }
  67413. return new BABYLON.Vector3(v.x, v.y, v.z);
  67414. };
  67415. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  67416. var v = impostor.physicsBody.angularVelocity;
  67417. if (!v) {
  67418. return null;
  67419. }
  67420. return new BABYLON.Vector3(v.x, v.y, v.z);
  67421. };
  67422. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  67423. var staticBody = mass === 0;
  67424. //this will actually set the body's density and not its mass.
  67425. //But this is how oimo treats the mass variable.
  67426. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  67427. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  67428. };
  67429. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  67430. return impostor.physicsBody.shapes.density;
  67431. };
  67432. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  67433. return impostor.physicsBody.shapes.friction;
  67434. };
  67435. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  67436. impostor.physicsBody.shapes.friction = friction;
  67437. };
  67438. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  67439. return impostor.physicsBody.shapes.restitution;
  67440. };
  67441. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  67442. impostor.physicsBody.shapes.restitution = restitution;
  67443. };
  67444. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  67445. impostor.physicsBody.sleep();
  67446. };
  67447. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  67448. impostor.physicsBody.awake();
  67449. };
  67450. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  67451. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  67452. if (minDistance !== void 0) {
  67453. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  67454. }
  67455. };
  67456. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  67457. //TODO separate rotational and transational motors.
  67458. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  67459. if (motor) {
  67460. motor.setMotor(speed, maxForce);
  67461. }
  67462. };
  67463. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  67464. //TODO separate rotational and transational motors.
  67465. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  67466. if (motor) {
  67467. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  67468. }
  67469. };
  67470. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  67471. var body = impostor.physicsBody;
  67472. mesh.position.x = body.position.x;
  67473. mesh.position.y = body.position.y;
  67474. mesh.position.z = body.position.z;
  67475. if (mesh.rotationQuaternion) {
  67476. mesh.rotationQuaternion.x = body.orientation.x;
  67477. mesh.rotationQuaternion.y = body.orientation.y;
  67478. mesh.rotationQuaternion.z = body.orientation.z;
  67479. mesh.rotationQuaternion.w = body.orientation.s;
  67480. }
  67481. };
  67482. OimoJSPlugin.prototype.getRadius = function (impostor) {
  67483. return impostor.physicsBody.shapes.radius;
  67484. };
  67485. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  67486. var shape = impostor.physicsBody.shapes;
  67487. result.x = shape.halfWidth * 2;
  67488. result.y = shape.halfHeight * 2;
  67489. result.z = shape.halfDepth * 2;
  67490. };
  67491. OimoJSPlugin.prototype.dispose = function () {
  67492. this.world.clear();
  67493. };
  67494. return OimoJSPlugin;
  67495. }());
  67496. BABYLON.OimoJSPlugin = OimoJSPlugin;
  67497. })(BABYLON || (BABYLON = {}));
  67498. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  67499. var BABYLON;
  67500. (function (BABYLON) {
  67501. var Internals;
  67502. (function (Internals) {
  67503. /*
  67504. * Based on jsTGALoader - Javascript loader for TGA file
  67505. * By Vincent Thibault
  67506. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  67507. */
  67508. var TGATools = /** @class */ (function () {
  67509. function TGATools() {
  67510. }
  67511. TGATools.GetTGAHeader = function (data) {
  67512. var offset = 0;
  67513. var header = {
  67514. id_length: data[offset++],
  67515. colormap_type: data[offset++],
  67516. image_type: data[offset++],
  67517. colormap_index: data[offset++] | data[offset++] << 8,
  67518. colormap_length: data[offset++] | data[offset++] << 8,
  67519. colormap_size: data[offset++],
  67520. origin: [
  67521. data[offset++] | data[offset++] << 8,
  67522. data[offset++] | data[offset++] << 8
  67523. ],
  67524. width: data[offset++] | data[offset++] << 8,
  67525. height: data[offset++] | data[offset++] << 8,
  67526. pixel_size: data[offset++],
  67527. flags: data[offset++]
  67528. };
  67529. return header;
  67530. };
  67531. TGATools.UploadContent = function (gl, data) {
  67532. // Not enough data to contain header ?
  67533. if (data.length < 19) {
  67534. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  67535. return;
  67536. }
  67537. // Read Header
  67538. var offset = 18;
  67539. var header = TGATools.GetTGAHeader(data);
  67540. // Assume it's a valid Targa file.
  67541. if (header.id_length + offset > data.length) {
  67542. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  67543. return;
  67544. }
  67545. // Skip not needed data
  67546. offset += header.id_length;
  67547. var use_rle = false;
  67548. var use_pal = false;
  67549. var use_rgb = false;
  67550. var use_grey = false;
  67551. // Get some informations.
  67552. switch (header.image_type) {
  67553. case TGATools._TYPE_RLE_INDEXED:
  67554. use_rle = true;
  67555. case TGATools._TYPE_INDEXED:
  67556. use_pal = true;
  67557. break;
  67558. case TGATools._TYPE_RLE_RGB:
  67559. use_rle = true;
  67560. case TGATools._TYPE_RGB:
  67561. use_rgb = true;
  67562. break;
  67563. case TGATools._TYPE_RLE_GREY:
  67564. use_rle = true;
  67565. case TGATools._TYPE_GREY:
  67566. use_grey = true;
  67567. break;
  67568. }
  67569. var pixel_data;
  67570. // var numAlphaBits = header.flags & 0xf;
  67571. var pixel_size = header.pixel_size >> 3;
  67572. var pixel_total = header.width * header.height * pixel_size;
  67573. // Read palettes
  67574. var palettes;
  67575. if (use_pal) {
  67576. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  67577. }
  67578. // Read LRE
  67579. if (use_rle) {
  67580. pixel_data = new Uint8Array(pixel_total);
  67581. var c, count, i;
  67582. var localOffset = 0;
  67583. var pixels = new Uint8Array(pixel_size);
  67584. while (offset < pixel_total && localOffset < pixel_total) {
  67585. c = data[offset++];
  67586. count = (c & 0x7f) + 1;
  67587. // RLE pixels
  67588. if (c & 0x80) {
  67589. // Bind pixel tmp array
  67590. for (i = 0; i < pixel_size; ++i) {
  67591. pixels[i] = data[offset++];
  67592. }
  67593. // Copy pixel array
  67594. for (i = 0; i < count; ++i) {
  67595. pixel_data.set(pixels, localOffset + i * pixel_size);
  67596. }
  67597. localOffset += pixel_size * count;
  67598. }
  67599. else {
  67600. count *= pixel_size;
  67601. for (i = 0; i < count; ++i) {
  67602. pixel_data[localOffset + i] = data[offset++];
  67603. }
  67604. localOffset += count;
  67605. }
  67606. }
  67607. }
  67608. else {
  67609. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  67610. }
  67611. // Load to texture
  67612. var x_start, y_start, x_step, y_step, y_end, x_end;
  67613. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  67614. default:
  67615. case TGATools._ORIGIN_UL:
  67616. x_start = 0;
  67617. x_step = 1;
  67618. x_end = header.width;
  67619. y_start = 0;
  67620. y_step = 1;
  67621. y_end = header.height;
  67622. break;
  67623. case TGATools._ORIGIN_BL:
  67624. x_start = 0;
  67625. x_step = 1;
  67626. x_end = header.width;
  67627. y_start = header.height - 1;
  67628. y_step = -1;
  67629. y_end = -1;
  67630. break;
  67631. case TGATools._ORIGIN_UR:
  67632. x_start = header.width - 1;
  67633. x_step = -1;
  67634. x_end = -1;
  67635. y_start = 0;
  67636. y_step = 1;
  67637. y_end = header.height;
  67638. break;
  67639. case TGATools._ORIGIN_BR:
  67640. x_start = header.width - 1;
  67641. x_step = -1;
  67642. x_end = -1;
  67643. y_start = header.height - 1;
  67644. y_step = -1;
  67645. y_end = -1;
  67646. break;
  67647. }
  67648. // Load the specify method
  67649. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  67650. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  67651. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  67652. };
  67653. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67654. var image = pixel_data, colormap = palettes;
  67655. var width = header.width, height = header.height;
  67656. var color, i = 0, x, y;
  67657. var imageData = new Uint8Array(width * height * 4);
  67658. for (y = y_start; y !== y_end; y += y_step) {
  67659. for (x = x_start; x !== x_end; x += x_step, i++) {
  67660. color = image[i];
  67661. imageData[(x + width * y) * 4 + 3] = 255;
  67662. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  67663. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  67664. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  67665. }
  67666. }
  67667. return imageData;
  67668. };
  67669. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67670. var image = pixel_data;
  67671. var width = header.width, height = header.height;
  67672. var color, i = 0, x, y;
  67673. var imageData = new Uint8Array(width * height * 4);
  67674. for (y = y_start; y !== y_end; y += y_step) {
  67675. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  67676. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  67677. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  67678. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  67679. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  67680. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  67681. }
  67682. }
  67683. return imageData;
  67684. };
  67685. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67686. var image = pixel_data;
  67687. var width = header.width, height = header.height;
  67688. var i = 0, x, y;
  67689. var imageData = new Uint8Array(width * height * 4);
  67690. for (y = y_start; y !== y_end; y += y_step) {
  67691. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  67692. imageData[(x + width * y) * 4 + 3] = 255;
  67693. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67694. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  67695. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  67696. }
  67697. }
  67698. return imageData;
  67699. };
  67700. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67701. var image = pixel_data;
  67702. var width = header.width, height = header.height;
  67703. var i = 0, x, y;
  67704. var imageData = new Uint8Array(width * height * 4);
  67705. for (y = y_start; y !== y_end; y += y_step) {
  67706. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  67707. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67708. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  67709. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  67710. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  67711. }
  67712. }
  67713. return imageData;
  67714. };
  67715. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67716. var image = pixel_data;
  67717. var width = header.width, height = header.height;
  67718. var color, i = 0, x, y;
  67719. var imageData = new Uint8Array(width * height * 4);
  67720. for (y = y_start; y !== y_end; y += y_step) {
  67721. for (x = x_start; x !== x_end; x += x_step, i++) {
  67722. color = image[i];
  67723. imageData[(x + width * y) * 4 + 0] = color;
  67724. imageData[(x + width * y) * 4 + 1] = color;
  67725. imageData[(x + width * y) * 4 + 2] = color;
  67726. imageData[(x + width * y) * 4 + 3] = 255;
  67727. }
  67728. }
  67729. return imageData;
  67730. };
  67731. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67732. var image = pixel_data;
  67733. var width = header.width, height = header.height;
  67734. var i = 0, x, y;
  67735. var imageData = new Uint8Array(width * height * 4);
  67736. for (y = y_start; y !== y_end; y += y_step) {
  67737. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  67738. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  67739. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  67740. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67741. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  67742. }
  67743. }
  67744. return imageData;
  67745. };
  67746. //private static _TYPE_NO_DATA = 0;
  67747. TGATools._TYPE_INDEXED = 1;
  67748. TGATools._TYPE_RGB = 2;
  67749. TGATools._TYPE_GREY = 3;
  67750. TGATools._TYPE_RLE_INDEXED = 9;
  67751. TGATools._TYPE_RLE_RGB = 10;
  67752. TGATools._TYPE_RLE_GREY = 11;
  67753. TGATools._ORIGIN_MASK = 0x30;
  67754. TGATools._ORIGIN_SHIFT = 0x04;
  67755. TGATools._ORIGIN_BL = 0x00;
  67756. TGATools._ORIGIN_BR = 0x01;
  67757. TGATools._ORIGIN_UL = 0x02;
  67758. TGATools._ORIGIN_UR = 0x03;
  67759. return TGATools;
  67760. }());
  67761. Internals.TGATools = TGATools;
  67762. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67763. })(BABYLON || (BABYLON = {}));
  67764. //# sourceMappingURL=babylon.tga.js.map
  67765. var BABYLON;
  67766. (function (BABYLON) {
  67767. var Internals;
  67768. (function (Internals) {
  67769. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  67770. // All values and structures referenced from:
  67771. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  67772. var DDS_MAGIC = 0x20534444;
  67773. var
  67774. //DDSD_CAPS = 0x1,
  67775. //DDSD_HEIGHT = 0x2,
  67776. //DDSD_WIDTH = 0x4,
  67777. //DDSD_PITCH = 0x8,
  67778. //DDSD_PIXELFORMAT = 0x1000,
  67779. DDSD_MIPMAPCOUNT = 0x20000;
  67780. //DDSD_LINEARSIZE = 0x80000,
  67781. //DDSD_DEPTH = 0x800000;
  67782. // var DDSCAPS_COMPLEX = 0x8,
  67783. // DDSCAPS_MIPMAP = 0x400000,
  67784. // DDSCAPS_TEXTURE = 0x1000;
  67785. var DDSCAPS2_CUBEMAP = 0x200;
  67786. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  67787. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  67788. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  67789. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  67790. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  67791. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  67792. // DDSCAPS2_VOLUME = 0x200000;
  67793. var
  67794. //DDPF_ALPHAPIXELS = 0x1,
  67795. //DDPF_ALPHA = 0x2,
  67796. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  67797. //DDPF_YUV = 0x200,
  67798. DDPF_LUMINANCE = 0x20000;
  67799. function FourCCToInt32(value) {
  67800. return value.charCodeAt(0) +
  67801. (value.charCodeAt(1) << 8) +
  67802. (value.charCodeAt(2) << 16) +
  67803. (value.charCodeAt(3) << 24);
  67804. }
  67805. function Int32ToFourCC(value) {
  67806. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  67807. }
  67808. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  67809. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  67810. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  67811. var FOURCC_DX10 = FourCCToInt32("DX10");
  67812. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  67813. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  67814. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  67815. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  67816. var headerLengthInt = 31; // The header length in 32 bit ints
  67817. // Offsets into the header array
  67818. var off_magic = 0;
  67819. var off_size = 1;
  67820. var off_flags = 2;
  67821. var off_height = 3;
  67822. var off_width = 4;
  67823. var off_mipmapCount = 7;
  67824. var off_pfFlags = 20;
  67825. var off_pfFourCC = 21;
  67826. var off_RGBbpp = 22;
  67827. // var off_RMask = 23;
  67828. // var off_GMask = 24;
  67829. // var off_BMask = 25;
  67830. // var off_AMask = 26;
  67831. // var off_caps1 = 27;
  67832. var off_caps2 = 28;
  67833. // var off_caps3 = 29;
  67834. // var off_caps4 = 30;
  67835. var off_dxgiFormat = 32;
  67836. ;
  67837. var DDSTools = /** @class */ (function () {
  67838. function DDSTools() {
  67839. }
  67840. DDSTools.GetDDSInfo = function (arrayBuffer) {
  67841. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  67842. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  67843. var mipmapCount = 1;
  67844. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  67845. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67846. }
  67847. var fourCC = header[off_pfFourCC];
  67848. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  67849. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67850. switch (fourCC) {
  67851. case FOURCC_D3DFMT_R16G16B16A16F:
  67852. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67853. break;
  67854. case FOURCC_D3DFMT_R32G32B32A32F:
  67855. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67856. break;
  67857. case FOURCC_DX10:
  67858. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  67859. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67860. break;
  67861. }
  67862. }
  67863. return {
  67864. width: header[off_width],
  67865. height: header[off_height],
  67866. mipmapCount: mipmapCount,
  67867. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  67868. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  67869. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  67870. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  67871. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  67872. dxgiFormat: dxgiFormat,
  67873. textureType: textureType
  67874. };
  67875. };
  67876. DDSTools._ToHalfFloat = function (value) {
  67877. if (!DDSTools._FloatView) {
  67878. DDSTools._FloatView = new Float32Array(1);
  67879. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  67880. }
  67881. DDSTools._FloatView[0] = value;
  67882. var x = DDSTools._Int32View[0];
  67883. var bits = (x >> 16) & 0x8000; /* Get the sign */
  67884. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  67885. var e = (x >> 23) & 0xff; /* Using int is faster here */
  67886. /* If zero, or denormal, or exponent underflows too much for a denormal
  67887. * half, return signed zero. */
  67888. if (e < 103) {
  67889. return bits;
  67890. }
  67891. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  67892. if (e > 142) {
  67893. bits |= 0x7c00;
  67894. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  67895. * not Inf, so make sure we set one mantissa bit too. */
  67896. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  67897. return bits;
  67898. }
  67899. /* If exponent underflows but not too much, return a denormal */
  67900. if (e < 113) {
  67901. m |= 0x0800;
  67902. /* Extra rounding may overflow and set mantissa to 0 and exponent
  67903. * to 1, which is OK. */
  67904. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  67905. return bits;
  67906. }
  67907. bits |= ((e - 112) << 10) | (m >> 1);
  67908. bits += m & 1;
  67909. return bits;
  67910. };
  67911. DDSTools._FromHalfFloat = function (value) {
  67912. var s = (value & 0x8000) >> 15;
  67913. var e = (value & 0x7C00) >> 10;
  67914. var f = value & 0x03FF;
  67915. if (e === 0) {
  67916. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  67917. }
  67918. else if (e == 0x1F) {
  67919. return f ? NaN : ((s ? -1 : 1) * Infinity);
  67920. }
  67921. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  67922. };
  67923. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67924. var destArray = new Float32Array(dataLength);
  67925. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67926. var index = 0;
  67927. for (var y = 0; y < height; y++) {
  67928. for (var x = 0; x < width; x++) {
  67929. var srcPos = (x + y * width) * 4;
  67930. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  67931. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  67932. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  67933. if (DDSTools.StoreLODInAlphaChannel) {
  67934. destArray[index + 3] = lod;
  67935. }
  67936. else {
  67937. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  67938. }
  67939. index += 4;
  67940. }
  67941. }
  67942. return destArray;
  67943. };
  67944. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67945. if (DDSTools.StoreLODInAlphaChannel) {
  67946. var destArray = new Uint16Array(dataLength);
  67947. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67948. var index = 0;
  67949. for (var y = 0; y < height; y++) {
  67950. for (var x = 0; x < width; x++) {
  67951. var srcPos = (x + y * width) * 4;
  67952. destArray[index] = srcData[srcPos];
  67953. destArray[index + 1] = srcData[srcPos + 1];
  67954. destArray[index + 2] = srcData[srcPos + 2];
  67955. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  67956. index += 4;
  67957. }
  67958. }
  67959. return destArray;
  67960. }
  67961. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  67962. };
  67963. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67964. if (DDSTools.StoreLODInAlphaChannel) {
  67965. var destArray = new Float32Array(dataLength);
  67966. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67967. var index = 0;
  67968. for (var y = 0; y < height; y++) {
  67969. for (var x = 0; x < width; x++) {
  67970. var srcPos = (x + y * width) * 4;
  67971. destArray[index] = srcData[srcPos];
  67972. destArray[index + 1] = srcData[srcPos + 1];
  67973. destArray[index + 2] = srcData[srcPos + 2];
  67974. destArray[index + 3] = lod;
  67975. index += 4;
  67976. }
  67977. }
  67978. return destArray;
  67979. }
  67980. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  67981. };
  67982. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67983. var destArray = new Uint8Array(dataLength);
  67984. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67985. var index = 0;
  67986. for (var y = 0; y < height; y++) {
  67987. for (var x = 0; x < width; x++) {
  67988. var srcPos = (x + y * width) * 4;
  67989. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  67990. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  67991. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  67992. if (DDSTools.StoreLODInAlphaChannel) {
  67993. destArray[index + 3] = lod;
  67994. }
  67995. else {
  67996. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  67997. }
  67998. index += 4;
  67999. }
  68000. }
  68001. return destArray;
  68002. };
  68003. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  68004. var destArray = new Uint8Array(dataLength);
  68005. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  68006. var index = 0;
  68007. for (var y = 0; y < height; y++) {
  68008. for (var x = 0; x < width; x++) {
  68009. var srcPos = (x + y * width) * 4;
  68010. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  68011. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  68012. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  68013. if (DDSTools.StoreLODInAlphaChannel) {
  68014. destArray[index + 3] = lod;
  68015. }
  68016. else {
  68017. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  68018. }
  68019. index += 4;
  68020. }
  68021. }
  68022. return destArray;
  68023. };
  68024. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68025. var byteArray = new Uint8Array(dataLength);
  68026. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68027. var index = 0;
  68028. for (var y = 0; y < height; y++) {
  68029. for (var x = 0; x < width; x++) {
  68030. var srcPos = (x + y * width) * 4;
  68031. byteArray[index] = srcData[srcPos + 2];
  68032. byteArray[index + 1] = srcData[srcPos + 1];
  68033. byteArray[index + 2] = srcData[srcPos];
  68034. byteArray[index + 3] = srcData[srcPos + 3];
  68035. index += 4;
  68036. }
  68037. }
  68038. return byteArray;
  68039. };
  68040. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68041. var byteArray = new Uint8Array(dataLength);
  68042. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68043. var index = 0;
  68044. for (var y = 0; y < height; y++) {
  68045. for (var x = 0; x < width; x++) {
  68046. var srcPos = (x + y * width) * 3;
  68047. byteArray[index] = srcData[srcPos + 2];
  68048. byteArray[index + 1] = srcData[srcPos + 1];
  68049. byteArray[index + 2] = srcData[srcPos];
  68050. index += 3;
  68051. }
  68052. }
  68053. return byteArray;
  68054. };
  68055. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  68056. var byteArray = new Uint8Array(dataLength);
  68057. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  68058. var index = 0;
  68059. for (var y = 0; y < height; y++) {
  68060. for (var x = 0; x < width; x++) {
  68061. var srcPos = (x + y * width);
  68062. byteArray[index] = srcData[srcPos];
  68063. index++;
  68064. }
  68065. }
  68066. return byteArray;
  68067. };
  68068. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  68069. if (lodIndex === void 0) { lodIndex = -1; }
  68070. var ext = engine.getCaps().s3tc;
  68071. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  68072. var internalFormat = 0;
  68073. var format = 0;
  68074. var blockBytes = 1;
  68075. if (header[off_magic] != DDS_MAGIC) {
  68076. BABYLON.Tools.Error("Invalid magic number in DDS header");
  68077. return;
  68078. }
  68079. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  68080. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  68081. return;
  68082. }
  68083. if (info.isCompressed && !ext) {
  68084. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  68085. return;
  68086. }
  68087. var bpp = header[off_RGBbpp];
  68088. dataOffset = header[off_size] + 4;
  68089. var computeFormats = false;
  68090. if (info.isFourCC) {
  68091. fourCC = header[off_pfFourCC];
  68092. switch (fourCC) {
  68093. case FOURCC_DXT1:
  68094. blockBytes = 8;
  68095. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  68096. break;
  68097. case FOURCC_DXT3:
  68098. blockBytes = 16;
  68099. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  68100. break;
  68101. case FOURCC_DXT5:
  68102. blockBytes = 16;
  68103. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  68104. break;
  68105. case FOURCC_D3DFMT_R16G16B16A16F:
  68106. computeFormats = true;
  68107. break;
  68108. case FOURCC_D3DFMT_R32G32B32A32F:
  68109. computeFormats = true;
  68110. break;
  68111. case FOURCC_DX10:
  68112. // There is an additionnal header so dataOffset need to be changed
  68113. dataOffset += 5 * 4; // 5 uints
  68114. var supported = false;
  68115. switch (info.dxgiFormat) {
  68116. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  68117. computeFormats = true;
  68118. supported = true;
  68119. break;
  68120. case DXGI_FORMAT_B8G8R8X8_UNORM:
  68121. info.isRGB = true;
  68122. info.isFourCC = false;
  68123. bpp = 32;
  68124. supported = true;
  68125. break;
  68126. }
  68127. if (supported) {
  68128. break;
  68129. }
  68130. default:
  68131. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  68132. return;
  68133. }
  68134. }
  68135. if (computeFormats) {
  68136. format = engine._getWebGLTextureType(info.textureType);
  68137. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68138. }
  68139. mipmapCount = 1;
  68140. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  68141. mipmapCount = Math.max(1, header[off_mipmapCount]);
  68142. }
  68143. for (var face = 0; face < faces; face++) {
  68144. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  68145. width = header[off_width];
  68146. height = header[off_height];
  68147. for (mip = 0; mip < mipmapCount; ++mip) {
  68148. if (lodIndex === -1 || lodIndex === mip) {
  68149. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  68150. var i = (lodIndex === -1) ? mip : 0;
  68151. if (!info.isCompressed && info.isFourCC) {
  68152. dataLength = width * height * 4;
  68153. var FloatArray = null;
  68154. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  68155. if (bpp === 128) {
  68156. FloatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68157. }
  68158. else if (bpp === 64) {
  68159. FloatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68160. }
  68161. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68162. format = engine._getWebGLTextureType(info.textureType);
  68163. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68164. }
  68165. else {
  68166. if (bpp === 128) {
  68167. FloatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68168. }
  68169. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  68170. FloatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68171. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68172. format = engine._getWebGLTextureType(info.textureType);
  68173. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  68174. }
  68175. else {
  68176. FloatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  68177. }
  68178. }
  68179. if (FloatArray) {
  68180. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, FloatArray);
  68181. }
  68182. }
  68183. else if (info.isRGB) {
  68184. if (bpp === 24) {
  68185. dataLength = width * height * 3;
  68186. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68187. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  68188. }
  68189. else {
  68190. dataLength = width * height * 4;
  68191. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68192. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  68193. }
  68194. }
  68195. else if (info.isLuminance) {
  68196. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  68197. var unpaddedRowSize = width;
  68198. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  68199. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  68200. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  68201. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  68202. }
  68203. else {
  68204. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  68205. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  68206. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  68207. }
  68208. }
  68209. dataOffset += width * height * (bpp / 8);
  68210. width *= 0.5;
  68211. height *= 0.5;
  68212. width = Math.max(1.0, width);
  68213. height = Math.max(1.0, height);
  68214. }
  68215. }
  68216. };
  68217. DDSTools.StoreLODInAlphaChannel = false;
  68218. return DDSTools;
  68219. }());
  68220. Internals.DDSTools = DDSTools;
  68221. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68222. })(BABYLON || (BABYLON = {}));
  68223. //# sourceMappingURL=babylon.dds.js.map
  68224. var BABYLON;
  68225. (function (BABYLON) {
  68226. var Internals;
  68227. (function (Internals) {
  68228. /**
  68229. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  68230. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  68231. */
  68232. var KhronosTextureContainer = /** @class */ (function () {
  68233. /**
  68234. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  68235. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  68236. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  68237. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  68238. */
  68239. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  68240. this.arrayBuffer = arrayBuffer;
  68241. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  68242. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  68243. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  68244. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  68245. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  68246. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  68247. BABYLON.Tools.Error("texture missing KTX identifier");
  68248. return;
  68249. }
  68250. // load the reset of the header in native 32 bit int
  68251. var header = new Int32Array(this.arrayBuffer, 12, 13);
  68252. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  68253. var oppositeEndianess = header[0] === 0x01020304;
  68254. // read all the header elements in order they exist in the file, without modification (sans endainness)
  68255. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  68256. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  68257. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  68258. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  68259. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  68260. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  68261. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  68262. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  68263. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  68264. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  68265. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  68266. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  68267. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  68268. if (this.glType !== 0) {
  68269. BABYLON.Tools.Error("only compressed formats currently supported");
  68270. return;
  68271. }
  68272. else {
  68273. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  68274. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  68275. }
  68276. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  68277. BABYLON.Tools.Error("only 2D textures currently supported");
  68278. return;
  68279. }
  68280. if (this.numberOfArrayElements !== 0) {
  68281. BABYLON.Tools.Error("texture arrays not currently supported");
  68282. return;
  68283. }
  68284. if (this.numberOfFaces !== facesExpected) {
  68285. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  68286. return;
  68287. }
  68288. // we now have a completely validated file, so could use existence of loadType as success
  68289. // would need to make this more elaborate & adjust checks above to support more than one load type
  68290. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  68291. }
  68292. // not as fast hardware based, but will probably never need to use
  68293. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  68294. return ((val & 0xFF) << 24)
  68295. | ((val & 0xFF00) << 8)
  68296. | ((val >> 8) & 0xFF00)
  68297. | ((val >> 24) & 0xFF);
  68298. };
  68299. /**
  68300. * It is assumed that the texture has already been created & is currently bound
  68301. */
  68302. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  68303. switch (this.loadType) {
  68304. case KhronosTextureContainer.COMPRESSED_2D:
  68305. this._upload2DCompressedLevels(gl, loadMipmaps);
  68306. break;
  68307. case KhronosTextureContainer.TEX_2D:
  68308. case KhronosTextureContainer.COMPRESSED_3D:
  68309. case KhronosTextureContainer.TEX_3D:
  68310. }
  68311. };
  68312. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  68313. // initialize width & height for level 1
  68314. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  68315. var width = this.pixelWidth;
  68316. var height = this.pixelHeight;
  68317. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  68318. for (var level = 0; level < mipmapCount; level++) {
  68319. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  68320. for (var face = 0; face < this.numberOfFaces; face++) {
  68321. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  68322. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  68323. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  68324. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  68325. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  68326. }
  68327. width = Math.max(1.0, width * 0.5);
  68328. height = Math.max(1.0, height * 0.5);
  68329. }
  68330. };
  68331. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  68332. // load types
  68333. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  68334. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  68335. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  68336. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  68337. return KhronosTextureContainer;
  68338. }());
  68339. Internals.KhronosTextureContainer = KhronosTextureContainer;
  68340. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  68341. })(BABYLON || (BABYLON = {}));
  68342. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  68343. var BABYLON;
  68344. (function (BABYLON) {
  68345. var Debug;
  68346. (function (Debug) {
  68347. /**
  68348. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  68349. */
  68350. var SkeletonViewer = /** @class */ (function () {
  68351. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  68352. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  68353. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  68354. this.skeleton = skeleton;
  68355. this.mesh = mesh;
  68356. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  68357. this.renderingGroupId = renderingGroupId;
  68358. this.color = BABYLON.Color3.White();
  68359. this._debugLines = new Array();
  68360. this._isEnabled = false;
  68361. this._scene = scene;
  68362. this.update();
  68363. this._renderFunction = this.update.bind(this);
  68364. }
  68365. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  68366. get: function () {
  68367. return this._isEnabled;
  68368. },
  68369. set: function (value) {
  68370. if (this._isEnabled === value) {
  68371. return;
  68372. }
  68373. this._isEnabled = value;
  68374. if (value) {
  68375. this._scene.registerBeforeRender(this._renderFunction);
  68376. }
  68377. else {
  68378. this._scene.unregisterBeforeRender(this._renderFunction);
  68379. }
  68380. },
  68381. enumerable: true,
  68382. configurable: true
  68383. });
  68384. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  68385. if (x === void 0) { x = 0; }
  68386. if (y === void 0) { y = 0; }
  68387. if (z === void 0) { z = 0; }
  68388. var tmat = BABYLON.Tmp.Matrix[0];
  68389. var parentBone = bone.getParent();
  68390. tmat.copyFrom(bone.getLocalMatrix());
  68391. if (x !== 0 || y !== 0 || z !== 0) {
  68392. var tmat2 = BABYLON.Tmp.Matrix[1];
  68393. BABYLON.Matrix.IdentityToRef(tmat2);
  68394. tmat2.m[12] = x;
  68395. tmat2.m[13] = y;
  68396. tmat2.m[14] = z;
  68397. tmat2.multiplyToRef(tmat, tmat);
  68398. }
  68399. if (parentBone) {
  68400. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  68401. }
  68402. tmat.multiplyToRef(meshMat, tmat);
  68403. position.x = tmat.m[12];
  68404. position.y = tmat.m[13];
  68405. position.z = tmat.m[14];
  68406. };
  68407. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  68408. var len = bones.length;
  68409. var meshPos = this.mesh.position;
  68410. for (var i = 0; i < len; i++) {
  68411. var bone = bones[i];
  68412. var points = this._debugLines[i];
  68413. if (!points) {
  68414. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68415. this._debugLines[i] = points;
  68416. }
  68417. this._getBonePosition(points[0], bone, meshMat);
  68418. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  68419. points[0].subtractInPlace(meshPos);
  68420. points[1].subtractInPlace(meshPos);
  68421. }
  68422. };
  68423. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  68424. var len = bones.length;
  68425. var boneNum = 0;
  68426. var meshPos = this.mesh.position;
  68427. for (var i = len - 1; i >= 0; i--) {
  68428. var childBone = bones[i];
  68429. var parentBone = childBone.getParent();
  68430. if (!parentBone) {
  68431. continue;
  68432. }
  68433. var points = this._debugLines[boneNum];
  68434. if (!points) {
  68435. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68436. this._debugLines[boneNum] = points;
  68437. }
  68438. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  68439. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  68440. points[0].subtractInPlace(meshPos);
  68441. points[1].subtractInPlace(meshPos);
  68442. boneNum++;
  68443. }
  68444. };
  68445. SkeletonViewer.prototype.update = function () {
  68446. if (this.autoUpdateBonesMatrices) {
  68447. this.skeleton.computeAbsoluteTransforms();
  68448. }
  68449. if (this.skeleton.bones[0].length === undefined) {
  68450. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  68451. }
  68452. else {
  68453. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  68454. }
  68455. if (!this._debugMesh) {
  68456. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  68457. this._debugMesh.renderingGroupId = this.renderingGroupId;
  68458. }
  68459. else {
  68460. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  68461. }
  68462. this._debugMesh.position.copyFrom(this.mesh.position);
  68463. this._debugMesh.color = this.color;
  68464. };
  68465. SkeletonViewer.prototype.dispose = function () {
  68466. if (this._debugMesh) {
  68467. this.isEnabled = false;
  68468. this._debugMesh.dispose();
  68469. this._debugMesh = null;
  68470. }
  68471. };
  68472. return SkeletonViewer;
  68473. }());
  68474. Debug.SkeletonViewer = SkeletonViewer;
  68475. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68476. })(BABYLON || (BABYLON = {}));
  68477. //# sourceMappingURL=babylon.skeletonViewer.js.map
  68478. var BABYLON;
  68479. (function (BABYLON) {
  68480. var Debug;
  68481. (function (Debug) {
  68482. var AxesViewer = /** @class */ (function () {
  68483. function AxesViewer(scene, scaleLines) {
  68484. if (scaleLines === void 0) { scaleLines = 1; }
  68485. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68486. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68487. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68488. this.scaleLines = 1;
  68489. this.scaleLines = scaleLines;
  68490. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  68491. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  68492. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  68493. this._xmesh.renderingGroupId = 2;
  68494. this._ymesh.renderingGroupId = 2;
  68495. this._zmesh.renderingGroupId = 2;
  68496. this._xmesh.material.checkReadyOnlyOnce = true;
  68497. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  68498. this._ymesh.material.checkReadyOnlyOnce = true;
  68499. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  68500. this._zmesh.material.checkReadyOnlyOnce = true;
  68501. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  68502. this.scene = scene;
  68503. }
  68504. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  68505. var scaleLines = this.scaleLines;
  68506. if (this._xmesh) {
  68507. this._xmesh.position.copyFrom(position);
  68508. }
  68509. if (this._ymesh) {
  68510. this._ymesh.position.copyFrom(position);
  68511. }
  68512. if (this._zmesh) {
  68513. this._zmesh.position.copyFrom(position);
  68514. }
  68515. var point2 = this._xline[1];
  68516. point2.x = xaxis.x * scaleLines;
  68517. point2.y = xaxis.y * scaleLines;
  68518. point2.z = xaxis.z * scaleLines;
  68519. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  68520. point2 = this._yline[1];
  68521. point2.x = yaxis.x * scaleLines;
  68522. point2.y = yaxis.y * scaleLines;
  68523. point2.z = yaxis.z * scaleLines;
  68524. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  68525. point2 = this._zline[1];
  68526. point2.x = zaxis.x * scaleLines;
  68527. point2.y = zaxis.y * scaleLines;
  68528. point2.z = zaxis.z * scaleLines;
  68529. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  68530. };
  68531. AxesViewer.prototype.dispose = function () {
  68532. if (this._xmesh) {
  68533. this._xmesh.dispose();
  68534. }
  68535. if (this._ymesh) {
  68536. this._ymesh.dispose();
  68537. }
  68538. if (this._zmesh) {
  68539. this._zmesh.dispose();
  68540. }
  68541. this._xmesh = null;
  68542. this._ymesh = null;
  68543. this._zmesh = null;
  68544. this.scene = null;
  68545. };
  68546. return AxesViewer;
  68547. }());
  68548. Debug.AxesViewer = AxesViewer;
  68549. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68550. })(BABYLON || (BABYLON = {}));
  68551. //# sourceMappingURL=babylon.axesViewer.js.map
  68552. var BABYLON;
  68553. (function (BABYLON) {
  68554. var Debug;
  68555. (function (Debug) {
  68556. var BoneAxesViewer = /** @class */ (function (_super) {
  68557. __extends(BoneAxesViewer, _super);
  68558. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  68559. if (scaleLines === void 0) { scaleLines = 1; }
  68560. var _this = _super.call(this, scene, scaleLines) || this;
  68561. _this.pos = BABYLON.Vector3.Zero();
  68562. _this.xaxis = BABYLON.Vector3.Zero();
  68563. _this.yaxis = BABYLON.Vector3.Zero();
  68564. _this.zaxis = BABYLON.Vector3.Zero();
  68565. _this.mesh = mesh;
  68566. _this.bone = bone;
  68567. return _this;
  68568. }
  68569. BoneAxesViewer.prototype.update = function () {
  68570. if (!this.mesh || !this.bone) {
  68571. return;
  68572. }
  68573. var bone = this.bone;
  68574. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  68575. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  68576. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  68577. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  68578. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  68579. };
  68580. BoneAxesViewer.prototype.dispose = function () {
  68581. if (this.mesh) {
  68582. this.mesh = null;
  68583. this.bone = null;
  68584. _super.prototype.dispose.call(this);
  68585. }
  68586. };
  68587. return BoneAxesViewer;
  68588. }(Debug.AxesViewer));
  68589. Debug.BoneAxesViewer = BoneAxesViewer;
  68590. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68591. })(BABYLON || (BABYLON = {}));
  68592. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  68593. var BABYLON;
  68594. (function (BABYLON) {
  68595. var RayHelper = /** @class */ (function () {
  68596. function RayHelper(ray) {
  68597. this.ray = ray;
  68598. }
  68599. RayHelper.CreateAndShow = function (ray, scene, color) {
  68600. var helper = new RayHelper(ray);
  68601. helper.show(scene, color);
  68602. return helper;
  68603. };
  68604. RayHelper.prototype.show = function (scene, color) {
  68605. if (!this._renderFunction && this.ray) {
  68606. var ray = this.ray;
  68607. this._renderFunction = this._render.bind(this);
  68608. this._scene = scene;
  68609. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  68610. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  68611. if (this._renderFunction) {
  68612. this._scene.registerBeforeRender(this._renderFunction);
  68613. }
  68614. }
  68615. if (color && this._renderLine) {
  68616. this._renderLine.color.copyFrom(color);
  68617. }
  68618. };
  68619. RayHelper.prototype.hide = function () {
  68620. if (this._renderFunction && this._scene) {
  68621. this._scene.unregisterBeforeRender(this._renderFunction);
  68622. this._scene = null;
  68623. this._renderFunction = null;
  68624. if (this._renderLine) {
  68625. this._renderLine.dispose();
  68626. this._renderLine = null;
  68627. }
  68628. this._renderPoints = [];
  68629. }
  68630. };
  68631. RayHelper.prototype._render = function () {
  68632. var ray = this.ray;
  68633. if (!ray) {
  68634. return;
  68635. }
  68636. var point = this._renderPoints[1];
  68637. var len = Math.min(ray.length, 1000000);
  68638. point.copyFrom(ray.direction);
  68639. point.scaleInPlace(len);
  68640. point.addInPlace(ray.origin);
  68641. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  68642. };
  68643. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  68644. this._attachedToMesh = mesh;
  68645. var ray = this.ray;
  68646. if (!ray) {
  68647. return;
  68648. }
  68649. if (!ray.direction) {
  68650. ray.direction = BABYLON.Vector3.Zero();
  68651. }
  68652. if (!ray.origin) {
  68653. ray.origin = BABYLON.Vector3.Zero();
  68654. }
  68655. if (length) {
  68656. ray.length = length;
  68657. }
  68658. if (!meshSpaceOrigin) {
  68659. meshSpaceOrigin = BABYLON.Vector3.Zero();
  68660. }
  68661. if (!meshSpaceDirection) {
  68662. // -1 so that this will work with Mesh.lookAt
  68663. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  68664. }
  68665. if (!this._meshSpaceDirection) {
  68666. this._meshSpaceDirection = meshSpaceDirection.clone();
  68667. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  68668. }
  68669. else {
  68670. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  68671. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  68672. }
  68673. if (!this._updateToMeshFunction) {
  68674. this._updateToMeshFunction = this._updateToMesh.bind(this);
  68675. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  68676. }
  68677. this._updateToMesh();
  68678. };
  68679. RayHelper.prototype.detachFromMesh = function () {
  68680. if (this._attachedToMesh) {
  68681. if (this._updateToMeshFunction) {
  68682. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  68683. }
  68684. this._attachedToMesh = null;
  68685. this._updateToMeshFunction = null;
  68686. }
  68687. };
  68688. RayHelper.prototype._updateToMesh = function () {
  68689. var ray = this.ray;
  68690. if (!this._attachedToMesh || !ray) {
  68691. return;
  68692. }
  68693. if (this._attachedToMesh._isDisposed) {
  68694. this.detachFromMesh();
  68695. return;
  68696. }
  68697. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  68698. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  68699. };
  68700. RayHelper.prototype.dispose = function () {
  68701. this.hide();
  68702. this.detachFromMesh();
  68703. this.ray = null;
  68704. };
  68705. return RayHelper;
  68706. }());
  68707. BABYLON.RayHelper = RayHelper;
  68708. })(BABYLON || (BABYLON = {}));
  68709. //# sourceMappingURL=babylon.rayHelper.js.map
  68710. var BABYLON;
  68711. (function (BABYLON) {
  68712. // load the inspector using require, if not present in the global namespace.
  68713. var DebugLayer = /** @class */ (function () {
  68714. function DebugLayer(scene) {
  68715. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  68716. this._scene = scene;
  68717. // load inspector using require, if it doesn't exist on the global namespace.
  68718. }
  68719. /** Creates the inspector window. */
  68720. DebugLayer.prototype._createInspector = function (config) {
  68721. if (config === void 0) { config = {}; }
  68722. var popup = config.popup || false;
  68723. var initialTab = config.initialTab || 0;
  68724. var parentElement = config.parentElement || null;
  68725. if (!this._inspector) {
  68726. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  68727. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  68728. } // else nothing to do,; instance is already existing
  68729. };
  68730. DebugLayer.prototype.isVisible = function () {
  68731. if (!this._inspector) {
  68732. return false;
  68733. }
  68734. return true;
  68735. };
  68736. DebugLayer.prototype.hide = function () {
  68737. if (this._inspector) {
  68738. try {
  68739. this._inspector.dispose();
  68740. }
  68741. catch (e) {
  68742. // If the inspector has been removed directly from the inspector tool
  68743. }
  68744. this._inspector = null;
  68745. }
  68746. };
  68747. DebugLayer.prototype.show = function (config) {
  68748. if (config === void 0) { config = {}; }
  68749. if (typeof this.BJSINSPECTOR == 'undefined') {
  68750. // Load inspector and add it to the DOM
  68751. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  68752. }
  68753. else {
  68754. // Otherwise creates the inspector
  68755. this._createInspector(config);
  68756. }
  68757. };
  68758. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  68759. return DebugLayer;
  68760. }());
  68761. BABYLON.DebugLayer = DebugLayer;
  68762. })(BABYLON || (BABYLON = {}));
  68763. //# sourceMappingURL=babylon.debugLayer.js.map
  68764. var BABYLON;
  68765. (function (BABYLON) {
  68766. var Debug;
  68767. (function (Debug) {
  68768. var PhysicsViewer = /** @class */ (function () {
  68769. function PhysicsViewer(scene) {
  68770. this._impostors = [];
  68771. this._meshes = [];
  68772. this._numMeshes = 0;
  68773. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68774. var physicEngine = this._scene.getPhysicsEngine();
  68775. if (physicEngine) {
  68776. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  68777. }
  68778. }
  68779. PhysicsViewer.prototype._updateDebugMeshes = function () {
  68780. var plugin = this._physicsEnginePlugin;
  68781. for (var i = 0; i < this._numMeshes; i++) {
  68782. var impostor = this._impostors[i];
  68783. if (!impostor) {
  68784. continue;
  68785. }
  68786. if (impostor.isDisposed) {
  68787. this.hideImpostor(this._impostors[i--]);
  68788. }
  68789. else {
  68790. var mesh = this._meshes[i];
  68791. if (mesh && plugin) {
  68792. plugin.syncMeshWithImpostor(mesh, impostor);
  68793. }
  68794. }
  68795. }
  68796. };
  68797. PhysicsViewer.prototype.showImpostor = function (impostor) {
  68798. if (!this._scene) {
  68799. return;
  68800. }
  68801. for (var i = 0; i < this._numMeshes; i++) {
  68802. if (this._impostors[i] == impostor) {
  68803. return;
  68804. }
  68805. }
  68806. var debugMesh = this._getDebugMesh(impostor, this._scene);
  68807. if (debugMesh) {
  68808. this._impostors[this._numMeshes] = impostor;
  68809. this._meshes[this._numMeshes] = debugMesh;
  68810. if (this._numMeshes === 0) {
  68811. this._renderFunction = this._updateDebugMeshes.bind(this);
  68812. this._scene.registerBeforeRender(this._renderFunction);
  68813. }
  68814. this._numMeshes++;
  68815. }
  68816. };
  68817. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  68818. if (!impostor || !this._scene) {
  68819. return;
  68820. }
  68821. var removed = false;
  68822. for (var i = 0; i < this._numMeshes; i++) {
  68823. if (this._impostors[i] == impostor) {
  68824. var mesh = this._meshes[i];
  68825. if (!mesh) {
  68826. continue;
  68827. }
  68828. this._scene.removeMesh(mesh);
  68829. mesh.dispose();
  68830. this._numMeshes--;
  68831. if (this._numMeshes > 0) {
  68832. this._meshes[i] = this._meshes[this._numMeshes];
  68833. this._impostors[i] = this._impostors[this._numMeshes];
  68834. this._meshes[this._numMeshes] = null;
  68835. this._impostors[this._numMeshes] = null;
  68836. }
  68837. else {
  68838. this._meshes[0] = null;
  68839. this._impostors[0] = null;
  68840. }
  68841. removed = true;
  68842. break;
  68843. }
  68844. }
  68845. if (removed && this._numMeshes === 0) {
  68846. this._scene.unregisterBeforeRender(this._renderFunction);
  68847. }
  68848. };
  68849. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  68850. if (!this._debugMaterial) {
  68851. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  68852. this._debugMaterial.wireframe = true;
  68853. }
  68854. return this._debugMaterial;
  68855. };
  68856. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  68857. if (!this._debugBoxMesh) {
  68858. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  68859. this._debugBoxMesh.renderingGroupId = 1;
  68860. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68861. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  68862. scene.removeMesh(this._debugBoxMesh);
  68863. }
  68864. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  68865. };
  68866. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  68867. if (!this._debugSphereMesh) {
  68868. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  68869. this._debugSphereMesh.renderingGroupId = 1;
  68870. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68871. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  68872. scene.removeMesh(this._debugSphereMesh);
  68873. }
  68874. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  68875. };
  68876. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  68877. var mesh = null;
  68878. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  68879. mesh = this._getDebugBoxMesh(scene);
  68880. impostor.getBoxSizeToRef(mesh.scaling);
  68881. }
  68882. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  68883. mesh = this._getDebugSphereMesh(scene);
  68884. var radius = impostor.getRadius();
  68885. mesh.scaling.x = radius * 2;
  68886. mesh.scaling.y = radius * 2;
  68887. mesh.scaling.z = radius * 2;
  68888. }
  68889. return mesh;
  68890. };
  68891. PhysicsViewer.prototype.dispose = function () {
  68892. for (var i = 0; i < this._numMeshes; i++) {
  68893. this.hideImpostor(this._impostors[i]);
  68894. }
  68895. if (this._debugBoxMesh) {
  68896. this._debugBoxMesh.dispose();
  68897. }
  68898. if (this._debugSphereMesh) {
  68899. this._debugSphereMesh.dispose();
  68900. }
  68901. if (this._debugMaterial) {
  68902. this._debugMaterial.dispose();
  68903. }
  68904. this._impostors.length = 0;
  68905. this._scene = null;
  68906. this._physicsEnginePlugin = null;
  68907. };
  68908. return PhysicsViewer;
  68909. }());
  68910. Debug.PhysicsViewer = PhysicsViewer;
  68911. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68912. })(BABYLON || (BABYLON = {}));
  68913. //# sourceMappingURL=babylon.physicsViewer.js.map
  68914. var BABYLON;
  68915. (function (BABYLON) {
  68916. var BoundingBoxRenderer = /** @class */ (function () {
  68917. function BoundingBoxRenderer(scene) {
  68918. this.frontColor = new BABYLON.Color3(1, 1, 1);
  68919. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  68920. this.showBackLines = true;
  68921. this.renderList = new BABYLON.SmartArray(32);
  68922. this._vertexBuffers = {};
  68923. this._scene = scene;
  68924. }
  68925. BoundingBoxRenderer.prototype._prepareRessources = function () {
  68926. if (this._colorShader) {
  68927. return;
  68928. }
  68929. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  68930. attributes: [BABYLON.VertexBuffer.PositionKind],
  68931. uniforms: ["world", "viewProjection", "color"]
  68932. });
  68933. var engine = this._scene.getEngine();
  68934. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  68935. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  68936. this._createIndexBuffer();
  68937. };
  68938. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  68939. var engine = this._scene.getEngine();
  68940. 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]);
  68941. };
  68942. BoundingBoxRenderer.prototype._rebuild = function () {
  68943. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68944. if (vb) {
  68945. vb._rebuild();
  68946. }
  68947. this._createIndexBuffer();
  68948. };
  68949. BoundingBoxRenderer.prototype.reset = function () {
  68950. this.renderList.reset();
  68951. };
  68952. BoundingBoxRenderer.prototype.render = function () {
  68953. if (this.renderList.length === 0) {
  68954. return;
  68955. }
  68956. this._prepareRessources();
  68957. if (!this._colorShader.isReady()) {
  68958. return;
  68959. }
  68960. var engine = this._scene.getEngine();
  68961. engine.setDepthWrite(false);
  68962. this._colorShader._preBind();
  68963. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  68964. var boundingBox = this.renderList.data[boundingBoxIndex];
  68965. var min = boundingBox.minimum;
  68966. var max = boundingBox.maximum;
  68967. var diff = max.subtract(min);
  68968. var median = min.add(diff.scale(0.5));
  68969. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68970. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68971. .multiply(boundingBox.getWorldMatrix());
  68972. // VBOs
  68973. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68974. if (this.showBackLines) {
  68975. // Back
  68976. engine.setDepthFunctionToGreaterOrEqual();
  68977. this._scene.resetCachedMaterial();
  68978. this._colorShader.setColor4("color", this.backColor.toColor4());
  68979. this._colorShader.bind(worldMatrix);
  68980. // Draw order
  68981. engine.draw(false, 0, 24);
  68982. }
  68983. // Front
  68984. engine.setDepthFunctionToLess();
  68985. this._scene.resetCachedMaterial();
  68986. this._colorShader.setColor4("color", this.frontColor.toColor4());
  68987. this._colorShader.bind(worldMatrix);
  68988. // Draw order
  68989. engine.draw(false, 0, 24);
  68990. }
  68991. this._colorShader.unbind();
  68992. engine.setDepthFunctionToLessOrEqual();
  68993. engine.setDepthWrite(true);
  68994. };
  68995. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  68996. this._prepareRessources();
  68997. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  68998. return;
  68999. }
  69000. var engine = this._scene.getEngine();
  69001. engine.setDepthWrite(false);
  69002. engine.setColorWrite(false);
  69003. this._colorShader._preBind();
  69004. var boundingBox = mesh._boundingInfo.boundingBox;
  69005. var min = boundingBox.minimum;
  69006. var max = boundingBox.maximum;
  69007. var diff = max.subtract(min);
  69008. var median = min.add(diff.scale(0.5));
  69009. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  69010. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  69011. .multiply(boundingBox.getWorldMatrix());
  69012. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  69013. engine.setDepthFunctionToLess();
  69014. this._scene.resetCachedMaterial();
  69015. this._colorShader.bind(worldMatrix);
  69016. engine.draw(false, 0, 24);
  69017. this._colorShader.unbind();
  69018. engine.setDepthFunctionToLessOrEqual();
  69019. engine.setDepthWrite(true);
  69020. engine.setColorWrite(true);
  69021. };
  69022. BoundingBoxRenderer.prototype.dispose = function () {
  69023. if (!this._colorShader) {
  69024. return;
  69025. }
  69026. this.renderList.dispose();
  69027. this._colorShader.dispose();
  69028. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69029. if (buffer) {
  69030. buffer.dispose();
  69031. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69032. }
  69033. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69034. };
  69035. return BoundingBoxRenderer;
  69036. }());
  69037. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  69038. })(BABYLON || (BABYLON = {}));
  69039. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  69040. var BABYLON;
  69041. (function (BABYLON) {
  69042. var MorphTarget = /** @class */ (function () {
  69043. function MorphTarget(name, influence) {
  69044. if (influence === void 0) { influence = 0; }
  69045. this.name = name;
  69046. this.animations = new Array();
  69047. this._positions = null;
  69048. this._normals = null;
  69049. this._tangents = null;
  69050. this.onInfluenceChanged = new BABYLON.Observable();
  69051. this.influence = influence;
  69052. }
  69053. Object.defineProperty(MorphTarget.prototype, "influence", {
  69054. get: function () {
  69055. return this._influence;
  69056. },
  69057. set: function (influence) {
  69058. if (this._influence === influence) {
  69059. return;
  69060. }
  69061. var previous = this._influence;
  69062. this._influence = influence;
  69063. if (this.onInfluenceChanged.hasObservers) {
  69064. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  69065. }
  69066. },
  69067. enumerable: true,
  69068. configurable: true
  69069. });
  69070. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  69071. get: function () {
  69072. return !!this._positions;
  69073. },
  69074. enumerable: true,
  69075. configurable: true
  69076. });
  69077. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  69078. get: function () {
  69079. return !!this._normals;
  69080. },
  69081. enumerable: true,
  69082. configurable: true
  69083. });
  69084. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  69085. get: function () {
  69086. return !!this._tangents;
  69087. },
  69088. enumerable: true,
  69089. configurable: true
  69090. });
  69091. MorphTarget.prototype.setPositions = function (data) {
  69092. this._positions = data;
  69093. };
  69094. MorphTarget.prototype.getPositions = function () {
  69095. return this._positions;
  69096. };
  69097. MorphTarget.prototype.setNormals = function (data) {
  69098. this._normals = data;
  69099. };
  69100. MorphTarget.prototype.getNormals = function () {
  69101. return this._normals;
  69102. };
  69103. MorphTarget.prototype.setTangents = function (data) {
  69104. this._tangents = data;
  69105. };
  69106. MorphTarget.prototype.getTangents = function () {
  69107. return this._tangents;
  69108. };
  69109. /**
  69110. * Serializes the current target into a Serialization object.
  69111. * Returns the serialized object.
  69112. */
  69113. MorphTarget.prototype.serialize = function () {
  69114. var serializationObject = {};
  69115. serializationObject.name = this.name;
  69116. serializationObject.influence = this.influence;
  69117. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  69118. if (this.hasNormals) {
  69119. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  69120. }
  69121. if (this.hasTangents) {
  69122. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  69123. }
  69124. // Animations
  69125. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  69126. return serializationObject;
  69127. };
  69128. // Statics
  69129. MorphTarget.Parse = function (serializationObject) {
  69130. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  69131. result.setPositions(serializationObject.positions);
  69132. if (serializationObject.normals) {
  69133. result.setNormals(serializationObject.normals);
  69134. }
  69135. if (serializationObject.tangents) {
  69136. result.setTangents(serializationObject.tangents);
  69137. }
  69138. // Animations
  69139. if (serializationObject.animations) {
  69140. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  69141. var parsedAnimation = serializationObject.animations[animationIndex];
  69142. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  69143. }
  69144. }
  69145. return result;
  69146. };
  69147. MorphTarget.FromMesh = function (mesh, name, influence) {
  69148. if (!name) {
  69149. name = mesh.name;
  69150. }
  69151. var result = new MorphTarget(name, influence);
  69152. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69153. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  69154. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  69155. }
  69156. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  69157. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  69158. }
  69159. return result;
  69160. };
  69161. return MorphTarget;
  69162. }());
  69163. BABYLON.MorphTarget = MorphTarget;
  69164. })(BABYLON || (BABYLON = {}));
  69165. //# sourceMappingURL=babylon.morphTarget.js.map
  69166. var BABYLON;
  69167. (function (BABYLON) {
  69168. var MorphTargetManager = /** @class */ (function () {
  69169. function MorphTargetManager(scene) {
  69170. if (scene === void 0) { scene = null; }
  69171. this._targets = new Array();
  69172. this._targetObservable = new Array();
  69173. this._activeTargets = new BABYLON.SmartArray(16);
  69174. this._supportsNormals = false;
  69175. this._supportsTangents = false;
  69176. this._vertexCount = 0;
  69177. this._uniqueId = 0;
  69178. this._tempInfluences = new Array();
  69179. if (!scene) {
  69180. scene = BABYLON.Engine.LastCreatedScene;
  69181. }
  69182. this._scene = scene;
  69183. if (this._scene) {
  69184. this._scene.morphTargetManagers.push(this);
  69185. this._uniqueId = this._scene.getUniqueId();
  69186. }
  69187. }
  69188. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  69189. get: function () {
  69190. return this._uniqueId;
  69191. },
  69192. enumerable: true,
  69193. configurable: true
  69194. });
  69195. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  69196. get: function () {
  69197. return this._vertexCount;
  69198. },
  69199. enumerable: true,
  69200. configurable: true
  69201. });
  69202. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  69203. get: function () {
  69204. return this._supportsNormals;
  69205. },
  69206. enumerable: true,
  69207. configurable: true
  69208. });
  69209. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  69210. get: function () {
  69211. return this._supportsTangents;
  69212. },
  69213. enumerable: true,
  69214. configurable: true
  69215. });
  69216. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  69217. get: function () {
  69218. return this._targets.length;
  69219. },
  69220. enumerable: true,
  69221. configurable: true
  69222. });
  69223. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  69224. get: function () {
  69225. return this._activeTargets.length;
  69226. },
  69227. enumerable: true,
  69228. configurable: true
  69229. });
  69230. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  69231. get: function () {
  69232. return this._influences;
  69233. },
  69234. enumerable: true,
  69235. configurable: true
  69236. });
  69237. MorphTargetManager.prototype.getActiveTarget = function (index) {
  69238. return this._activeTargets.data[index];
  69239. };
  69240. MorphTargetManager.prototype.getTarget = function (index) {
  69241. return this._targets[index];
  69242. };
  69243. MorphTargetManager.prototype.addTarget = function (target) {
  69244. var _this = this;
  69245. this._targets.push(target);
  69246. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  69247. _this._syncActiveTargets(needUpdate);
  69248. }));
  69249. this._syncActiveTargets(true);
  69250. };
  69251. MorphTargetManager.prototype.removeTarget = function (target) {
  69252. var index = this._targets.indexOf(target);
  69253. if (index >= 0) {
  69254. this._targets.splice(index, 1);
  69255. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  69256. this._syncActiveTargets(true);
  69257. }
  69258. };
  69259. /**
  69260. * Serializes the current manager into a Serialization object.
  69261. * Returns the serialized object.
  69262. */
  69263. MorphTargetManager.prototype.serialize = function () {
  69264. var serializationObject = {};
  69265. serializationObject.id = this.uniqueId;
  69266. serializationObject.targets = [];
  69267. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  69268. var target = _a[_i];
  69269. serializationObject.targets.push(target.serialize());
  69270. }
  69271. return serializationObject;
  69272. };
  69273. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  69274. var influenceCount = 0;
  69275. this._activeTargets.reset();
  69276. this._supportsNormals = true;
  69277. this._supportsTangents = true;
  69278. this._vertexCount = 0;
  69279. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  69280. var target = _a[_i];
  69281. if (target.influence > 0) {
  69282. this._activeTargets.push(target);
  69283. this._tempInfluences[influenceCount++] = target.influence;
  69284. this._supportsNormals = this._supportsNormals && target.hasNormals;
  69285. this._supportsTangents = this._supportsTangents && target.hasTangents;
  69286. var positions = target.getPositions();
  69287. if (!positions) {
  69288. BABYLON.Tools.Error("Invalid target. Target must positions.");
  69289. return;
  69290. }
  69291. var vertexCount = positions.length / 3;
  69292. if (this._vertexCount === 0) {
  69293. this._vertexCount = vertexCount;
  69294. }
  69295. else if (this._vertexCount !== vertexCount) {
  69296. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  69297. return;
  69298. }
  69299. }
  69300. }
  69301. if (!this._influences || this._influences.length !== influenceCount) {
  69302. this._influences = new Float32Array(influenceCount);
  69303. }
  69304. for (var index = 0; index < influenceCount; index++) {
  69305. this._influences[index] = this._tempInfluences[index];
  69306. }
  69307. if (needUpdate && this._scene) {
  69308. // Flag meshes as dirty to resync with the active targets
  69309. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  69310. var mesh = _c[_b];
  69311. if (mesh.morphTargetManager === this) {
  69312. mesh._syncGeometryWithMorphTargetManager();
  69313. }
  69314. }
  69315. }
  69316. };
  69317. // Statics
  69318. MorphTargetManager.Parse = function (serializationObject, scene) {
  69319. var result = new MorphTargetManager(scene);
  69320. result._uniqueId = serializationObject.id;
  69321. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  69322. var targetData = _a[_i];
  69323. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  69324. }
  69325. return result;
  69326. };
  69327. return MorphTargetManager;
  69328. }());
  69329. BABYLON.MorphTargetManager = MorphTargetManager;
  69330. })(BABYLON || (BABYLON = {}));
  69331. //# sourceMappingURL=babylon.morphTargetManager.js.map
  69332. var BABYLON;
  69333. (function (BABYLON) {
  69334. var Octree = /** @class */ (function () {
  69335. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  69336. if (maxDepth === void 0) { maxDepth = 2; }
  69337. this.maxDepth = maxDepth;
  69338. this.dynamicContent = new Array();
  69339. this._maxBlockCapacity = maxBlockCapacity || 64;
  69340. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  69341. this._creationFunc = creationFunc;
  69342. }
  69343. // Methods
  69344. Octree.prototype.update = function (worldMin, worldMax, entries) {
  69345. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  69346. };
  69347. Octree.prototype.addMesh = function (entry) {
  69348. for (var index = 0; index < this.blocks.length; index++) {
  69349. var block = this.blocks[index];
  69350. block.addEntry(entry);
  69351. }
  69352. };
  69353. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  69354. this._selectionContent.reset();
  69355. for (var index = 0; index < this.blocks.length; index++) {
  69356. var block = this.blocks[index];
  69357. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  69358. }
  69359. if (allowDuplicate) {
  69360. this._selectionContent.concat(this.dynamicContent);
  69361. }
  69362. else {
  69363. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69364. }
  69365. return this._selectionContent;
  69366. };
  69367. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  69368. this._selectionContent.reset();
  69369. for (var index = 0; index < this.blocks.length; index++) {
  69370. var block = this.blocks[index];
  69371. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  69372. }
  69373. if (allowDuplicate) {
  69374. this._selectionContent.concat(this.dynamicContent);
  69375. }
  69376. else {
  69377. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69378. }
  69379. return this._selectionContent;
  69380. };
  69381. Octree.prototype.intersectsRay = function (ray) {
  69382. this._selectionContent.reset();
  69383. for (var index = 0; index < this.blocks.length; index++) {
  69384. var block = this.blocks[index];
  69385. block.intersectsRay(ray, this._selectionContent);
  69386. }
  69387. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  69388. return this._selectionContent;
  69389. };
  69390. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  69391. target.blocks = new Array();
  69392. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  69393. // Segmenting space
  69394. for (var x = 0; x < 2; x++) {
  69395. for (var y = 0; y < 2; y++) {
  69396. for (var z = 0; z < 2; z++) {
  69397. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  69398. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  69399. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  69400. block.addEntries(entries);
  69401. target.blocks.push(block);
  69402. }
  69403. }
  69404. }
  69405. };
  69406. Octree.CreationFuncForMeshes = function (entry, block) {
  69407. var boundingInfo = entry.getBoundingInfo();
  69408. if (!entry.isBlocked && boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  69409. block.entries.push(entry);
  69410. }
  69411. };
  69412. Octree.CreationFuncForSubMeshes = function (entry, block) {
  69413. var boundingInfo = entry.getBoundingInfo();
  69414. if (boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  69415. block.entries.push(entry);
  69416. }
  69417. };
  69418. return Octree;
  69419. }());
  69420. BABYLON.Octree = Octree;
  69421. })(BABYLON || (BABYLON = {}));
  69422. //# sourceMappingURL=babylon.octree.js.map
  69423. var BABYLON;
  69424. (function (BABYLON) {
  69425. var OctreeBlock = /** @class */ (function () {
  69426. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  69427. this.entries = new Array();
  69428. this._boundingVectors = new Array();
  69429. this._capacity = capacity;
  69430. this._depth = depth;
  69431. this._maxDepth = maxDepth;
  69432. this._creationFunc = creationFunc;
  69433. this._minPoint = minPoint;
  69434. this._maxPoint = maxPoint;
  69435. this._boundingVectors.push(minPoint.clone());
  69436. this._boundingVectors.push(maxPoint.clone());
  69437. this._boundingVectors.push(minPoint.clone());
  69438. this._boundingVectors[2].x = maxPoint.x;
  69439. this._boundingVectors.push(minPoint.clone());
  69440. this._boundingVectors[3].y = maxPoint.y;
  69441. this._boundingVectors.push(minPoint.clone());
  69442. this._boundingVectors[4].z = maxPoint.z;
  69443. this._boundingVectors.push(maxPoint.clone());
  69444. this._boundingVectors[5].z = minPoint.z;
  69445. this._boundingVectors.push(maxPoint.clone());
  69446. this._boundingVectors[6].x = minPoint.x;
  69447. this._boundingVectors.push(maxPoint.clone());
  69448. this._boundingVectors[7].y = minPoint.y;
  69449. }
  69450. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  69451. // Property
  69452. get: function () {
  69453. return this._capacity;
  69454. },
  69455. enumerable: true,
  69456. configurable: true
  69457. });
  69458. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  69459. get: function () {
  69460. return this._minPoint;
  69461. },
  69462. enumerable: true,
  69463. configurable: true
  69464. });
  69465. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  69466. get: function () {
  69467. return this._maxPoint;
  69468. },
  69469. enumerable: true,
  69470. configurable: true
  69471. });
  69472. // Methods
  69473. OctreeBlock.prototype.addEntry = function (entry) {
  69474. if (this.blocks) {
  69475. for (var index = 0; index < this.blocks.length; index++) {
  69476. var block = this.blocks[index];
  69477. block.addEntry(entry);
  69478. }
  69479. return;
  69480. }
  69481. this._creationFunc(entry, this);
  69482. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  69483. this.createInnerBlocks();
  69484. }
  69485. };
  69486. OctreeBlock.prototype.addEntries = function (entries) {
  69487. for (var index = 0; index < entries.length; index++) {
  69488. var mesh = entries[index];
  69489. this.addEntry(mesh);
  69490. }
  69491. };
  69492. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  69493. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  69494. if (this.blocks) {
  69495. for (var index = 0; index < this.blocks.length; index++) {
  69496. var block = this.blocks[index];
  69497. block.select(frustumPlanes, selection, allowDuplicate);
  69498. }
  69499. return;
  69500. }
  69501. if (allowDuplicate) {
  69502. selection.concat(this.entries);
  69503. }
  69504. else {
  69505. selection.concatWithNoDuplicate(this.entries);
  69506. }
  69507. }
  69508. };
  69509. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  69510. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  69511. if (this.blocks) {
  69512. for (var index = 0; index < this.blocks.length; index++) {
  69513. var block = this.blocks[index];
  69514. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  69515. }
  69516. return;
  69517. }
  69518. if (allowDuplicate) {
  69519. selection.concat(this.entries);
  69520. }
  69521. else {
  69522. selection.concatWithNoDuplicate(this.entries);
  69523. }
  69524. }
  69525. };
  69526. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  69527. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  69528. if (this.blocks) {
  69529. for (var index = 0; index < this.blocks.length; index++) {
  69530. var block = this.blocks[index];
  69531. block.intersectsRay(ray, selection);
  69532. }
  69533. return;
  69534. }
  69535. selection.concatWithNoDuplicate(this.entries);
  69536. }
  69537. };
  69538. OctreeBlock.prototype.createInnerBlocks = function () {
  69539. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  69540. };
  69541. return OctreeBlock;
  69542. }());
  69543. BABYLON.OctreeBlock = OctreeBlock;
  69544. })(BABYLON || (BABYLON = {}));
  69545. //# sourceMappingURL=babylon.octreeBlock.js.map
  69546. var BABYLON;
  69547. (function (BABYLON) {
  69548. var SIMDVector3 = /** @class */ (function () {
  69549. function SIMDVector3() {
  69550. }
  69551. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  69552. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  69553. };
  69554. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  69555. var m = transformation.m;
  69556. var m0 = SIMD.Float32x4.load(m, 0);
  69557. var m1 = SIMD.Float32x4.load(m, 4);
  69558. var m2 = SIMD.Float32x4.load(m, 8);
  69559. var m3 = SIMD.Float32x4.load(m, 12);
  69560. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  69561. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  69562. result.x = SIMD.Float32x4.extractLane(r, 0);
  69563. result.y = SIMD.Float32x4.extractLane(r, 1);
  69564. result.z = SIMD.Float32x4.extractLane(r, 2);
  69565. };
  69566. return SIMDVector3;
  69567. }());
  69568. var SIMDMatrix = /** @class */ (function () {
  69569. function SIMDMatrix() {
  69570. }
  69571. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  69572. var tm = this.m;
  69573. var om = other.m;
  69574. var m0 = SIMD.Float32x4.load(om, 0);
  69575. var m1 = SIMD.Float32x4.load(om, 4);
  69576. var m2 = SIMD.Float32x4.load(om, 8);
  69577. var m3 = SIMD.Float32x4.load(om, 12);
  69578. for (var i = 0; i < 16; i += 4) {
  69579. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  69580. }
  69581. return this;
  69582. };
  69583. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  69584. var src = this.m;
  69585. var dest = other.m;
  69586. // Load the 4 rows
  69587. var src0 = SIMD.Float32x4.load(src, 0);
  69588. var src1 = SIMD.Float32x4.load(src, 4);
  69589. var src2 = SIMD.Float32x4.load(src, 8);
  69590. var src3 = SIMD.Float32x4.load(src, 12);
  69591. // Transpose the source matrix. Sort of. Not a true transpose operation
  69592. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  69593. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  69594. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  69595. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  69596. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  69597. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  69598. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  69599. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  69600. // This is a true transposition, but it will lead to an incorrect result
  69601. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  69602. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  69603. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  69604. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  69605. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  69606. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  69607. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  69608. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  69609. // ----
  69610. tmp1 = SIMD.Float32x4.mul(row2, row3);
  69611. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69612. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  69613. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  69614. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69615. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  69616. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  69617. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  69618. // ----
  69619. tmp1 = SIMD.Float32x4.mul(row1, row2);
  69620. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69621. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  69622. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  69623. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69624. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  69625. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  69626. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  69627. // ----
  69628. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  69629. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69630. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  69631. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  69632. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  69633. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69634. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  69635. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  69636. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  69637. // ----
  69638. tmp1 = SIMD.Float32x4.mul(row0, row1);
  69639. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69640. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  69641. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  69642. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69643. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  69644. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  69645. // ----
  69646. tmp1 = SIMD.Float32x4.mul(row0, row3);
  69647. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69648. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  69649. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  69650. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69651. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  69652. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  69653. // ----
  69654. tmp1 = SIMD.Float32x4.mul(row0, row2);
  69655. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69656. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  69657. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  69658. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69659. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  69660. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  69661. // Compute determinant
  69662. var det = SIMD.Float32x4.mul(row0, minor0);
  69663. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  69664. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  69665. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  69666. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  69667. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  69668. // These shuffles aren't necessary if the faulty transposition is done
  69669. // up at the top of this function.
  69670. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  69671. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  69672. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  69673. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  69674. // Compute final values by multiplying with 1/det
  69675. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  69676. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  69677. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  69678. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  69679. return this;
  69680. };
  69681. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  69682. var out = result.m;
  69683. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  69684. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  69685. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  69686. // cc.kmVec3Subtract(f, pCenter, pEye);
  69687. var f = SIMD.Float32x4.sub(center, eye);
  69688. // cc.kmVec3Normalize(f, f);
  69689. var tmp = SIMD.Float32x4.mul(f, f);
  69690. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69691. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69692. // cc.kmVec3Assign(up, pUp);
  69693. // cc.kmVec3Normalize(up, up);
  69694. tmp = SIMD.Float32x4.mul(up, up);
  69695. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69696. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69697. // cc.kmVec3Cross(s, f, up);
  69698. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  69699. // cc.kmVec3Normalize(s, s);
  69700. tmp = SIMD.Float32x4.mul(s, s);
  69701. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69702. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69703. // cc.kmVec3Cross(u, s, f);
  69704. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  69705. // cc.kmVec3Normalize(s, s);
  69706. tmp = SIMD.Float32x4.mul(s, s);
  69707. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69708. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69709. var zero = SIMD.Float32x4.splat(0.0);
  69710. s = SIMD.Float32x4.neg(s);
  69711. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  69712. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  69713. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  69714. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  69715. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  69716. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  69717. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  69718. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  69719. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  69720. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  69721. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  69722. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  69723. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  69724. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  69725. };
  69726. return SIMDMatrix;
  69727. }());
  69728. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  69729. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  69730. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  69731. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  69732. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  69733. var SIMDHelper = /** @class */ (function () {
  69734. function SIMDHelper() {
  69735. }
  69736. Object.defineProperty(SIMDHelper, "IsEnabled", {
  69737. get: function () {
  69738. return SIMDHelper._isEnabled;
  69739. },
  69740. enumerable: true,
  69741. configurable: true
  69742. });
  69743. SIMDHelper.DisableSIMD = function () {
  69744. // Replace functions
  69745. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  69746. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  69747. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  69748. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  69749. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  69750. SIMDHelper._isEnabled = false;
  69751. };
  69752. SIMDHelper.EnableSIMD = function () {
  69753. if (self.SIMD === undefined) {
  69754. return;
  69755. }
  69756. // check if polyfills needed
  69757. if (!self.Math.fround) {
  69758. self.Math.fround = (function (array) { return function (x) {
  69759. return array[0] = x, array[0];
  69760. }; })(new Float32Array(1));
  69761. }
  69762. if (!self.Math.imul) {
  69763. self.Math.imul = function (a, b) {
  69764. var ah = (a >>> 16) & 0xffff;
  69765. var al = a & 0xffff;
  69766. var bh = (b >>> 16) & 0xffff;
  69767. var bl = b & 0xffff;
  69768. // the shift by 0 fixes the sign on the high part
  69769. // the final |0 converts the unsigned value into a signed value
  69770. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  69771. };
  69772. }
  69773. // Replace functions
  69774. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  69775. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  69776. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  69777. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  69778. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  69779. SIMDHelper._isEnabled = true;
  69780. };
  69781. SIMDHelper._isEnabled = false;
  69782. return SIMDHelper;
  69783. }());
  69784. BABYLON.SIMDHelper = SIMDHelper;
  69785. })(BABYLON || (BABYLON = {}));
  69786. //# sourceMappingURL=babylon.math.SIMD.js.map
  69787. var BABYLON;
  69788. (function (BABYLON) {
  69789. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  69790. __extends(VRDistortionCorrectionPostProcess, _super);
  69791. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  69792. var _this = _super.call(this, name, "vrDistortionCorrection", [
  69793. 'LensCenter',
  69794. 'Scale',
  69795. 'ScaleIn',
  69796. 'HmdWarpParam'
  69797. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  69798. _this._isRightEye = isRightEye;
  69799. _this._distortionFactors = vrMetrics.distortionK;
  69800. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  69801. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  69802. _this.adaptScaleToCurrentViewport = true;
  69803. _this.onSizeChangedObservable.add(function () {
  69804. _this.aspectRatio = _this.width * .5 / _this.height;
  69805. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  69806. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  69807. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  69808. });
  69809. _this.onApplyObservable.add(function (effect) {
  69810. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  69811. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  69812. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  69813. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  69814. });
  69815. return _this;
  69816. }
  69817. return VRDistortionCorrectionPostProcess;
  69818. }(BABYLON.PostProcess));
  69819. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  69820. })(BABYLON || (BABYLON = {}));
  69821. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  69822. var BABYLON;
  69823. (function (BABYLON) {
  69824. var AnaglyphPostProcess = /** @class */ (function (_super) {
  69825. __extends(AnaglyphPostProcess, _super);
  69826. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  69827. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  69828. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69829. _this.onApplyObservable.add(function (effect) {
  69830. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  69831. });
  69832. return _this;
  69833. }
  69834. return AnaglyphPostProcess;
  69835. }(BABYLON.PostProcess));
  69836. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  69837. })(BABYLON || (BABYLON = {}));
  69838. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  69839. var BABYLON;
  69840. (function (BABYLON) {
  69841. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  69842. __extends(StereoscopicInterlacePostProcess, _super);
  69843. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  69844. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  69845. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69846. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69847. _this.onSizeChangedObservable.add(function () {
  69848. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69849. });
  69850. _this.onApplyObservable.add(function (effect) {
  69851. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  69852. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  69853. });
  69854. return _this;
  69855. }
  69856. return StereoscopicInterlacePostProcess;
  69857. }(BABYLON.PostProcess));
  69858. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  69859. })(BABYLON || (BABYLON = {}));
  69860. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  69861. var BABYLON;
  69862. (function (BABYLON) {
  69863. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  69864. function FreeCameraDeviceOrientationInput() {
  69865. var _this = this;
  69866. this._screenOrientationAngle = 0;
  69867. this._screenQuaternion = new BABYLON.Quaternion();
  69868. this._alpha = 0;
  69869. this._beta = 0;
  69870. this._gamma = 0;
  69871. this._orientationChanged = function () {
  69872. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  69873. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  69874. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  69875. };
  69876. this._deviceOrientation = function (evt) {
  69877. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  69878. _this._beta = evt.beta !== null ? evt.beta : 0;
  69879. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  69880. };
  69881. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  69882. this._orientationChanged();
  69883. }
  69884. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  69885. get: function () {
  69886. return this._camera;
  69887. },
  69888. set: function (camera) {
  69889. this._camera = camera;
  69890. if (this._camera != null && !this._camera.rotationQuaternion) {
  69891. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  69892. }
  69893. },
  69894. enumerable: true,
  69895. configurable: true
  69896. });
  69897. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69898. window.addEventListener("orientationchange", this._orientationChanged);
  69899. window.addEventListener("deviceorientation", this._deviceOrientation);
  69900. //In certain cases, the attach control is called AFTER orientation was changed,
  69901. //So this is needed.
  69902. this._orientationChanged();
  69903. };
  69904. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  69905. window.removeEventListener("orientationchange", this._orientationChanged);
  69906. window.removeEventListener("deviceorientation", this._deviceOrientation);
  69907. };
  69908. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  69909. //if no device orientation provided, don't update the rotation.
  69910. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  69911. if (!this._alpha)
  69912. return;
  69913. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  69914. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  69915. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  69916. //Mirror on XY Plane
  69917. this._camera.rotationQuaternion.z *= -1;
  69918. this._camera.rotationQuaternion.w *= -1;
  69919. };
  69920. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  69921. return "FreeCameraDeviceOrientationInput";
  69922. };
  69923. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  69924. return "deviceOrientation";
  69925. };
  69926. return FreeCameraDeviceOrientationInput;
  69927. }());
  69928. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  69929. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  69930. })(BABYLON || (BABYLON = {}));
  69931. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  69932. var BABYLON;
  69933. (function (BABYLON) {
  69934. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  69935. function ArcRotateCameraVRDeviceOrientationInput() {
  69936. this.alphaCorrection = 1;
  69937. this.betaCorrection = 1;
  69938. this.gammaCorrection = 1;
  69939. this._alpha = 0;
  69940. this._beta = 0;
  69941. this._gamma = 0;
  69942. this._dirty = false;
  69943. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  69944. }
  69945. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69946. this.camera.attachControl(element, noPreventDefault);
  69947. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  69948. };
  69949. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  69950. if (evt.alpha !== null) {
  69951. this._alpha = +evt.alpha | 0;
  69952. }
  69953. if (evt.beta !== null) {
  69954. this._beta = +evt.beta | 0;
  69955. }
  69956. if (evt.gamma !== null) {
  69957. this._gamma = +evt.gamma | 0;
  69958. }
  69959. this._dirty = true;
  69960. };
  69961. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  69962. if (this._dirty) {
  69963. this._dirty = false;
  69964. if (this._gamma < 0) {
  69965. this._gamma = 180 + this._gamma;
  69966. }
  69967. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  69968. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  69969. }
  69970. };
  69971. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  69972. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  69973. };
  69974. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  69975. return "ArcRotateCameraVRDeviceOrientationInput";
  69976. };
  69977. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  69978. return "VRDeviceOrientation";
  69979. };
  69980. return ArcRotateCameraVRDeviceOrientationInput;
  69981. }());
  69982. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  69983. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  69984. })(BABYLON || (BABYLON = {}));
  69985. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  69986. var BABYLON;
  69987. (function (BABYLON) {
  69988. var VRCameraMetrics = /** @class */ (function () {
  69989. function VRCameraMetrics() {
  69990. this.compensateDistortion = true;
  69991. }
  69992. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  69993. get: function () {
  69994. return this.hResolution / (2 * this.vResolution);
  69995. },
  69996. enumerable: true,
  69997. configurable: true
  69998. });
  69999. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  70000. get: function () {
  70001. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  70002. },
  70003. enumerable: true,
  70004. configurable: true
  70005. });
  70006. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  70007. get: function () {
  70008. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  70009. var h = (4 * meters) / this.hScreenSize;
  70010. return BABYLON.Matrix.Translation(h, 0, 0);
  70011. },
  70012. enumerable: true,
  70013. configurable: true
  70014. });
  70015. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  70016. get: function () {
  70017. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  70018. var h = (4 * meters) / this.hScreenSize;
  70019. return BABYLON.Matrix.Translation(-h, 0, 0);
  70020. },
  70021. enumerable: true,
  70022. configurable: true
  70023. });
  70024. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  70025. get: function () {
  70026. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  70027. },
  70028. enumerable: true,
  70029. configurable: true
  70030. });
  70031. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  70032. get: function () {
  70033. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  70034. },
  70035. enumerable: true,
  70036. configurable: true
  70037. });
  70038. VRCameraMetrics.GetDefault = function () {
  70039. var result = new VRCameraMetrics();
  70040. result.hResolution = 1280;
  70041. result.vResolution = 800;
  70042. result.hScreenSize = 0.149759993;
  70043. result.vScreenSize = 0.0935999975;
  70044. result.vScreenCenter = 0.0467999987;
  70045. result.eyeToScreenDistance = 0.0410000011;
  70046. result.lensSeparationDistance = 0.0635000020;
  70047. result.interpupillaryDistance = 0.0640000030;
  70048. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  70049. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  70050. result.postProcessScaleFactor = 1.714605507808412;
  70051. result.lensCenterOffset = 0.151976421;
  70052. return result;
  70053. };
  70054. return VRCameraMetrics;
  70055. }());
  70056. BABYLON.VRCameraMetrics = VRCameraMetrics;
  70057. })(BABYLON || (BABYLON = {}));
  70058. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  70059. var BABYLON;
  70060. (function (BABYLON) {
  70061. var WebVRFreeCamera = /** @class */ (function (_super) {
  70062. __extends(WebVRFreeCamera, _super);
  70063. function WebVRFreeCamera(name, position, scene, webVROptions) {
  70064. if (webVROptions === void 0) { webVROptions = {}; }
  70065. var _this = _super.call(this, name, position, scene) || this;
  70066. _this.webVROptions = webVROptions;
  70067. _this._vrDevice = null;
  70068. _this.rawPose = null;
  70069. _this._specsVersion = "1.1";
  70070. _this._attached = false;
  70071. _this._descendants = [];
  70072. _this.devicePosition = BABYLON.Vector3.Zero();
  70073. _this.deviceScaleFactor = 1;
  70074. _this.controllers = [];
  70075. _this.onControllersAttachedObservable = new BABYLON.Observable();
  70076. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  70077. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  70078. _this.minZ = 0.1;
  70079. //legacy support - the compensation boolean was removed.
  70080. if (arguments.length === 5) {
  70081. _this.webVROptions = arguments[4];
  70082. }
  70083. // default webVR options
  70084. if (_this.webVROptions.trackPosition == undefined) {
  70085. _this.webVROptions.trackPosition = true;
  70086. }
  70087. if (_this.webVROptions.controllerMeshes == undefined) {
  70088. _this.webVROptions.controllerMeshes = true;
  70089. }
  70090. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  70091. _this.webVROptions.defaultLightingOnControllers = true;
  70092. }
  70093. _this.rotationQuaternion = new BABYLON.Quaternion();
  70094. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70095. if (_this.webVROptions && _this.webVROptions.positionScale) {
  70096. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  70097. }
  70098. //enable VR
  70099. var engine = _this.getEngine();
  70100. _this._onVREnabled = function (success) { if (success) {
  70101. _this.initControllers();
  70102. } };
  70103. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  70104. engine.initWebVR().add(function (event) {
  70105. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  70106. return;
  70107. }
  70108. _this._vrDevice = event.vrDisplay;
  70109. //reset the rig parameters.
  70110. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  70111. if (_this._attached) {
  70112. _this.getEngine().enableVR();
  70113. }
  70114. });
  70115. if (typeof (VRFrameData) !== "undefined")
  70116. _this._frameData = new VRFrameData();
  70117. /**
  70118. * The idea behind the following lines:
  70119. * objects that have the camera as parent should actually have the rig cameras as a parent.
  70120. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  70121. * the second will not show it correctly.
  70122. *
  70123. * To solve this - each object that has the camera as parent will be added to a protected array.
  70124. * When the rig camera renders, it will take this array and set all of those to be its children.
  70125. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  70126. * Amazing!
  70127. */
  70128. scene.onBeforeCameraRenderObservable.add(function (camera) {
  70129. if (camera.parent === _this && _this.rigParenting) {
  70130. _this._descendants = _this.getDescendants(true, function (n) {
  70131. // don't take the cameras or the controllers!
  70132. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  70133. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  70134. return !isController && !isRigCamera;
  70135. });
  70136. _this._descendants.forEach(function (node) {
  70137. node.parent = camera;
  70138. });
  70139. }
  70140. });
  70141. scene.onAfterCameraRenderObservable.add(function (camera) {
  70142. if (camera.parent === _this && _this.rigParenting) {
  70143. _this._descendants.forEach(function (node) {
  70144. node.parent = _this;
  70145. });
  70146. }
  70147. });
  70148. return _this;
  70149. }
  70150. WebVRFreeCamera.prototype.dispose = function () {
  70151. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  70152. _super.prototype.dispose.call(this);
  70153. };
  70154. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  70155. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  70156. var gp = _a[_i];
  70157. if (gp.hand === name) {
  70158. return gp;
  70159. }
  70160. }
  70161. return null;
  70162. };
  70163. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  70164. get: function () {
  70165. if (!this._leftController) {
  70166. this._leftController = this.getControllerByName("left");
  70167. }
  70168. return this._leftController;
  70169. },
  70170. enumerable: true,
  70171. configurable: true
  70172. });
  70173. ;
  70174. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  70175. get: function () {
  70176. if (!this._rightController) {
  70177. this._rightController = this.getControllerByName("right");
  70178. }
  70179. return this._rightController;
  70180. },
  70181. enumerable: true,
  70182. configurable: true
  70183. });
  70184. ;
  70185. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  70186. if (length === void 0) { length = 100; }
  70187. if (this.leftCamera) {
  70188. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  70189. }
  70190. else {
  70191. return _super.prototype.getForwardRay.call(this, length);
  70192. }
  70193. };
  70194. WebVRFreeCamera.prototype._checkInputs = function () {
  70195. if (this._vrDevice && this._vrDevice.isPresenting) {
  70196. this._vrDevice.getFrameData(this._frameData);
  70197. this.updateFromDevice(this._frameData.pose);
  70198. }
  70199. _super.prototype._checkInputs.call(this);
  70200. };
  70201. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  70202. if (poseData && poseData.orientation) {
  70203. this.rawPose = poseData;
  70204. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  70205. if (this.getScene().useRightHandedSystem) {
  70206. this.deviceRotationQuaternion.z *= -1;
  70207. this.deviceRotationQuaternion.w *= -1;
  70208. }
  70209. if (this.webVROptions.trackPosition && this.rawPose.position) {
  70210. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  70211. if (this.getScene().useRightHandedSystem) {
  70212. this.devicePosition.z *= -1;
  70213. }
  70214. }
  70215. }
  70216. };
  70217. /**
  70218. * WebVR's attach control will start broadcasting frames to the device.
  70219. * Note that in certain browsers (chrome for example) this function must be called
  70220. * within a user-interaction callback. Example:
  70221. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  70222. *
  70223. * @param {HTMLElement} element
  70224. * @param {boolean} [noPreventDefault]
  70225. *
  70226. * @memberOf WebVRFreeCamera
  70227. */
  70228. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  70229. _super.prototype.attachControl.call(this, element, noPreventDefault);
  70230. this._attached = true;
  70231. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  70232. if (this._vrDevice) {
  70233. this.getEngine().enableVR();
  70234. }
  70235. };
  70236. WebVRFreeCamera.prototype.detachControl = function (element) {
  70237. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70238. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70239. _super.prototype.detachControl.call(this, element);
  70240. this._attached = false;
  70241. this.getEngine().disableVR();
  70242. };
  70243. WebVRFreeCamera.prototype.getClassName = function () {
  70244. return "WebVRFreeCamera";
  70245. };
  70246. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  70247. //uses the vrDisplay's "resetPose()".
  70248. //pitch and roll won't be affected.
  70249. this._vrDevice.resetPose();
  70250. };
  70251. WebVRFreeCamera.prototype._updateRigCameras = function () {
  70252. var camLeft = this._rigCameras[0];
  70253. var camRight = this._rigCameras[1];
  70254. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70255. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70256. camLeft.position.copyFrom(this.devicePosition);
  70257. camRight.position.copyFrom(this.devicePosition);
  70258. };
  70259. /**
  70260. * This function is called by the two RIG cameras.
  70261. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  70262. */
  70263. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  70264. var _this = this;
  70265. //WebVR 1.1
  70266. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  70267. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  70268. if (!this.getScene().useRightHandedSystem) {
  70269. [2, 6, 8, 9, 14].forEach(function (num) {
  70270. _this._webvrViewMatrix.m[num] *= -1;
  70271. });
  70272. }
  70273. // update the camera rotation matrix
  70274. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  70275. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  70276. // Computing target and final matrix
  70277. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  70278. var parentCamera = this._cameraRigParams["parentCamera"];
  70279. // should the view matrix be updated with scale and position offset?
  70280. if (parentCamera.deviceScaleFactor !== 1) {
  70281. this._webvrViewMatrix.invert();
  70282. // scale the position, if set
  70283. if (parentCamera.deviceScaleFactor) {
  70284. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  70285. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  70286. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  70287. }
  70288. this._webvrViewMatrix.invert();
  70289. }
  70290. return this._webvrViewMatrix;
  70291. };
  70292. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  70293. var _this = this;
  70294. var parentCamera = this.parent;
  70295. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  70296. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  70297. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  70298. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  70299. //babylon compatible matrix
  70300. if (!this.getScene().useRightHandedSystem) {
  70301. [8, 9, 10, 11].forEach(function (num) {
  70302. _this._projectionMatrix.m[num] *= -1;
  70303. });
  70304. }
  70305. return this._projectionMatrix;
  70306. };
  70307. WebVRFreeCamera.prototype.initControllers = function () {
  70308. var _this = this;
  70309. this.controllers = [];
  70310. var manager = this.getScene().gamepadManager;
  70311. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70312. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  70313. var webVrController = gamepad;
  70314. if (webVrController.defaultModel) {
  70315. webVrController.defaultModel.setEnabled(false);
  70316. }
  70317. }
  70318. });
  70319. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70320. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  70321. var webVrController_1 = gamepad;
  70322. if (_this.webVROptions.controllerMeshes) {
  70323. if (webVrController_1.defaultModel) {
  70324. webVrController_1.defaultModel.setEnabled(true);
  70325. }
  70326. else {
  70327. // Load the meshes
  70328. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  70329. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  70330. if (_this.webVROptions.defaultLightingOnControllers) {
  70331. if (!_this._lightOnControllers) {
  70332. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  70333. }
  70334. var activateLightOnSubMeshes_1 = function (mesh, light) {
  70335. var children = mesh.getChildren();
  70336. if (children.length !== 0) {
  70337. children.forEach(function (mesh) {
  70338. light.includedOnlyMeshes.push(mesh);
  70339. activateLightOnSubMeshes_1(mesh, light);
  70340. });
  70341. }
  70342. };
  70343. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  70344. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  70345. }
  70346. });
  70347. }
  70348. }
  70349. webVrController_1.attachToPoseControlledCamera(_this);
  70350. // since this is async - sanity check. Is the controller already stored?
  70351. if (_this.controllers.indexOf(webVrController_1) === -1) {
  70352. //add to the controllers array
  70353. _this.controllers.push(webVrController_1);
  70354. //did we find enough controllers? Great! let the developer know.
  70355. if (_this.controllers.length >= 2) {
  70356. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  70357. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  70358. // So we're overriding setting left & right manually to be sure
  70359. var firstViveWandDetected = false;
  70360. for (var i = 0; i < _this.controllers.length; i++) {
  70361. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  70362. if (!firstViveWandDetected) {
  70363. firstViveWandDetected = true;
  70364. _this.controllers[i].hand = "left";
  70365. }
  70366. else {
  70367. _this.controllers[i].hand = "right";
  70368. }
  70369. }
  70370. }
  70371. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  70372. }
  70373. }
  70374. }
  70375. });
  70376. };
  70377. return WebVRFreeCamera;
  70378. }(BABYLON.FreeCamera));
  70379. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  70380. })(BABYLON || (BABYLON = {}));
  70381. //# sourceMappingURL=babylon.webVRCamera.js.map
  70382. var BABYLON;
  70383. (function (BABYLON) {
  70384. // We're mainly based on the logic defined into the FreeCamera code
  70385. var DeviceOrientationCamera = /** @class */ (function (_super) {
  70386. __extends(DeviceOrientationCamera, _super);
  70387. function DeviceOrientationCamera(name, position, scene) {
  70388. var _this = _super.call(this, name, position, scene) || this;
  70389. _this._quaternionCache = new BABYLON.Quaternion();
  70390. _this.inputs.addDeviceOrientation();
  70391. return _this;
  70392. }
  70393. DeviceOrientationCamera.prototype.getClassName = function () {
  70394. return "DeviceOrientationCamera";
  70395. };
  70396. DeviceOrientationCamera.prototype._checkInputs = function () {
  70397. _super.prototype._checkInputs.call(this);
  70398. this._quaternionCache.copyFrom(this.rotationQuaternion);
  70399. if (this._initialQuaternion) {
  70400. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  70401. }
  70402. };
  70403. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  70404. var _this = this;
  70405. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  70406. //can only work if this camera has a rotation quaternion already.
  70407. if (!this.rotationQuaternion)
  70408. return;
  70409. if (!this._initialQuaternion) {
  70410. this._initialQuaternion = new BABYLON.Quaternion();
  70411. }
  70412. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  70413. ['x', 'y', 'z'].forEach(function (axisName) {
  70414. if (!axis[axisName]) {
  70415. _this._initialQuaternion[axisName] = 0;
  70416. }
  70417. else {
  70418. _this._initialQuaternion[axisName] *= -1;
  70419. }
  70420. });
  70421. this._initialQuaternion.normalize();
  70422. //force rotation update
  70423. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  70424. };
  70425. return DeviceOrientationCamera;
  70426. }(BABYLON.FreeCamera));
  70427. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  70428. })(BABYLON || (BABYLON = {}));
  70429. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  70430. var BABYLON;
  70431. (function (BABYLON) {
  70432. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  70433. __extends(VRDeviceOrientationFreeCamera, _super);
  70434. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  70435. if (compensateDistortion === void 0) { compensateDistortion = true; }
  70436. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  70437. var _this = _super.call(this, name, position, scene) || this;
  70438. vrCameraMetrics.compensateDistortion = compensateDistortion;
  70439. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  70440. return _this;
  70441. }
  70442. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  70443. return "VRDeviceOrientationFreeCamera";
  70444. };
  70445. return VRDeviceOrientationFreeCamera;
  70446. }(BABYLON.DeviceOrientationCamera));
  70447. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  70448. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  70449. __extends(VRDeviceOrientationGamepadCamera, _super);
  70450. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  70451. if (compensateDistortion === void 0) { compensateDistortion = true; }
  70452. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  70453. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  70454. _this.inputs.addGamepad();
  70455. return _this;
  70456. }
  70457. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  70458. return "VRDeviceOrientationGamepadCamera";
  70459. };
  70460. return VRDeviceOrientationGamepadCamera;
  70461. }(VRDeviceOrientationFreeCamera));
  70462. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  70463. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  70464. __extends(VRDeviceOrientationArcRotateCamera, _super);
  70465. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  70466. if (compensateDistortion === void 0) { compensateDistortion = true; }
  70467. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  70468. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  70469. vrCameraMetrics.compensateDistortion = compensateDistortion;
  70470. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  70471. _this.inputs.addVRDeviceOrientation();
  70472. return _this;
  70473. }
  70474. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  70475. return "VRDeviceOrientationArcRotateCamera";
  70476. };
  70477. return VRDeviceOrientationArcRotateCamera;
  70478. }(BABYLON.ArcRotateCamera));
  70479. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  70480. })(BABYLON || (BABYLON = {}));
  70481. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  70482. var BABYLON;
  70483. (function (BABYLON) {
  70484. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  70485. __extends(AnaglyphFreeCamera, _super);
  70486. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  70487. var _this = _super.call(this, name, position, scene) || this;
  70488. _this.interaxialDistance = interaxialDistance;
  70489. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70490. return _this;
  70491. }
  70492. AnaglyphFreeCamera.prototype.getClassName = function () {
  70493. return "AnaglyphFreeCamera";
  70494. };
  70495. return AnaglyphFreeCamera;
  70496. }(BABYLON.FreeCamera));
  70497. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  70498. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  70499. __extends(AnaglyphArcRotateCamera, _super);
  70500. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  70501. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  70502. _this.interaxialDistance = interaxialDistance;
  70503. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70504. return _this;
  70505. }
  70506. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  70507. return "AnaglyphArcRotateCamera";
  70508. };
  70509. return AnaglyphArcRotateCamera;
  70510. }(BABYLON.ArcRotateCamera));
  70511. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  70512. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  70513. __extends(AnaglyphGamepadCamera, _super);
  70514. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  70515. var _this = _super.call(this, name, position, scene) || this;
  70516. _this.interaxialDistance = interaxialDistance;
  70517. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70518. return _this;
  70519. }
  70520. AnaglyphGamepadCamera.prototype.getClassName = function () {
  70521. return "AnaglyphGamepadCamera";
  70522. };
  70523. return AnaglyphGamepadCamera;
  70524. }(BABYLON.GamepadCamera));
  70525. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  70526. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  70527. __extends(AnaglyphUniversalCamera, _super);
  70528. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  70529. var _this = _super.call(this, name, position, scene) || this;
  70530. _this.interaxialDistance = interaxialDistance;
  70531. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70532. return _this;
  70533. }
  70534. AnaglyphUniversalCamera.prototype.getClassName = function () {
  70535. return "AnaglyphUniversalCamera";
  70536. };
  70537. return AnaglyphUniversalCamera;
  70538. }(BABYLON.UniversalCamera));
  70539. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  70540. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  70541. __extends(StereoscopicFreeCamera, _super);
  70542. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70543. var _this = _super.call(this, name, position, scene) || this;
  70544. _this.interaxialDistance = interaxialDistance;
  70545. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70546. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70547. return _this;
  70548. }
  70549. StereoscopicFreeCamera.prototype.getClassName = function () {
  70550. return "StereoscopicFreeCamera";
  70551. };
  70552. return StereoscopicFreeCamera;
  70553. }(BABYLON.FreeCamera));
  70554. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  70555. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  70556. __extends(StereoscopicArcRotateCamera, _super);
  70557. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  70558. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  70559. _this.interaxialDistance = interaxialDistance;
  70560. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70561. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70562. return _this;
  70563. }
  70564. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  70565. return "StereoscopicArcRotateCamera";
  70566. };
  70567. return StereoscopicArcRotateCamera;
  70568. }(BABYLON.ArcRotateCamera));
  70569. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  70570. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  70571. __extends(StereoscopicGamepadCamera, _super);
  70572. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70573. var _this = _super.call(this, name, position, scene) || this;
  70574. _this.interaxialDistance = interaxialDistance;
  70575. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70576. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70577. return _this;
  70578. }
  70579. StereoscopicGamepadCamera.prototype.getClassName = function () {
  70580. return "StereoscopicGamepadCamera";
  70581. };
  70582. return StereoscopicGamepadCamera;
  70583. }(BABYLON.GamepadCamera));
  70584. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  70585. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  70586. __extends(StereoscopicUniversalCamera, _super);
  70587. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70588. var _this = _super.call(this, name, position, scene) || this;
  70589. _this.interaxialDistance = interaxialDistance;
  70590. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70591. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70592. return _this;
  70593. }
  70594. StereoscopicUniversalCamera.prototype.getClassName = function () {
  70595. return "StereoscopicUniversalCamera";
  70596. };
  70597. return StereoscopicUniversalCamera;
  70598. }(BABYLON.UniversalCamera));
  70599. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  70600. })(BABYLON || (BABYLON = {}));
  70601. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  70602. var BABYLON;
  70603. (function (BABYLON) {
  70604. var VRExperienceHelper = /** @class */ (function () {
  70605. function VRExperienceHelper(scene, webVROptions) {
  70606. if (webVROptions === void 0) { webVROptions = {}; }
  70607. var _this = this;
  70608. this.webVROptions = webVROptions;
  70609. // Can the system support WebVR, even if a headset isn't plugged in?
  70610. this._webVRsupported = false;
  70611. // If WebVR is supported, is a headset plugged in and are we ready to present?
  70612. this._webVRready = false;
  70613. // Are we waiting for the requestPresent callback to complete?
  70614. this._webVRrequesting = false;
  70615. // Are we presenting to the headset right now?
  70616. this._webVRpresenting = false;
  70617. // Are we presenting in the fullscreen fallback?
  70618. this._fullscreenVRpresenting = false;
  70619. this._scene = scene;
  70620. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  70621. this._position = new BABYLON.Vector3(0, 2, 0);
  70622. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  70623. }
  70624. else {
  70625. this._position = this._scene.activeCamera.position.clone();
  70626. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position, scene);
  70627. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  70628. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  70629. }
  70630. this._scene.activeCamera = this._deviceOrientationCamera;
  70631. this._canvas = scene.getEngine().getRenderingCanvas();
  70632. if (this._canvas) {
  70633. this._scene.activeCamera.attachControl(this._canvas);
  70634. }
  70635. this._btnVR = document.createElement("BUTTON");
  70636. this._btnVR.className = "babylonVRicon";
  70637. this._btnVR.id = "babylonVRiconbtn";
  70638. this._btnVR.title = "Click to switch to VR";
  70639. 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) }";
  70640. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  70641. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  70642. // css += ".babylonVRicon.vrdisplaysupported { }";
  70643. // css += ".babylonVRicon.vrdisplayready { }";
  70644. // css += ".babylonVRicon.vrdisplayrequesting { }";
  70645. var style = document.createElement('style');
  70646. style.appendChild(document.createTextNode(css));
  70647. document.getElementsByTagName('head')[0].appendChild(style);
  70648. if (this._canvas) {
  70649. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  70650. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  70651. this._btnVR.addEventListener("click", function () {
  70652. _this.enterVR();
  70653. });
  70654. window.addEventListener("resize", function () {
  70655. if (_this._canvas) {
  70656. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  70657. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  70658. }
  70659. if (_this._fullscreenVRpresenting && _this._webVRready) {
  70660. _this.exitVR();
  70661. }
  70662. });
  70663. }
  70664. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70665. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70666. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70667. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70668. document.body.appendChild(this._btnVR);
  70669. // Exiting VR mode using 'ESC' key on desktop
  70670. this._onKeyDown = function (event) {
  70671. if (event.keyCode === 27 && _this.isInVRMode()) {
  70672. _this.exitVR();
  70673. }
  70674. };
  70675. document.addEventListener("keydown", this._onKeyDown);
  70676. // Exiting VR mode double tapping the touch screen
  70677. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  70678. if (_this.isInVRMode()) {
  70679. _this.exitVR();
  70680. if (_this._fullscreenVRpresenting) {
  70681. _this._scene.getEngine().switchFullscreen(true);
  70682. }
  70683. }
  70684. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  70685. // Listen for WebVR display changes
  70686. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  70687. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  70688. this._onVRRequestPresentStart = function () {
  70689. _this._webVRrequesting = true;
  70690. _this.updateButtonVisibility();
  70691. };
  70692. this._onVRRequestPresentComplete = function (success) {
  70693. _this._webVRrequesting = false;
  70694. _this.updateButtonVisibility();
  70695. };
  70696. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  70697. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  70698. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  70699. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  70700. // Create the cameras
  70701. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  70702. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  70703. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  70704. this.updateButtonVisibility();
  70705. }
  70706. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  70707. get: function () {
  70708. return this._deviceOrientationCamera;
  70709. },
  70710. enumerable: true,
  70711. configurable: true
  70712. });
  70713. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  70714. // Based on the current WebVR support, returns the current VR camera used
  70715. get: function () {
  70716. if (this._webVRready) {
  70717. return this._webVRCamera;
  70718. }
  70719. else {
  70720. return this._vrDeviceOrientationCamera;
  70721. }
  70722. },
  70723. enumerable: true,
  70724. configurable: true
  70725. });
  70726. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  70727. get: function () {
  70728. return this._webVRCamera;
  70729. },
  70730. enumerable: true,
  70731. configurable: true
  70732. });
  70733. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  70734. get: function () {
  70735. return this._vrDeviceOrientationCamera;
  70736. },
  70737. enumerable: true,
  70738. configurable: true
  70739. });
  70740. // Raised when one of the controller has loaded successfully its associated default mesh
  70741. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  70742. if (this.onControllerMeshLoaded) {
  70743. this.onControllerMeshLoaded(webVRController);
  70744. }
  70745. };
  70746. VRExperienceHelper.prototype._onFullscreenChange = function () {
  70747. if (document.fullscreen !== undefined) {
  70748. this._fullscreenVRpresenting = document.fullscreen;
  70749. }
  70750. else if (document.mozFullScreen !== undefined) {
  70751. this._fullscreenVRpresenting = document.mozFullScreen;
  70752. }
  70753. else if (document.webkitIsFullScreen !== undefined) {
  70754. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  70755. }
  70756. else if (document.msIsFullScreen !== undefined) {
  70757. this._fullscreenVRpresenting = document.msIsFullScreen;
  70758. }
  70759. if (!this._fullscreenVRpresenting && this._canvas) {
  70760. this.exitVR();
  70761. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  70762. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  70763. }
  70764. };
  70765. VRExperienceHelper.prototype.isInVRMode = function () {
  70766. return this._webVRpresenting || this._fullscreenVRpresenting;
  70767. };
  70768. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  70769. var vrDisplay = this._scene.getEngine().getVRDevice();
  70770. if (vrDisplay) {
  70771. var wasPresenting = this._webVRpresenting;
  70772. // A VR display is connected
  70773. this._webVRpresenting = vrDisplay.isPresenting;
  70774. if (wasPresenting && !this._webVRpresenting)
  70775. this.exitVR();
  70776. }
  70777. else {
  70778. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  70779. }
  70780. this.updateButtonVisibility();
  70781. };
  70782. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  70783. this._webVRsupported = eventArgs.vrSupported;
  70784. this._webVRready = !!eventArgs.vrDisplay;
  70785. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  70786. this.updateButtonVisibility();
  70787. };
  70788. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  70789. if (!this._btnVR) {
  70790. return;
  70791. }
  70792. this._btnVR.className = "babylonVRicon";
  70793. if (this.isInVRMode()) {
  70794. this._btnVR.className += " vrdisplaypresenting";
  70795. }
  70796. else {
  70797. if (this._webVRready)
  70798. this._btnVR.className += " vrdisplayready";
  70799. if (this._webVRsupported)
  70800. this._btnVR.className += " vrdisplaysupported";
  70801. if (this._webVRrequesting)
  70802. this._btnVR.className += " vrdisplayrequesting";
  70803. }
  70804. };
  70805. /**
  70806. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  70807. * Otherwise, will use the fullscreen API.
  70808. */
  70809. VRExperienceHelper.prototype.enterVR = function () {
  70810. if (this._scene.activeCamera) {
  70811. this._position = this._scene.activeCamera.position.clone();
  70812. }
  70813. if (this.onEnteringVR) {
  70814. this.onEnteringVR();
  70815. }
  70816. if (this._webVRrequesting)
  70817. return;
  70818. // If WebVR is supported and a headset is connected
  70819. if (this._webVRready) {
  70820. if (!this._webVRpresenting) {
  70821. this._webVRCamera.position = this._position;
  70822. this._scene.activeCamera = this._webVRCamera;
  70823. }
  70824. }
  70825. else {
  70826. this._vrDeviceOrientationCamera.position = this._position;
  70827. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  70828. this._scene.getEngine().switchFullscreen(true);
  70829. this.updateButtonVisibility();
  70830. }
  70831. if (this._scene.activeCamera && this._canvas) {
  70832. this._scene.activeCamera.attachControl(this._canvas);
  70833. }
  70834. };
  70835. /**
  70836. * Attempt to exit VR, or fullscreen.
  70837. */
  70838. VRExperienceHelper.prototype.exitVR = function () {
  70839. if (this.onExitingVR) {
  70840. this.onExitingVR();
  70841. }
  70842. if (this._webVRpresenting) {
  70843. this._scene.getEngine().disableVR();
  70844. }
  70845. if (this._scene.activeCamera) {
  70846. this._position = this._scene.activeCamera.position.clone();
  70847. }
  70848. this._deviceOrientationCamera.position = this._position;
  70849. this._scene.activeCamera = this._deviceOrientationCamera;
  70850. if (this._canvas) {
  70851. this._scene.activeCamera.attachControl(this._canvas);
  70852. }
  70853. this.updateButtonVisibility();
  70854. };
  70855. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  70856. get: function () {
  70857. return this._position;
  70858. },
  70859. set: function (value) {
  70860. this._position = value;
  70861. if (this._scene.activeCamera) {
  70862. this._scene.activeCamera.position = value;
  70863. }
  70864. },
  70865. enumerable: true,
  70866. configurable: true
  70867. });
  70868. VRExperienceHelper.prototype.dispose = function () {
  70869. if (this.isInVRMode()) {
  70870. this.exitVR();
  70871. }
  70872. this._deviceOrientationCamera.dispose();
  70873. if (this._webVRCamera) {
  70874. this._webVRCamera.dispose();
  70875. }
  70876. if (this._vrDeviceOrientationCamera) {
  70877. this._vrDeviceOrientationCamera.dispose();
  70878. }
  70879. document.body.removeChild(this._btnVR);
  70880. document.removeEventListener("keydown", this._onKeyDown);
  70881. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  70882. };
  70883. VRExperienceHelper.prototype.getClassName = function () {
  70884. return "VRExperienceHelper";
  70885. };
  70886. return VRExperienceHelper;
  70887. }());
  70888. BABYLON.VRExperienceHelper = VRExperienceHelper;
  70889. })(BABYLON || (BABYLON = {}));
  70890. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  70891. // Mainly based on these 2 articles :
  70892. // 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
  70893. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  70894. var BABYLON;
  70895. (function (BABYLON) {
  70896. var JoystickAxis;
  70897. (function (JoystickAxis) {
  70898. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  70899. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  70900. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  70901. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  70902. var VirtualJoystick = /** @class */ (function () {
  70903. function VirtualJoystick(leftJoystick) {
  70904. var _this = this;
  70905. if (leftJoystick) {
  70906. this._leftJoystick = true;
  70907. }
  70908. else {
  70909. this._leftJoystick = false;
  70910. }
  70911. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  70912. VirtualJoystick._globalJoystickIndex++;
  70913. // By default left & right arrow keys are moving the X
  70914. // and up & down keys are moving the Y
  70915. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70916. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70917. this.reverseLeftRight = false;
  70918. this.reverseUpDown = false;
  70919. // collections of pointers
  70920. this._touches = new BABYLON.StringDictionary();
  70921. this.deltaPosition = BABYLON.Vector3.Zero();
  70922. this._joystickSensibility = 25;
  70923. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70924. this._rotationSpeed = 25;
  70925. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  70926. this._rotateOnAxisRelativeToMesh = false;
  70927. this._onResize = function (evt) {
  70928. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70929. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70930. if (VirtualJoystick.vjCanvas) {
  70931. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  70932. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  70933. }
  70934. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  70935. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  70936. };
  70937. // injecting a canvas element on top of the canvas 3D game
  70938. if (!VirtualJoystick.vjCanvas) {
  70939. window.addEventListener("resize", this._onResize, false);
  70940. VirtualJoystick.vjCanvas = document.createElement("canvas");
  70941. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70942. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70943. VirtualJoystick.vjCanvas.width = window.innerWidth;
  70944. VirtualJoystick.vjCanvas.height = window.innerHeight;
  70945. VirtualJoystick.vjCanvas.style.width = "100%";
  70946. VirtualJoystick.vjCanvas.style.height = "100%";
  70947. VirtualJoystick.vjCanvas.style.position = "absolute";
  70948. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  70949. VirtualJoystick.vjCanvas.style.top = "0px";
  70950. VirtualJoystick.vjCanvas.style.left = "0px";
  70951. VirtualJoystick.vjCanvas.style.zIndex = "5";
  70952. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  70953. // Support for jQuery PEP polyfill
  70954. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  70955. var context = VirtualJoystick.vjCanvas.getContext('2d');
  70956. if (!context) {
  70957. throw new Error("Unable to create canvas for virtual joystick");
  70958. }
  70959. VirtualJoystick.vjCanvasContext = context;
  70960. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  70961. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70962. document.body.appendChild(VirtualJoystick.vjCanvas);
  70963. }
  70964. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  70965. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  70966. this.pressed = false;
  70967. // default joystick color
  70968. this._joystickColor = "cyan";
  70969. this._joystickPointerID = -1;
  70970. // current joystick position
  70971. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  70972. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  70973. // origin joystick position
  70974. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  70975. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  70976. this._onPointerDownHandlerRef = function (evt) {
  70977. _this._onPointerDown(evt);
  70978. };
  70979. this._onPointerMoveHandlerRef = function (evt) {
  70980. _this._onPointerMove(evt);
  70981. };
  70982. this._onPointerOutHandlerRef = function (evt) {
  70983. _this._onPointerUp(evt);
  70984. };
  70985. this._onPointerUpHandlerRef = function (evt) {
  70986. _this._onPointerUp(evt);
  70987. };
  70988. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  70989. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  70990. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  70991. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  70992. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  70993. evt.preventDefault(); // Disables system menu
  70994. }, false);
  70995. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70996. }
  70997. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  70998. this._joystickSensibility = newJoystickSensibility;
  70999. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  71000. };
  71001. VirtualJoystick.prototype._onPointerDown = function (e) {
  71002. var positionOnScreenCondition;
  71003. e.preventDefault();
  71004. if (this._leftJoystick === true) {
  71005. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  71006. }
  71007. else {
  71008. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  71009. }
  71010. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  71011. // First contact will be dedicated to the virtual joystick
  71012. this._joystickPointerID = e.pointerId;
  71013. this._joystickPointerStartPos.x = e.clientX;
  71014. this._joystickPointerStartPos.y = e.clientY;
  71015. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  71016. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  71017. this._deltaJoystickVector.x = 0;
  71018. this._deltaJoystickVector.y = 0;
  71019. this.pressed = true;
  71020. this._touches.add(e.pointerId.toString(), e);
  71021. }
  71022. else {
  71023. // You can only trigger the action buttons with a joystick declared
  71024. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  71025. this._action();
  71026. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  71027. }
  71028. }
  71029. };
  71030. VirtualJoystick.prototype._onPointerMove = function (e) {
  71031. // If the current pointer is the one associated to the joystick (first touch contact)
  71032. if (this._joystickPointerID == e.pointerId) {
  71033. this._joystickPointerPos.x = e.clientX;
  71034. this._joystickPointerPos.y = e.clientY;
  71035. this._deltaJoystickVector = this._joystickPointerPos.clone();
  71036. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  71037. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  71038. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  71039. switch (this._axisTargetedByLeftAndRight) {
  71040. case JoystickAxis.X:
  71041. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  71042. break;
  71043. case JoystickAxis.Y:
  71044. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  71045. break;
  71046. case JoystickAxis.Z:
  71047. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  71048. break;
  71049. }
  71050. var directionUpDown = this.reverseUpDown ? 1 : -1;
  71051. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  71052. switch (this._axisTargetedByUpAndDown) {
  71053. case JoystickAxis.X:
  71054. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  71055. break;
  71056. case JoystickAxis.Y:
  71057. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  71058. break;
  71059. case JoystickAxis.Z:
  71060. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  71061. break;
  71062. }
  71063. }
  71064. else {
  71065. var data = this._touches.get(e.pointerId.toString());
  71066. if (data) {
  71067. data.x = e.clientX;
  71068. data.y = e.clientY;
  71069. }
  71070. }
  71071. };
  71072. VirtualJoystick.prototype._onPointerUp = function (e) {
  71073. if (this._joystickPointerID == e.pointerId) {
  71074. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  71075. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  71076. this._joystickPointerID = -1;
  71077. this.pressed = false;
  71078. }
  71079. else {
  71080. var touch = this._touches.get(e.pointerId.toString());
  71081. if (touch) {
  71082. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  71083. }
  71084. }
  71085. this._deltaJoystickVector.x = 0;
  71086. this._deltaJoystickVector.y = 0;
  71087. this._touches.remove(e.pointerId.toString());
  71088. };
  71089. /**
  71090. * Change the color of the virtual joystick
  71091. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  71092. */
  71093. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  71094. this._joystickColor = newColor;
  71095. };
  71096. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  71097. this._action = action;
  71098. };
  71099. // Define which axis you'd like to control for left & right
  71100. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  71101. switch (axis) {
  71102. case JoystickAxis.X:
  71103. case JoystickAxis.Y:
  71104. case JoystickAxis.Z:
  71105. this._axisTargetedByLeftAndRight = axis;
  71106. break;
  71107. default:
  71108. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  71109. break;
  71110. }
  71111. };
  71112. // Define which axis you'd like to control for up & down
  71113. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  71114. switch (axis) {
  71115. case JoystickAxis.X:
  71116. case JoystickAxis.Y:
  71117. case JoystickAxis.Z:
  71118. this._axisTargetedByUpAndDown = axis;
  71119. break;
  71120. default:
  71121. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  71122. break;
  71123. }
  71124. };
  71125. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  71126. var _this = this;
  71127. if (this.pressed) {
  71128. this._touches.forEach(function (key, touch) {
  71129. if (touch.pointerId === _this._joystickPointerID) {
  71130. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  71131. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  71132. VirtualJoystick.vjCanvasContext.beginPath();
  71133. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  71134. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  71135. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  71136. VirtualJoystick.vjCanvasContext.stroke();
  71137. VirtualJoystick.vjCanvasContext.closePath();
  71138. VirtualJoystick.vjCanvasContext.beginPath();
  71139. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  71140. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  71141. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  71142. VirtualJoystick.vjCanvasContext.stroke();
  71143. VirtualJoystick.vjCanvasContext.closePath();
  71144. VirtualJoystick.vjCanvasContext.beginPath();
  71145. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  71146. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  71147. VirtualJoystick.vjCanvasContext.stroke();
  71148. VirtualJoystick.vjCanvasContext.closePath();
  71149. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  71150. }
  71151. else {
  71152. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  71153. VirtualJoystick.vjCanvasContext.beginPath();
  71154. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  71155. VirtualJoystick.vjCanvasContext.beginPath();
  71156. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  71157. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  71158. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  71159. VirtualJoystick.vjCanvasContext.stroke();
  71160. VirtualJoystick.vjCanvasContext.closePath();
  71161. touch.prevX = touch.x;
  71162. touch.prevY = touch.y;
  71163. }
  71164. ;
  71165. });
  71166. }
  71167. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  71168. };
  71169. VirtualJoystick.prototype.releaseCanvas = function () {
  71170. if (VirtualJoystick.vjCanvas) {
  71171. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  71172. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  71173. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  71174. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  71175. window.removeEventListener("resize", this._onResize);
  71176. document.body.removeChild(VirtualJoystick.vjCanvas);
  71177. VirtualJoystick.vjCanvas = null;
  71178. }
  71179. };
  71180. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  71181. VirtualJoystick._globalJoystickIndex = 0;
  71182. return VirtualJoystick;
  71183. }());
  71184. BABYLON.VirtualJoystick = VirtualJoystick;
  71185. })(BABYLON || (BABYLON = {}));
  71186. //# sourceMappingURL=babylon.virtualJoystick.js.map
  71187. var BABYLON;
  71188. (function (BABYLON) {
  71189. // We're mainly based on the logic defined into the FreeCamera code
  71190. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  71191. __extends(VirtualJoysticksCamera, _super);
  71192. function VirtualJoysticksCamera(name, position, scene) {
  71193. var _this = _super.call(this, name, position, scene) || this;
  71194. _this.inputs.addVirtualJoystick();
  71195. return _this;
  71196. }
  71197. VirtualJoysticksCamera.prototype.getClassName = function () {
  71198. return "VirtualJoysticksCamera";
  71199. };
  71200. return VirtualJoysticksCamera;
  71201. }(BABYLON.FreeCamera));
  71202. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  71203. })(BABYLON || (BABYLON = {}));
  71204. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  71205. var BABYLON;
  71206. (function (BABYLON) {
  71207. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  71208. function FreeCameraVirtualJoystickInput() {
  71209. }
  71210. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  71211. return this._leftjoystick;
  71212. };
  71213. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  71214. return this._rightjoystick;
  71215. };
  71216. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  71217. if (this._leftjoystick) {
  71218. var camera = this.camera;
  71219. var speed = camera._computeLocalCameraSpeed() * 50;
  71220. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  71221. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  71222. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  71223. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  71224. if (!this._leftjoystick.pressed) {
  71225. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  71226. }
  71227. if (!this._rightjoystick.pressed) {
  71228. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  71229. }
  71230. }
  71231. };
  71232. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  71233. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  71234. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  71235. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  71236. this._leftjoystick.setJoystickSensibility(0.15);
  71237. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  71238. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  71239. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  71240. this._rightjoystick.reverseUpDown = true;
  71241. this._rightjoystick.setJoystickSensibility(0.05);
  71242. this._rightjoystick.setJoystickColor("yellow");
  71243. };
  71244. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  71245. this._leftjoystick.releaseCanvas();
  71246. this._rightjoystick.releaseCanvas();
  71247. };
  71248. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  71249. return "FreeCameraVirtualJoystickInput";
  71250. };
  71251. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  71252. return "virtualJoystick";
  71253. };
  71254. return FreeCameraVirtualJoystickInput;
  71255. }());
  71256. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  71257. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  71258. })(BABYLON || (BABYLON = {}));
  71259. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  71260. var BABYLON;
  71261. (function (BABYLON) {
  71262. var SimplificationSettings = /** @class */ (function () {
  71263. function SimplificationSettings(quality, distance, optimizeMesh) {
  71264. this.quality = quality;
  71265. this.distance = distance;
  71266. this.optimizeMesh = optimizeMesh;
  71267. }
  71268. return SimplificationSettings;
  71269. }());
  71270. BABYLON.SimplificationSettings = SimplificationSettings;
  71271. var SimplificationQueue = /** @class */ (function () {
  71272. function SimplificationQueue() {
  71273. this.running = false;
  71274. this._simplificationArray = [];
  71275. }
  71276. SimplificationQueue.prototype.addTask = function (task) {
  71277. this._simplificationArray.push(task);
  71278. };
  71279. SimplificationQueue.prototype.executeNext = function () {
  71280. var task = this._simplificationArray.pop();
  71281. if (task) {
  71282. this.running = true;
  71283. this.runSimplification(task);
  71284. }
  71285. else {
  71286. this.running = false;
  71287. }
  71288. };
  71289. SimplificationQueue.prototype.runSimplification = function (task) {
  71290. var _this = this;
  71291. if (task.parallelProcessing) {
  71292. //parallel simplifier
  71293. task.settings.forEach(function (setting) {
  71294. var simplifier = _this.getSimplifier(task);
  71295. simplifier.simplify(setting, function (newMesh) {
  71296. task.mesh.addLODLevel(setting.distance, newMesh);
  71297. newMesh.isVisible = true;
  71298. //check if it is the last
  71299. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  71300. //all done, run the success callback.
  71301. task.successCallback();
  71302. }
  71303. _this.executeNext();
  71304. });
  71305. });
  71306. }
  71307. else {
  71308. //single simplifier.
  71309. var simplifier = this.getSimplifier(task);
  71310. var runDecimation = function (setting, callback) {
  71311. simplifier.simplify(setting, function (newMesh) {
  71312. task.mesh.addLODLevel(setting.distance, newMesh);
  71313. newMesh.isVisible = true;
  71314. //run the next quality level
  71315. callback();
  71316. });
  71317. };
  71318. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  71319. runDecimation(task.settings[loop.index], function () {
  71320. loop.executeNext();
  71321. });
  71322. }, function () {
  71323. //execution ended, run the success callback.
  71324. if (task.successCallback) {
  71325. task.successCallback();
  71326. }
  71327. _this.executeNext();
  71328. });
  71329. }
  71330. };
  71331. SimplificationQueue.prototype.getSimplifier = function (task) {
  71332. switch (task.simplificationType) {
  71333. case SimplificationType.QUADRATIC:
  71334. default:
  71335. return new QuadraticErrorSimplification(task.mesh);
  71336. }
  71337. };
  71338. return SimplificationQueue;
  71339. }());
  71340. BABYLON.SimplificationQueue = SimplificationQueue;
  71341. /**
  71342. * The implemented types of simplification.
  71343. * At the moment only Quadratic Error Decimation is implemented.
  71344. */
  71345. var SimplificationType;
  71346. (function (SimplificationType) {
  71347. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  71348. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  71349. var DecimationTriangle = /** @class */ (function () {
  71350. function DecimationTriangle(vertices) {
  71351. this.vertices = vertices;
  71352. this.error = new Array(4);
  71353. this.deleted = false;
  71354. this.isDirty = false;
  71355. this.deletePending = false;
  71356. this.borderFactor = 0;
  71357. }
  71358. return DecimationTriangle;
  71359. }());
  71360. BABYLON.DecimationTriangle = DecimationTriangle;
  71361. var DecimationVertex = /** @class */ (function () {
  71362. function DecimationVertex(position, id) {
  71363. this.position = position;
  71364. this.id = id;
  71365. this.isBorder = true;
  71366. this.q = new QuadraticMatrix();
  71367. this.triangleCount = 0;
  71368. this.triangleStart = 0;
  71369. this.originalOffsets = [];
  71370. }
  71371. DecimationVertex.prototype.updatePosition = function (newPosition) {
  71372. this.position.copyFrom(newPosition);
  71373. };
  71374. return DecimationVertex;
  71375. }());
  71376. BABYLON.DecimationVertex = DecimationVertex;
  71377. var QuadraticMatrix = /** @class */ (function () {
  71378. function QuadraticMatrix(data) {
  71379. this.data = new Array(10);
  71380. for (var i = 0; i < 10; ++i) {
  71381. if (data && data[i]) {
  71382. this.data[i] = data[i];
  71383. }
  71384. else {
  71385. this.data[i] = 0;
  71386. }
  71387. }
  71388. }
  71389. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  71390. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  71391. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  71392. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  71393. return det;
  71394. };
  71395. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  71396. for (var i = 0; i < 10; ++i) {
  71397. this.data[i] += matrix.data[i];
  71398. }
  71399. };
  71400. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  71401. for (var i = 0; i < 10; ++i) {
  71402. this.data[i] += data[i];
  71403. }
  71404. };
  71405. QuadraticMatrix.prototype.add = function (matrix) {
  71406. var m = new QuadraticMatrix();
  71407. for (var i = 0; i < 10; ++i) {
  71408. m.data[i] = this.data[i] + matrix.data[i];
  71409. }
  71410. return m;
  71411. };
  71412. QuadraticMatrix.FromData = function (a, b, c, d) {
  71413. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  71414. };
  71415. //returning an array to avoid garbage collection
  71416. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  71417. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  71418. };
  71419. return QuadraticMatrix;
  71420. }());
  71421. BABYLON.QuadraticMatrix = QuadraticMatrix;
  71422. var Reference = /** @class */ (function () {
  71423. function Reference(vertexId, triangleId) {
  71424. this.vertexId = vertexId;
  71425. this.triangleId = triangleId;
  71426. }
  71427. return Reference;
  71428. }());
  71429. BABYLON.Reference = Reference;
  71430. /**
  71431. * An implementation of the Quadratic Error simplification algorithm.
  71432. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  71433. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  71434. * @author RaananW
  71435. */
  71436. var QuadraticErrorSimplification = /** @class */ (function () {
  71437. function QuadraticErrorSimplification(_mesh) {
  71438. this._mesh = _mesh;
  71439. this.initialized = false;
  71440. this.syncIterations = 5000;
  71441. this.aggressiveness = 7;
  71442. this.decimationIterations = 100;
  71443. this.boundingBoxEpsilon = BABYLON.Epsilon;
  71444. }
  71445. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  71446. var _this = this;
  71447. this.initDecimatedMesh();
  71448. //iterating through the submeshes array, one after the other.
  71449. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  71450. _this.initWithMesh(loop.index, function () {
  71451. _this.runDecimation(settings, loop.index, function () {
  71452. loop.executeNext();
  71453. });
  71454. }, settings.optimizeMesh);
  71455. }, function () {
  71456. setTimeout(function () {
  71457. successCallback(_this._reconstructedMesh);
  71458. }, 0);
  71459. });
  71460. };
  71461. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  71462. var _this = this;
  71463. var targetCount = ~~(this.triangles.length * settings.quality);
  71464. var deletedTriangles = 0;
  71465. var triangleCount = this.triangles.length;
  71466. var iterationFunction = function (iteration, callback) {
  71467. setTimeout(function () {
  71468. if (iteration % 5 === 0) {
  71469. _this.updateMesh(iteration === 0);
  71470. }
  71471. for (var i = 0; i < _this.triangles.length; ++i) {
  71472. _this.triangles[i].isDirty = false;
  71473. }
  71474. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  71475. var trianglesIterator = function (i) {
  71476. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  71477. var t = _this.triangles[tIdx];
  71478. if (!t)
  71479. return;
  71480. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  71481. return;
  71482. }
  71483. for (var j = 0; j < 3; ++j) {
  71484. if (t.error[j] < threshold) {
  71485. var deleted0 = [];
  71486. var deleted1 = [];
  71487. var v0 = t.vertices[j];
  71488. var v1 = t.vertices[(j + 1) % 3];
  71489. if (v0.isBorder || v1.isBorder)
  71490. continue;
  71491. var p = BABYLON.Vector3.Zero();
  71492. var n = BABYLON.Vector3.Zero();
  71493. var uv = BABYLON.Vector2.Zero();
  71494. var color = new BABYLON.Color4(0, 0, 0, 1);
  71495. _this.calculateError(v0, v1, p, n, uv, color);
  71496. var delTr = new Array();
  71497. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  71498. continue;
  71499. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  71500. continue;
  71501. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  71502. continue;
  71503. var uniqueArray = new Array();
  71504. delTr.forEach(function (deletedT) {
  71505. if (uniqueArray.indexOf(deletedT) === -1) {
  71506. deletedT.deletePending = true;
  71507. uniqueArray.push(deletedT);
  71508. }
  71509. });
  71510. if (uniqueArray.length % 2 !== 0) {
  71511. continue;
  71512. }
  71513. v0.q = v1.q.add(v0.q);
  71514. v0.updatePosition(p);
  71515. var tStart = _this.references.length;
  71516. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  71517. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  71518. var tCount = _this.references.length - tStart;
  71519. if (tCount <= v0.triangleCount) {
  71520. if (tCount) {
  71521. for (var c = 0; c < tCount; c++) {
  71522. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  71523. }
  71524. }
  71525. }
  71526. else {
  71527. v0.triangleStart = tStart;
  71528. }
  71529. v0.triangleCount = tCount;
  71530. break;
  71531. }
  71532. }
  71533. };
  71534. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  71535. }, 0);
  71536. };
  71537. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  71538. if (triangleCount - deletedTriangles <= targetCount)
  71539. loop.breakLoop();
  71540. else {
  71541. iterationFunction(loop.index, function () {
  71542. loop.executeNext();
  71543. });
  71544. }
  71545. }, function () {
  71546. setTimeout(function () {
  71547. //reconstruct this part of the mesh
  71548. _this.reconstructMesh(submeshIndex);
  71549. successCallback();
  71550. }, 0);
  71551. });
  71552. };
  71553. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  71554. var _this = this;
  71555. this.vertices = [];
  71556. this.triangles = [];
  71557. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71558. var indices = this._mesh.getIndices();
  71559. var submesh = this._mesh.subMeshes[submeshIndex];
  71560. var findInVertices = function (positionToSearch) {
  71561. if (optimizeMesh) {
  71562. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  71563. if (_this.vertices[ii].position.equals(positionToSearch)) {
  71564. return _this.vertices[ii];
  71565. }
  71566. }
  71567. }
  71568. return null;
  71569. };
  71570. var vertexReferences = [];
  71571. var vertexInit = function (i) {
  71572. if (!positionData) {
  71573. return;
  71574. }
  71575. var offset = i + submesh.verticesStart;
  71576. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  71577. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  71578. vertex.originalOffsets.push(offset);
  71579. if (vertex.id === _this.vertices.length) {
  71580. _this.vertices.push(vertex);
  71581. }
  71582. vertexReferences.push(vertex.id);
  71583. };
  71584. //var totalVertices = mesh.getTotalVertices();
  71585. var totalVertices = submesh.verticesCount;
  71586. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  71587. var indicesInit = function (i) {
  71588. if (!indices) {
  71589. return;
  71590. }
  71591. var offset = (submesh.indexStart / 3) + i;
  71592. var pos = (offset * 3);
  71593. var i0 = indices[pos + 0];
  71594. var i1 = indices[pos + 1];
  71595. var i2 = indices[pos + 2];
  71596. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  71597. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  71598. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  71599. var triangle = new DecimationTriangle([v0, v1, v2]);
  71600. triangle.originalOffset = pos;
  71601. _this.triangles.push(triangle);
  71602. };
  71603. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  71604. _this.init(callback);
  71605. });
  71606. });
  71607. };
  71608. QuadraticErrorSimplification.prototype.init = function (callback) {
  71609. var _this = this;
  71610. var triangleInit1 = function (i) {
  71611. var t = _this.triangles[i];
  71612. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  71613. for (var j = 0; j < 3; j++) {
  71614. 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))));
  71615. }
  71616. };
  71617. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  71618. var triangleInit2 = function (i) {
  71619. var t = _this.triangles[i];
  71620. for (var j = 0; j < 3; ++j) {
  71621. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  71622. }
  71623. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  71624. };
  71625. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  71626. _this.initialized = true;
  71627. callback();
  71628. });
  71629. });
  71630. };
  71631. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  71632. var newTriangles = [];
  71633. var i;
  71634. for (i = 0; i < this.vertices.length; ++i) {
  71635. this.vertices[i].triangleCount = 0;
  71636. }
  71637. var t;
  71638. var j;
  71639. for (i = 0; i < this.triangles.length; ++i) {
  71640. if (!this.triangles[i].deleted) {
  71641. t = this.triangles[i];
  71642. for (j = 0; j < 3; ++j) {
  71643. t.vertices[j].triangleCount = 1;
  71644. }
  71645. newTriangles.push(t);
  71646. }
  71647. }
  71648. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  71649. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  71650. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  71651. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  71652. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  71653. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  71654. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  71655. var vertexCount = 0;
  71656. for (i = 0; i < this.vertices.length; ++i) {
  71657. var vertex = this.vertices[i];
  71658. vertex.id = vertexCount;
  71659. if (vertex.triangleCount) {
  71660. vertex.originalOffsets.forEach(function (originalOffset) {
  71661. if (!normalData) {
  71662. return;
  71663. }
  71664. newPositionData.push(vertex.position.x);
  71665. newPositionData.push(vertex.position.y);
  71666. newPositionData.push(vertex.position.z);
  71667. newNormalData.push(normalData[originalOffset * 3]);
  71668. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  71669. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  71670. if (uvs && uvs.length) {
  71671. newUVsData.push(uvs[(originalOffset * 2)]);
  71672. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  71673. }
  71674. else if (colorsData && colorsData.length) {
  71675. newColorsData.push(colorsData[(originalOffset * 4)]);
  71676. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  71677. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  71678. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  71679. }
  71680. ++vertexCount;
  71681. });
  71682. }
  71683. }
  71684. var startingIndex = this._reconstructedMesh.getTotalIndices();
  71685. var startingVertex = this._reconstructedMesh.getTotalVertices();
  71686. var submeshesArray = this._reconstructedMesh.subMeshes;
  71687. this._reconstructedMesh.subMeshes = [];
  71688. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  71689. var originalIndices = this._mesh.getIndices();
  71690. for (i = 0; i < newTriangles.length; ++i) {
  71691. t = newTriangles[i]; //now get the new referencing point for each vertex
  71692. [0, 1, 2].forEach(function (idx) {
  71693. var id = originalIndices[t.originalOffset + idx];
  71694. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  71695. if (offset < 0)
  71696. offset = 0;
  71697. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  71698. });
  71699. }
  71700. //overwriting the old vertex buffers and indices.
  71701. this._reconstructedMesh.setIndices(newIndicesArray);
  71702. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  71703. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  71704. if (newUVsData.length > 0)
  71705. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  71706. if (newColorsData.length > 0)
  71707. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  71708. //create submesh
  71709. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  71710. if (submeshIndex > 0) {
  71711. this._reconstructedMesh.subMeshes = [];
  71712. submeshesArray.forEach(function (submesh) {
  71713. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  71714. });
  71715. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  71716. }
  71717. };
  71718. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  71719. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  71720. this._reconstructedMesh.material = this._mesh.material;
  71721. this._reconstructedMesh.parent = this._mesh.parent;
  71722. this._reconstructedMesh.isVisible = false;
  71723. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  71724. };
  71725. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  71726. for (var i = 0; i < vertex1.triangleCount; ++i) {
  71727. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  71728. if (t.deleted)
  71729. continue;
  71730. var s = this.references[vertex1.triangleStart + i].vertexId;
  71731. var v1 = t.vertices[(s + 1) % 3];
  71732. var v2 = t.vertices[(s + 2) % 3];
  71733. if ((v1 === vertex2 || v2 === vertex2)) {
  71734. deletedArray[i] = true;
  71735. delTr.push(t);
  71736. continue;
  71737. }
  71738. var d1 = v1.position.subtract(point);
  71739. d1 = d1.normalize();
  71740. var d2 = v2.position.subtract(point);
  71741. d2 = d2.normalize();
  71742. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  71743. return true;
  71744. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  71745. deletedArray[i] = false;
  71746. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  71747. return true;
  71748. }
  71749. return false;
  71750. };
  71751. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  71752. var newDeleted = deletedTriangles;
  71753. for (var i = 0; i < vertex.triangleCount; ++i) {
  71754. var ref = this.references[vertex.triangleStart + i];
  71755. var t = this.triangles[ref.triangleId];
  71756. if (t.deleted)
  71757. continue;
  71758. if (deletedArray[i] && t.deletePending) {
  71759. t.deleted = true;
  71760. newDeleted++;
  71761. continue;
  71762. }
  71763. t.vertices[ref.vertexId] = origVertex;
  71764. t.isDirty = true;
  71765. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  71766. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  71767. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  71768. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  71769. this.references.push(ref);
  71770. }
  71771. return newDeleted;
  71772. };
  71773. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  71774. for (var i = 0; i < this.vertices.length; ++i) {
  71775. var vCount = [];
  71776. var vId = [];
  71777. var v = this.vertices[i];
  71778. var j;
  71779. for (j = 0; j < v.triangleCount; ++j) {
  71780. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  71781. for (var ii = 0; ii < 3; ii++) {
  71782. var ofs = 0;
  71783. var vv = triangle.vertices[ii];
  71784. while (ofs < vCount.length) {
  71785. if (vId[ofs] === vv.id)
  71786. break;
  71787. ++ofs;
  71788. }
  71789. if (ofs === vCount.length) {
  71790. vCount.push(1);
  71791. vId.push(vv.id);
  71792. }
  71793. else {
  71794. vCount[ofs]++;
  71795. }
  71796. }
  71797. }
  71798. for (j = 0; j < vCount.length; ++j) {
  71799. if (vCount[j] === 1) {
  71800. this.vertices[vId[j]].isBorder = true;
  71801. }
  71802. else {
  71803. this.vertices[vId[j]].isBorder = false;
  71804. }
  71805. }
  71806. }
  71807. };
  71808. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  71809. if (identifyBorders === void 0) { identifyBorders = false; }
  71810. var i;
  71811. if (!identifyBorders) {
  71812. var newTrianglesVector = [];
  71813. for (i = 0; i < this.triangles.length; ++i) {
  71814. if (!this.triangles[i].deleted) {
  71815. newTrianglesVector.push(this.triangles[i]);
  71816. }
  71817. }
  71818. this.triangles = newTrianglesVector;
  71819. }
  71820. for (i = 0; i < this.vertices.length; ++i) {
  71821. this.vertices[i].triangleCount = 0;
  71822. this.vertices[i].triangleStart = 0;
  71823. }
  71824. var t;
  71825. var j;
  71826. var v;
  71827. for (i = 0; i < this.triangles.length; ++i) {
  71828. t = this.triangles[i];
  71829. for (j = 0; j < 3; ++j) {
  71830. v = t.vertices[j];
  71831. v.triangleCount++;
  71832. }
  71833. }
  71834. var tStart = 0;
  71835. for (i = 0; i < this.vertices.length; ++i) {
  71836. this.vertices[i].triangleStart = tStart;
  71837. tStart += this.vertices[i].triangleCount;
  71838. this.vertices[i].triangleCount = 0;
  71839. }
  71840. var newReferences = new Array(this.triangles.length * 3);
  71841. for (i = 0; i < this.triangles.length; ++i) {
  71842. t = this.triangles[i];
  71843. for (j = 0; j < 3; ++j) {
  71844. v = t.vertices[j];
  71845. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  71846. v.triangleCount++;
  71847. }
  71848. }
  71849. this.references = newReferences;
  71850. if (identifyBorders) {
  71851. this.identifyBorder();
  71852. }
  71853. };
  71854. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  71855. var x = point.x;
  71856. var y = point.y;
  71857. var z = point.z;
  71858. 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
  71859. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  71860. };
  71861. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  71862. var q = vertex1.q.add(vertex2.q);
  71863. var border = vertex1.isBorder && vertex2.isBorder;
  71864. var error = 0;
  71865. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  71866. if (qDet !== 0 && !border) {
  71867. if (!pointResult) {
  71868. pointResult = BABYLON.Vector3.Zero();
  71869. }
  71870. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  71871. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  71872. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  71873. error = this.vertexError(q, pointResult);
  71874. }
  71875. else {
  71876. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  71877. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  71878. var error1 = this.vertexError(q, vertex1.position);
  71879. var error2 = this.vertexError(q, vertex2.position);
  71880. var error3 = this.vertexError(q, p3);
  71881. error = Math.min(error1, error2, error3);
  71882. if (error === error1) {
  71883. if (pointResult) {
  71884. pointResult.copyFrom(vertex1.position);
  71885. }
  71886. }
  71887. else if (error === error2) {
  71888. if (pointResult) {
  71889. pointResult.copyFrom(vertex2.position);
  71890. }
  71891. }
  71892. else {
  71893. if (pointResult) {
  71894. pointResult.copyFrom(p3);
  71895. }
  71896. }
  71897. }
  71898. return error;
  71899. };
  71900. return QuadraticErrorSimplification;
  71901. }());
  71902. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  71903. })(BABYLON || (BABYLON = {}));
  71904. //# sourceMappingURL=babylon.meshSimplification.js.map
  71905. var BABYLON;
  71906. (function (BABYLON) {
  71907. var Internals;
  71908. (function (Internals) {
  71909. var MeshLODLevel = /** @class */ (function () {
  71910. function MeshLODLevel(distance, mesh) {
  71911. this.distance = distance;
  71912. this.mesh = mesh;
  71913. }
  71914. return MeshLODLevel;
  71915. }());
  71916. Internals.MeshLODLevel = MeshLODLevel;
  71917. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  71918. })(BABYLON || (BABYLON = {}));
  71919. //# sourceMappingURL=babylon.meshLODLevel.js.map
  71920. var BABYLON;
  71921. (function (BABYLON) {
  71922. // Standard optimizations
  71923. var SceneOptimization = /** @class */ (function () {
  71924. function SceneOptimization(priority) {
  71925. if (priority === void 0) { priority = 0; }
  71926. this.priority = priority;
  71927. this.apply = function (scene) {
  71928. return true; // Return true if everything that can be done was applied
  71929. };
  71930. }
  71931. return SceneOptimization;
  71932. }());
  71933. BABYLON.SceneOptimization = SceneOptimization;
  71934. var TextureOptimization = /** @class */ (function (_super) {
  71935. __extends(TextureOptimization, _super);
  71936. function TextureOptimization(priority, maximumSize) {
  71937. if (priority === void 0) { priority = 0; }
  71938. if (maximumSize === void 0) { maximumSize = 1024; }
  71939. var _this = _super.call(this, priority) || this;
  71940. _this.priority = priority;
  71941. _this.maximumSize = maximumSize;
  71942. _this.apply = function (scene) {
  71943. var allDone = true;
  71944. for (var index = 0; index < scene.textures.length; index++) {
  71945. var texture = scene.textures[index];
  71946. if (!texture.canRescale || texture.getContext) {
  71947. continue;
  71948. }
  71949. var currentSize = texture.getSize();
  71950. var maxDimension = Math.max(currentSize.width, currentSize.height);
  71951. if (maxDimension > _this.maximumSize) {
  71952. texture.scale(0.5);
  71953. allDone = false;
  71954. }
  71955. }
  71956. return allDone;
  71957. };
  71958. return _this;
  71959. }
  71960. return TextureOptimization;
  71961. }(SceneOptimization));
  71962. BABYLON.TextureOptimization = TextureOptimization;
  71963. var HardwareScalingOptimization = /** @class */ (function (_super) {
  71964. __extends(HardwareScalingOptimization, _super);
  71965. function HardwareScalingOptimization(priority, maximumScale) {
  71966. if (priority === void 0) { priority = 0; }
  71967. if (maximumScale === void 0) { maximumScale = 2; }
  71968. var _this = _super.call(this, priority) || this;
  71969. _this.priority = priority;
  71970. _this.maximumScale = maximumScale;
  71971. _this._currentScale = 1;
  71972. _this.apply = function (scene) {
  71973. _this._currentScale++;
  71974. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  71975. return _this._currentScale >= _this.maximumScale;
  71976. };
  71977. return _this;
  71978. }
  71979. return HardwareScalingOptimization;
  71980. }(SceneOptimization));
  71981. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  71982. var ShadowsOptimization = /** @class */ (function (_super) {
  71983. __extends(ShadowsOptimization, _super);
  71984. function ShadowsOptimization() {
  71985. var _this = _super !== null && _super.apply(this, arguments) || this;
  71986. _this.apply = function (scene) {
  71987. scene.shadowsEnabled = false;
  71988. return true;
  71989. };
  71990. return _this;
  71991. }
  71992. return ShadowsOptimization;
  71993. }(SceneOptimization));
  71994. BABYLON.ShadowsOptimization = ShadowsOptimization;
  71995. var PostProcessesOptimization = /** @class */ (function (_super) {
  71996. __extends(PostProcessesOptimization, _super);
  71997. function PostProcessesOptimization() {
  71998. var _this = _super !== null && _super.apply(this, arguments) || this;
  71999. _this.apply = function (scene) {
  72000. scene.postProcessesEnabled = false;
  72001. return true;
  72002. };
  72003. return _this;
  72004. }
  72005. return PostProcessesOptimization;
  72006. }(SceneOptimization));
  72007. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  72008. var LensFlaresOptimization = /** @class */ (function (_super) {
  72009. __extends(LensFlaresOptimization, _super);
  72010. function LensFlaresOptimization() {
  72011. var _this = _super !== null && _super.apply(this, arguments) || this;
  72012. _this.apply = function (scene) {
  72013. scene.lensFlaresEnabled = false;
  72014. return true;
  72015. };
  72016. return _this;
  72017. }
  72018. return LensFlaresOptimization;
  72019. }(SceneOptimization));
  72020. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  72021. var ParticlesOptimization = /** @class */ (function (_super) {
  72022. __extends(ParticlesOptimization, _super);
  72023. function ParticlesOptimization() {
  72024. var _this = _super !== null && _super.apply(this, arguments) || this;
  72025. _this.apply = function (scene) {
  72026. scene.particlesEnabled = false;
  72027. return true;
  72028. };
  72029. return _this;
  72030. }
  72031. return ParticlesOptimization;
  72032. }(SceneOptimization));
  72033. BABYLON.ParticlesOptimization = ParticlesOptimization;
  72034. var RenderTargetsOptimization = /** @class */ (function (_super) {
  72035. __extends(RenderTargetsOptimization, _super);
  72036. function RenderTargetsOptimization() {
  72037. var _this = _super !== null && _super.apply(this, arguments) || this;
  72038. _this.apply = function (scene) {
  72039. scene.renderTargetsEnabled = false;
  72040. return true;
  72041. };
  72042. return _this;
  72043. }
  72044. return RenderTargetsOptimization;
  72045. }(SceneOptimization));
  72046. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  72047. var MergeMeshesOptimization = /** @class */ (function (_super) {
  72048. __extends(MergeMeshesOptimization, _super);
  72049. function MergeMeshesOptimization() {
  72050. var _this = _super !== null && _super.apply(this, arguments) || this;
  72051. _this._canBeMerged = function (abstractMesh) {
  72052. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  72053. return false;
  72054. }
  72055. var mesh = abstractMesh;
  72056. if (!mesh.isVisible || !mesh.isEnabled()) {
  72057. return false;
  72058. }
  72059. if (mesh.instances.length > 0) {
  72060. return false;
  72061. }
  72062. if (mesh.skeleton || mesh.hasLODLevels) {
  72063. return false;
  72064. }
  72065. if (mesh.parent) {
  72066. return false;
  72067. }
  72068. return true;
  72069. };
  72070. _this.apply = function (scene, updateSelectionTree) {
  72071. var globalPool = scene.meshes.slice(0);
  72072. var globalLength = globalPool.length;
  72073. for (var index = 0; index < globalLength; index++) {
  72074. var currentPool = new Array();
  72075. var current = globalPool[index];
  72076. // Checks
  72077. if (!_this._canBeMerged(current)) {
  72078. continue;
  72079. }
  72080. currentPool.push(current);
  72081. // Find compatible meshes
  72082. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  72083. var otherMesh = globalPool[subIndex];
  72084. if (!_this._canBeMerged(otherMesh)) {
  72085. continue;
  72086. }
  72087. if (otherMesh.material !== current.material) {
  72088. continue;
  72089. }
  72090. if (otherMesh.checkCollisions !== current.checkCollisions) {
  72091. continue;
  72092. }
  72093. currentPool.push(otherMesh);
  72094. globalLength--;
  72095. globalPool.splice(subIndex, 1);
  72096. subIndex--;
  72097. }
  72098. if (currentPool.length < 2) {
  72099. continue;
  72100. }
  72101. // Merge meshes
  72102. BABYLON.Mesh.MergeMeshes(currentPool);
  72103. }
  72104. if (updateSelectionTree != undefined) {
  72105. if (updateSelectionTree) {
  72106. scene.createOrUpdateSelectionOctree();
  72107. }
  72108. }
  72109. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  72110. scene.createOrUpdateSelectionOctree();
  72111. }
  72112. return true;
  72113. };
  72114. return _this;
  72115. }
  72116. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  72117. get: function () {
  72118. return MergeMeshesOptimization._UpdateSelectionTree;
  72119. },
  72120. set: function (value) {
  72121. MergeMeshesOptimization._UpdateSelectionTree = value;
  72122. },
  72123. enumerable: true,
  72124. configurable: true
  72125. });
  72126. MergeMeshesOptimization._UpdateSelectionTree = false;
  72127. return MergeMeshesOptimization;
  72128. }(SceneOptimization));
  72129. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  72130. // Options
  72131. var SceneOptimizerOptions = /** @class */ (function () {
  72132. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  72133. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  72134. if (trackerDuration === void 0) { trackerDuration = 2000; }
  72135. this.targetFrameRate = targetFrameRate;
  72136. this.trackerDuration = trackerDuration;
  72137. this.optimizations = new Array();
  72138. }
  72139. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  72140. var result = new SceneOptimizerOptions(targetFrameRate);
  72141. var priority = 0;
  72142. result.optimizations.push(new MergeMeshesOptimization(priority));
  72143. result.optimizations.push(new ShadowsOptimization(priority));
  72144. result.optimizations.push(new LensFlaresOptimization(priority));
  72145. // Next priority
  72146. priority++;
  72147. result.optimizations.push(new PostProcessesOptimization(priority));
  72148. result.optimizations.push(new ParticlesOptimization(priority));
  72149. // Next priority
  72150. priority++;
  72151. result.optimizations.push(new TextureOptimization(priority, 1024));
  72152. return result;
  72153. };
  72154. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  72155. var result = new SceneOptimizerOptions(targetFrameRate);
  72156. var priority = 0;
  72157. result.optimizations.push(new MergeMeshesOptimization(priority));
  72158. result.optimizations.push(new ShadowsOptimization(priority));
  72159. result.optimizations.push(new LensFlaresOptimization(priority));
  72160. // Next priority
  72161. priority++;
  72162. result.optimizations.push(new PostProcessesOptimization(priority));
  72163. result.optimizations.push(new ParticlesOptimization(priority));
  72164. // Next priority
  72165. priority++;
  72166. result.optimizations.push(new TextureOptimization(priority, 512));
  72167. // Next priority
  72168. priority++;
  72169. result.optimizations.push(new RenderTargetsOptimization(priority));
  72170. // Next priority
  72171. priority++;
  72172. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  72173. return result;
  72174. };
  72175. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  72176. var result = new SceneOptimizerOptions(targetFrameRate);
  72177. var priority = 0;
  72178. result.optimizations.push(new MergeMeshesOptimization(priority));
  72179. result.optimizations.push(new ShadowsOptimization(priority));
  72180. result.optimizations.push(new LensFlaresOptimization(priority));
  72181. // Next priority
  72182. priority++;
  72183. result.optimizations.push(new PostProcessesOptimization(priority));
  72184. result.optimizations.push(new ParticlesOptimization(priority));
  72185. // Next priority
  72186. priority++;
  72187. result.optimizations.push(new TextureOptimization(priority, 256));
  72188. // Next priority
  72189. priority++;
  72190. result.optimizations.push(new RenderTargetsOptimization(priority));
  72191. // Next priority
  72192. priority++;
  72193. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  72194. return result;
  72195. };
  72196. return SceneOptimizerOptions;
  72197. }());
  72198. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  72199. // Scene optimizer tool
  72200. var SceneOptimizer = /** @class */ (function () {
  72201. function SceneOptimizer() {
  72202. }
  72203. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  72204. // TODO: add an epsilon
  72205. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  72206. if (onSuccess) {
  72207. onSuccess();
  72208. }
  72209. return;
  72210. }
  72211. // Apply current level of optimizations
  72212. var allDone = true;
  72213. var noOptimizationApplied = true;
  72214. for (var index = 0; index < options.optimizations.length; index++) {
  72215. var optimization = options.optimizations[index];
  72216. if (optimization.priority === currentPriorityLevel) {
  72217. noOptimizationApplied = false;
  72218. allDone = allDone && optimization.apply(scene);
  72219. }
  72220. }
  72221. // If no optimization was applied, this is a failure :(
  72222. if (noOptimizationApplied) {
  72223. if (onFailure) {
  72224. onFailure();
  72225. }
  72226. return;
  72227. }
  72228. // If all optimizations were done, move to next level
  72229. if (allDone) {
  72230. currentPriorityLevel++;
  72231. }
  72232. // Let's the system running for a specific amount of time before checking FPS
  72233. scene.executeWhenReady(function () {
  72234. setTimeout(function () {
  72235. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  72236. }, options.trackerDuration);
  72237. });
  72238. };
  72239. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  72240. if (!options) {
  72241. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  72242. }
  72243. // Let's the system running for a specific amount of time before checking FPS
  72244. scene.executeWhenReady(function () {
  72245. setTimeout(function () {
  72246. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  72247. }, options.trackerDuration);
  72248. });
  72249. };
  72250. return SceneOptimizer;
  72251. }());
  72252. BABYLON.SceneOptimizer = SceneOptimizer;
  72253. })(BABYLON || (BABYLON = {}));
  72254. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  72255. var BABYLON;
  72256. (function (BABYLON) {
  72257. var OutlineRenderer = /** @class */ (function () {
  72258. function OutlineRenderer(scene) {
  72259. this.zOffset = 1;
  72260. this._scene = scene;
  72261. }
  72262. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  72263. var _this = this;
  72264. if (useOverlay === void 0) { useOverlay = false; }
  72265. var scene = this._scene;
  72266. var engine = this._scene.getEngine();
  72267. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72268. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  72269. return;
  72270. }
  72271. var mesh = subMesh.getRenderingMesh();
  72272. var material = subMesh.getMaterial();
  72273. if (!material || !scene.activeCamera) {
  72274. return;
  72275. }
  72276. engine.enableEffect(this._effect);
  72277. // Logarithmic depth
  72278. if (material.useLogarithmicDepth) {
  72279. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  72280. }
  72281. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  72282. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  72283. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72284. // Bones
  72285. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72286. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72287. }
  72288. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  72289. // Alpha test
  72290. if (material && material.needAlphaTesting()) {
  72291. var alphaTexture = material.getAlphaTestTexture();
  72292. if (alphaTexture) {
  72293. this._effect.setTexture("diffuseSampler", alphaTexture);
  72294. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72295. }
  72296. }
  72297. engine.setZOffset(-this.zOffset);
  72298. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  72299. engine.setZOffset(0);
  72300. };
  72301. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  72302. var defines = [];
  72303. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  72304. var mesh = subMesh.getMesh();
  72305. var material = subMesh.getMaterial();
  72306. if (material) {
  72307. // Alpha test
  72308. if (material.needAlphaTesting()) {
  72309. defines.push("#define ALPHATEST");
  72310. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72311. attribs.push(BABYLON.VertexBuffer.UVKind);
  72312. defines.push("#define UV1");
  72313. }
  72314. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72315. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72316. defines.push("#define UV2");
  72317. }
  72318. }
  72319. //Logarithmic depth
  72320. if (material.useLogarithmicDepth) {
  72321. defines.push("#define LOGARITHMICDEPTH");
  72322. }
  72323. }
  72324. // Bones
  72325. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72326. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72327. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72328. if (mesh.numBoneInfluencers > 4) {
  72329. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72330. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72331. }
  72332. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72333. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72334. }
  72335. else {
  72336. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72337. }
  72338. // Instances
  72339. if (useInstances) {
  72340. defines.push("#define INSTANCES");
  72341. attribs.push("world0");
  72342. attribs.push("world1");
  72343. attribs.push("world2");
  72344. attribs.push("world3");
  72345. }
  72346. // Get correct effect
  72347. var join = defines.join("\n");
  72348. if (this._cachedDefines !== join) {
  72349. this._cachedDefines = join;
  72350. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  72351. }
  72352. return this._effect.isReady();
  72353. };
  72354. return OutlineRenderer;
  72355. }());
  72356. BABYLON.OutlineRenderer = OutlineRenderer;
  72357. })(BABYLON || (BABYLON = {}));
  72358. //# sourceMappingURL=babylon.outlineRenderer.js.map
  72359. var BABYLON;
  72360. (function (BABYLON) {
  72361. var FaceAdjacencies = /** @class */ (function () {
  72362. function FaceAdjacencies() {
  72363. this.edges = new Array();
  72364. this.edgesConnectedCount = 0;
  72365. }
  72366. return FaceAdjacencies;
  72367. }());
  72368. var EdgesRenderer = /** @class */ (function () {
  72369. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  72370. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  72371. if (epsilon === void 0) { epsilon = 0.95; }
  72372. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  72373. this.edgesWidthScalerForOrthographic = 1000.0;
  72374. this.edgesWidthScalerForPerspective = 50.0;
  72375. this._linesPositions = new Array();
  72376. this._linesNormals = new Array();
  72377. this._linesIndices = new Array();
  72378. this._buffers = {};
  72379. this._checkVerticesInsteadOfIndices = false;
  72380. this._source = source;
  72381. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  72382. this._epsilon = epsilon;
  72383. this._prepareRessources();
  72384. this._generateEdgesLines();
  72385. }
  72386. EdgesRenderer.prototype._prepareRessources = function () {
  72387. if (this._lineShader) {
  72388. return;
  72389. }
  72390. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  72391. attributes: ["position", "normal"],
  72392. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  72393. });
  72394. this._lineShader.disableDepthWrite = true;
  72395. this._lineShader.backFaceCulling = false;
  72396. };
  72397. EdgesRenderer.prototype._rebuild = function () {
  72398. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  72399. if (buffer) {
  72400. buffer._rebuild();
  72401. }
  72402. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  72403. if (buffer) {
  72404. buffer._rebuild();
  72405. }
  72406. var scene = this._source.getScene();
  72407. var engine = scene.getEngine();
  72408. this._ib = engine.createIndexBuffer(this._linesIndices);
  72409. };
  72410. EdgesRenderer.prototype.dispose = function () {
  72411. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  72412. if (buffer) {
  72413. buffer.dispose();
  72414. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  72415. }
  72416. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  72417. if (buffer) {
  72418. buffer.dispose();
  72419. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  72420. }
  72421. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  72422. this._lineShader.dispose();
  72423. };
  72424. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  72425. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  72426. return 0;
  72427. }
  72428. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  72429. return 1;
  72430. }
  72431. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  72432. return 2;
  72433. }
  72434. return -1;
  72435. };
  72436. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  72437. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  72438. return 0;
  72439. }
  72440. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  72441. return 1;
  72442. }
  72443. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  72444. return 2;
  72445. }
  72446. return -1;
  72447. };
  72448. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  72449. var needToCreateLine;
  72450. if (edge === undefined) {
  72451. needToCreateLine = true;
  72452. }
  72453. else {
  72454. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  72455. needToCreateLine = dotProduct < this._epsilon;
  72456. }
  72457. if (needToCreateLine) {
  72458. var offset = this._linesPositions.length / 3;
  72459. var normal = p0.subtract(p1);
  72460. normal.normalize();
  72461. // Positions
  72462. this._linesPositions.push(p0.x);
  72463. this._linesPositions.push(p0.y);
  72464. this._linesPositions.push(p0.z);
  72465. this._linesPositions.push(p0.x);
  72466. this._linesPositions.push(p0.y);
  72467. this._linesPositions.push(p0.z);
  72468. this._linesPositions.push(p1.x);
  72469. this._linesPositions.push(p1.y);
  72470. this._linesPositions.push(p1.z);
  72471. this._linesPositions.push(p1.x);
  72472. this._linesPositions.push(p1.y);
  72473. this._linesPositions.push(p1.z);
  72474. // Normals
  72475. this._linesNormals.push(p1.x);
  72476. this._linesNormals.push(p1.y);
  72477. this._linesNormals.push(p1.z);
  72478. this._linesNormals.push(-1);
  72479. this._linesNormals.push(p1.x);
  72480. this._linesNormals.push(p1.y);
  72481. this._linesNormals.push(p1.z);
  72482. this._linesNormals.push(1);
  72483. this._linesNormals.push(p0.x);
  72484. this._linesNormals.push(p0.y);
  72485. this._linesNormals.push(p0.z);
  72486. this._linesNormals.push(-1);
  72487. this._linesNormals.push(p0.x);
  72488. this._linesNormals.push(p0.y);
  72489. this._linesNormals.push(p0.z);
  72490. this._linesNormals.push(1);
  72491. // Indices
  72492. this._linesIndices.push(offset);
  72493. this._linesIndices.push(offset + 1);
  72494. this._linesIndices.push(offset + 2);
  72495. this._linesIndices.push(offset);
  72496. this._linesIndices.push(offset + 2);
  72497. this._linesIndices.push(offset + 3);
  72498. }
  72499. };
  72500. EdgesRenderer.prototype._generateEdgesLines = function () {
  72501. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  72502. var indices = this._source.getIndices();
  72503. if (!indices || !positions) {
  72504. return;
  72505. }
  72506. // First let's find adjacencies
  72507. var adjacencies = new Array();
  72508. var faceNormals = new Array();
  72509. var index;
  72510. var faceAdjacencies;
  72511. // Prepare faces
  72512. for (index = 0; index < indices.length; index += 3) {
  72513. faceAdjacencies = new FaceAdjacencies();
  72514. var p0Index = indices[index];
  72515. var p1Index = indices[index + 1];
  72516. var p2Index = indices[index + 2];
  72517. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  72518. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  72519. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  72520. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  72521. faceNormal.normalize();
  72522. faceNormals.push(faceNormal);
  72523. adjacencies.push(faceAdjacencies);
  72524. }
  72525. // Scan
  72526. for (index = 0; index < adjacencies.length; index++) {
  72527. faceAdjacencies = adjacencies[index];
  72528. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  72529. var otherFaceAdjacencies = adjacencies[otherIndex];
  72530. if (faceAdjacencies.edgesConnectedCount === 3) {
  72531. break;
  72532. }
  72533. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  72534. continue;
  72535. }
  72536. var otherP0 = indices[otherIndex * 3];
  72537. var otherP1 = indices[otherIndex * 3 + 1];
  72538. var otherP2 = indices[otherIndex * 3 + 2];
  72539. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  72540. var otherEdgeIndex = 0;
  72541. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  72542. continue;
  72543. }
  72544. switch (edgeIndex) {
  72545. case 0:
  72546. if (this._checkVerticesInsteadOfIndices) {
  72547. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  72548. }
  72549. else {
  72550. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  72551. }
  72552. break;
  72553. case 1:
  72554. if (this._checkVerticesInsteadOfIndices) {
  72555. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  72556. }
  72557. else {
  72558. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  72559. }
  72560. break;
  72561. case 2:
  72562. if (this._checkVerticesInsteadOfIndices) {
  72563. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  72564. }
  72565. else {
  72566. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  72567. }
  72568. break;
  72569. }
  72570. if (otherEdgeIndex === -1) {
  72571. continue;
  72572. }
  72573. faceAdjacencies.edges[edgeIndex] = otherIndex;
  72574. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  72575. faceAdjacencies.edgesConnectedCount++;
  72576. otherFaceAdjacencies.edgesConnectedCount++;
  72577. if (faceAdjacencies.edgesConnectedCount === 3) {
  72578. break;
  72579. }
  72580. }
  72581. }
  72582. }
  72583. // Create lines
  72584. for (index = 0; index < adjacencies.length; index++) {
  72585. // 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
  72586. var current = adjacencies[index];
  72587. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  72588. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  72589. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  72590. }
  72591. // Merge into a single mesh
  72592. var engine = this._source.getScene().getEngine();
  72593. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  72594. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  72595. this._ib = engine.createIndexBuffer(this._linesIndices);
  72596. this._indicesCount = this._linesIndices.length;
  72597. };
  72598. EdgesRenderer.prototype.render = function () {
  72599. var scene = this._source.getScene();
  72600. if (!this._lineShader.isReady() || !scene.activeCamera) {
  72601. return;
  72602. }
  72603. var engine = scene.getEngine();
  72604. this._lineShader._preBind();
  72605. // VBOs
  72606. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  72607. scene.resetCachedMaterial();
  72608. this._lineShader.setColor4("color", this._source.edgesColor);
  72609. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  72610. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  72611. }
  72612. else {
  72613. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  72614. }
  72615. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  72616. this._lineShader.bind(this._source.getWorldMatrix());
  72617. // Draw order
  72618. engine.draw(true, 0, this._indicesCount);
  72619. this._lineShader.unbind();
  72620. engine.setDepthWrite(true);
  72621. };
  72622. return EdgesRenderer;
  72623. }());
  72624. BABYLON.EdgesRenderer = EdgesRenderer;
  72625. })(BABYLON || (BABYLON = {}));
  72626. //# sourceMappingURL=babylon.edgesRenderer.js.map
  72627. var BABYLON;
  72628. (function (BABYLON) {
  72629. /**
  72630. * Special Glow Blur post process only blurring the alpha channel
  72631. * It enforces keeping the most luminous color in the color channel.
  72632. */
  72633. var GlowBlurPostProcess = /** @class */ (function (_super) {
  72634. __extends(GlowBlurPostProcess, _super);
  72635. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  72636. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72637. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  72638. _this.direction = direction;
  72639. _this.kernel = kernel;
  72640. _this.onApplyObservable.add(function (effect) {
  72641. effect.setFloat2("screenSize", _this.width, _this.height);
  72642. effect.setVector2("direction", _this.direction);
  72643. effect.setFloat("blurWidth", _this.kernel);
  72644. });
  72645. return _this;
  72646. }
  72647. return GlowBlurPostProcess;
  72648. }(BABYLON.PostProcess));
  72649. /**
  72650. * The highlight layer Helps adding a glow effect around a mesh.
  72651. *
  72652. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  72653. * glowy meshes to your scene.
  72654. *
  72655. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  72656. */
  72657. var HighlightLayer = /** @class */ (function () {
  72658. /**
  72659. * Instantiates a new highlight Layer and references it to the scene..
  72660. * @param name The name of the layer
  72661. * @param scene The scene to use the layer in
  72662. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  72663. */
  72664. function HighlightLayer(name, scene, options) {
  72665. this.name = name;
  72666. this._vertexBuffers = {};
  72667. this._mainTextureDesiredSize = { width: 0, height: 0 };
  72668. this._meshes = {};
  72669. this._maxSize = 0;
  72670. this._shouldRender = false;
  72671. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  72672. this._excludedMeshes = {};
  72673. /**
  72674. * Specifies whether or not the inner glow is ACTIVE in the layer.
  72675. */
  72676. this.innerGlow = true;
  72677. /**
  72678. * Specifies whether or not the outer glow is ACTIVE in the layer.
  72679. */
  72680. this.outerGlow = true;
  72681. /**
  72682. * Specifies wether the highlight layer is enabled or not.
  72683. */
  72684. this.isEnabled = true;
  72685. /**
  72686. * An event triggered when the highlight layer has been disposed.
  72687. * @type {BABYLON.Observable}
  72688. */
  72689. this.onDisposeObservable = new BABYLON.Observable();
  72690. /**
  72691. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  72692. * @type {BABYLON.Observable}
  72693. */
  72694. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  72695. /**
  72696. * An event triggered when the highlight layer is being blurred.
  72697. * @type {BABYLON.Observable}
  72698. */
  72699. this.onBeforeBlurObservable = new BABYLON.Observable();
  72700. /**
  72701. * An event triggered when the highlight layer has been blurred.
  72702. * @type {BABYLON.Observable}
  72703. */
  72704. this.onAfterBlurObservable = new BABYLON.Observable();
  72705. /**
  72706. * An event triggered when the glowing blurred texture is being merged in the scene.
  72707. * @type {BABYLON.Observable}
  72708. */
  72709. this.onBeforeComposeObservable = new BABYLON.Observable();
  72710. /**
  72711. * An event triggered when the glowing blurred texture has been merged in the scene.
  72712. * @type {BABYLON.Observable}
  72713. */
  72714. this.onAfterComposeObservable = new BABYLON.Observable();
  72715. /**
  72716. * An event triggered when the highlight layer changes its size.
  72717. * @type {BABYLON.Observable}
  72718. */
  72719. this.onSizeChangedObservable = new BABYLON.Observable();
  72720. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72721. var engine = scene.getEngine();
  72722. this._engine = engine;
  72723. this._maxSize = this._engine.getCaps().maxTextureSize;
  72724. this._scene.highlightLayers.push(this);
  72725. // Warn on stencil.
  72726. if (!this._engine.isStencilEnable) {
  72727. 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 }");
  72728. }
  72729. // Adapt options
  72730. this._options = options || {
  72731. mainTextureRatio: 0.5,
  72732. blurTextureSizeRatio: 0.5,
  72733. blurHorizontalSize: 1.0,
  72734. blurVerticalSize: 1.0,
  72735. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  72736. camera: null
  72737. };
  72738. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  72739. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  72740. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  72741. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  72742. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  72743. // VBO
  72744. var vertices = [];
  72745. vertices.push(1, 1);
  72746. vertices.push(-1, 1);
  72747. vertices.push(-1, -1);
  72748. vertices.push(1, -1);
  72749. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72750. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  72751. this._createIndexBuffer();
  72752. // Effect
  72753. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  72754. // Render target
  72755. this.setMainTextureSize();
  72756. // Create Textures and post processes
  72757. this.createTextureAndPostProcesses();
  72758. }
  72759. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  72760. /**
  72761. * Gets the horizontal size of the blur.
  72762. */
  72763. get: function () {
  72764. return this._horizontalBlurPostprocess.kernel;
  72765. },
  72766. /**
  72767. * Specifies the horizontal size of the blur.
  72768. */
  72769. set: function (value) {
  72770. this._horizontalBlurPostprocess.kernel = value;
  72771. },
  72772. enumerable: true,
  72773. configurable: true
  72774. });
  72775. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  72776. /**
  72777. * Gets the vertical size of the blur.
  72778. */
  72779. get: function () {
  72780. return this._verticalBlurPostprocess.kernel;
  72781. },
  72782. /**
  72783. * Specifies the vertical size of the blur.
  72784. */
  72785. set: function (value) {
  72786. this._verticalBlurPostprocess.kernel = value;
  72787. },
  72788. enumerable: true,
  72789. configurable: true
  72790. });
  72791. Object.defineProperty(HighlightLayer.prototype, "camera", {
  72792. /**
  72793. * Gets the camera attached to the layer.
  72794. */
  72795. get: function () {
  72796. return this._options.camera;
  72797. },
  72798. enumerable: true,
  72799. configurable: true
  72800. });
  72801. HighlightLayer.prototype._createIndexBuffer = function () {
  72802. var engine = this._scene.getEngine();
  72803. // Indices
  72804. var indices = [];
  72805. indices.push(0);
  72806. indices.push(1);
  72807. indices.push(2);
  72808. indices.push(0);
  72809. indices.push(2);
  72810. indices.push(3);
  72811. this._indexBuffer = engine.createIndexBuffer(indices);
  72812. };
  72813. HighlightLayer.prototype._rebuild = function () {
  72814. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72815. if (vb) {
  72816. vb._rebuild();
  72817. }
  72818. this._createIndexBuffer();
  72819. };
  72820. /**
  72821. * Creates the render target textures and post processes used in the highlight layer.
  72822. */
  72823. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  72824. var _this = this;
  72825. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  72826. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  72827. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  72828. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  72829. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  72830. width: this._mainTextureDesiredSize.width,
  72831. height: this._mainTextureDesiredSize.height
  72832. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72833. this._mainTexture.activeCamera = this._options.camera;
  72834. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72835. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72836. this._mainTexture.anisotropicFilteringLevel = 1;
  72837. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72838. this._mainTexture.renderParticles = false;
  72839. this._mainTexture.renderList = null;
  72840. this._mainTexture.ignoreCameraViewport = true;
  72841. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  72842. width: blurTextureWidth,
  72843. height: blurTextureHeight
  72844. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72845. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72846. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72847. this._blurTexture.anisotropicFilteringLevel = 16;
  72848. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72849. this._blurTexture.renderParticles = false;
  72850. this._blurTexture.ignoreCameraViewport = true;
  72851. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72852. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  72853. effect.setTexture("textureSampler", _this._mainTexture);
  72854. });
  72855. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  72856. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72857. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72858. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72859. });
  72860. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72861. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72862. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72863. });
  72864. }
  72865. else {
  72866. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72867. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72868. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72869. });
  72870. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72871. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72872. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72873. });
  72874. }
  72875. this._mainTexture.onAfterUnbindObservable.add(function () {
  72876. _this.onBeforeBlurObservable.notifyObservers(_this);
  72877. var internalTexture = _this._blurTexture.getInternalTexture();
  72878. if (internalTexture) {
  72879. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  72880. }
  72881. _this.onAfterBlurObservable.notifyObservers(_this);
  72882. });
  72883. // Custom render function
  72884. var renderSubMesh = function (subMesh) {
  72885. if (!_this._meshes) {
  72886. return;
  72887. }
  72888. var material = subMesh.getMaterial();
  72889. var mesh = subMesh.getRenderingMesh();
  72890. var scene = _this._scene;
  72891. var engine = scene.getEngine();
  72892. if (!material) {
  72893. return;
  72894. }
  72895. // Culling
  72896. engine.setState(material.backFaceCulling);
  72897. // Managing instances
  72898. var batch = mesh._getInstancesRenderList(subMesh._id);
  72899. if (batch.mustReturn) {
  72900. return;
  72901. }
  72902. // Excluded Mesh
  72903. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72904. return;
  72905. }
  72906. ;
  72907. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72908. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  72909. var emissiveTexture = null;
  72910. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  72911. emissiveTexture = material.emissiveTexture;
  72912. }
  72913. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  72914. engine.enableEffect(_this._glowMapGenerationEffect);
  72915. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  72916. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  72917. if (highlightLayerMesh) {
  72918. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  72919. }
  72920. else {
  72921. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  72922. }
  72923. // Alpha test
  72924. if (material && material.needAlphaTesting()) {
  72925. var alphaTexture = material.getAlphaTestTexture();
  72926. if (alphaTexture) {
  72927. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  72928. var textureMatrix = alphaTexture.getTextureMatrix();
  72929. if (textureMatrix) {
  72930. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  72931. }
  72932. }
  72933. }
  72934. // Glow emissive only
  72935. if (emissiveTexture) {
  72936. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  72937. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  72938. }
  72939. // Bones
  72940. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72941. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72942. }
  72943. // Draw
  72944. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  72945. }
  72946. else {
  72947. // Need to reset refresh rate of the shadowMap
  72948. _this._mainTexture.resetRefreshCounter();
  72949. }
  72950. };
  72951. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72952. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  72953. var index;
  72954. var engine = _this._scene.getEngine();
  72955. if (depthOnlySubMeshes.length) {
  72956. engine.setColorWrite(false);
  72957. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72958. renderSubMesh(depthOnlySubMeshes.data[index]);
  72959. }
  72960. engine.setColorWrite(true);
  72961. }
  72962. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72963. renderSubMesh(opaqueSubMeshes.data[index]);
  72964. }
  72965. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72966. renderSubMesh(alphaTestSubMeshes.data[index]);
  72967. }
  72968. for (index = 0; index < transparentSubMeshes.length; index++) {
  72969. renderSubMesh(transparentSubMeshes.data[index]);
  72970. }
  72971. };
  72972. this._mainTexture.onClearObservable.add(function (engine) {
  72973. engine.clear(HighlightLayer.neutralColor, true, true, true);
  72974. });
  72975. };
  72976. /**
  72977. * Checks for the readiness of the element composing the layer.
  72978. * @param subMesh the mesh to check for
  72979. * @param useInstances specify wether or not to use instances to render the mesh
  72980. * @param emissiveTexture the associated emissive texture used to generate the glow
  72981. * @return true if ready otherwise, false
  72982. */
  72983. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  72984. var material = subMesh.getMaterial();
  72985. if (!material) {
  72986. return false;
  72987. }
  72988. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  72989. return false;
  72990. }
  72991. var defines = [];
  72992. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72993. var mesh = subMesh.getMesh();
  72994. var uv1 = false;
  72995. var uv2 = false;
  72996. // Alpha test
  72997. if (material && material.needAlphaTesting()) {
  72998. var alphaTexture = material.getAlphaTestTexture();
  72999. if (alphaTexture) {
  73000. defines.push("#define ALPHATEST");
  73001. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  73002. alphaTexture.coordinatesIndex === 1) {
  73003. defines.push("#define DIFFUSEUV2");
  73004. uv2 = true;
  73005. }
  73006. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73007. defines.push("#define DIFFUSEUV1");
  73008. uv1 = true;
  73009. }
  73010. }
  73011. }
  73012. // Emissive
  73013. if (emissiveTexture) {
  73014. defines.push("#define EMISSIVE");
  73015. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  73016. emissiveTexture.coordinatesIndex === 1) {
  73017. defines.push("#define EMISSIVEUV2");
  73018. uv2 = true;
  73019. }
  73020. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73021. defines.push("#define EMISSIVEUV1");
  73022. uv1 = true;
  73023. }
  73024. }
  73025. if (uv1) {
  73026. attribs.push(BABYLON.VertexBuffer.UVKind);
  73027. defines.push("#define UV1");
  73028. }
  73029. if (uv2) {
  73030. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73031. defines.push("#define UV2");
  73032. }
  73033. // Bones
  73034. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73035. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73036. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73037. if (mesh.numBoneInfluencers > 4) {
  73038. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73039. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73040. }
  73041. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73042. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  73043. }
  73044. else {
  73045. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73046. }
  73047. // Instances
  73048. if (useInstances) {
  73049. defines.push("#define INSTANCES");
  73050. attribs.push("world0");
  73051. attribs.push("world1");
  73052. attribs.push("world2");
  73053. attribs.push("world3");
  73054. }
  73055. // Get correct effect
  73056. var join = defines.join("\n");
  73057. if (this._cachedDefines !== join) {
  73058. this._cachedDefines = join;
  73059. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  73060. }
  73061. return this._glowMapGenerationEffect.isReady();
  73062. };
  73063. /**
  73064. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  73065. */
  73066. HighlightLayer.prototype.render = function () {
  73067. var currentEffect = this._glowMapMergeEffect;
  73068. // Check
  73069. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  73070. return;
  73071. var engine = this._scene.getEngine();
  73072. this.onBeforeComposeObservable.notifyObservers(this);
  73073. // Render
  73074. engine.enableEffect(currentEffect);
  73075. engine.setState(false);
  73076. // Cache
  73077. var previousStencilBuffer = engine.getStencilBuffer();
  73078. var previousStencilFunction = engine.getStencilFunction();
  73079. var previousStencilMask = engine.getStencilMask();
  73080. var previousStencilOperationPass = engine.getStencilOperationPass();
  73081. var previousStencilOperationFail = engine.getStencilOperationFail();
  73082. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  73083. var previousAlphaMode = engine.getAlphaMode();
  73084. // Texture
  73085. currentEffect.setTexture("textureSampler", this._blurTexture);
  73086. // VBOs
  73087. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73088. // Stencil operations
  73089. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  73090. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  73091. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  73092. // Draw order
  73093. engine.setAlphaMode(this._options.alphaBlendingMode);
  73094. engine.setStencilMask(0x00);
  73095. engine.setStencilBuffer(true);
  73096. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  73097. if (this.outerGlow) {
  73098. currentEffect.setFloat("offset", 0);
  73099. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  73100. engine.draw(true, 0, 6);
  73101. }
  73102. if (this.innerGlow) {
  73103. currentEffect.setFloat("offset", 1);
  73104. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  73105. engine.draw(true, 0, 6);
  73106. }
  73107. // Restore Cache
  73108. engine.setStencilFunction(previousStencilFunction);
  73109. engine.setStencilMask(previousStencilMask);
  73110. engine.setAlphaMode(previousAlphaMode);
  73111. engine.setStencilBuffer(previousStencilBuffer);
  73112. engine.setStencilOperationPass(previousStencilOperationPass);
  73113. engine.setStencilOperationFail(previousStencilOperationFail);
  73114. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  73115. engine._stencilState.reset();
  73116. this.onAfterComposeObservable.notifyObservers(this);
  73117. // Handle size changes.
  73118. var size = this._mainTexture.getSize();
  73119. this.setMainTextureSize();
  73120. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  73121. // Recreate RTT and post processes on size change.
  73122. this.onSizeChangedObservable.notifyObservers(this);
  73123. this.disposeTextureAndPostProcesses();
  73124. this.createTextureAndPostProcesses();
  73125. }
  73126. };
  73127. /**
  73128. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  73129. * @param mesh The mesh to exclude from the highlight layer
  73130. */
  73131. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  73132. if (!this._excludedMeshes) {
  73133. return;
  73134. }
  73135. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  73136. if (!meshExcluded) {
  73137. this._excludedMeshes[mesh.uniqueId] = {
  73138. mesh: mesh,
  73139. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  73140. mesh.getEngine().setStencilBuffer(false);
  73141. }),
  73142. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  73143. mesh.getEngine().setStencilBuffer(true);
  73144. }),
  73145. };
  73146. }
  73147. };
  73148. /**
  73149. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  73150. * @param mesh The mesh to highlight
  73151. */
  73152. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  73153. if (!this._excludedMeshes) {
  73154. return;
  73155. }
  73156. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  73157. if (meshExcluded) {
  73158. if (meshExcluded.beforeRender) {
  73159. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  73160. }
  73161. if (meshExcluded.afterRender) {
  73162. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  73163. }
  73164. }
  73165. this._excludedMeshes[mesh.uniqueId] = null;
  73166. };
  73167. /**
  73168. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  73169. * @param mesh The mesh to highlight
  73170. * @param color The color of the highlight
  73171. * @param glowEmissiveOnly Extract the glow from the emissive texture
  73172. */
  73173. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  73174. var _this = this;
  73175. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  73176. if (!this._meshes) {
  73177. return;
  73178. }
  73179. var meshHighlight = this._meshes[mesh.uniqueId];
  73180. if (meshHighlight) {
  73181. meshHighlight.color = color;
  73182. }
  73183. else {
  73184. this._meshes[mesh.uniqueId] = {
  73185. mesh: mesh,
  73186. color: color,
  73187. // Lambda required for capture due to Observable this context
  73188. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  73189. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  73190. _this.defaultStencilReference(mesh);
  73191. }
  73192. else {
  73193. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  73194. }
  73195. }),
  73196. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  73197. glowEmissiveOnly: glowEmissiveOnly
  73198. };
  73199. }
  73200. this._shouldRender = true;
  73201. };
  73202. /**
  73203. * Remove a mesh from the highlight layer in order to make it stop glowing.
  73204. * @param mesh The mesh to highlight
  73205. */
  73206. HighlightLayer.prototype.removeMesh = function (mesh) {
  73207. if (!this._meshes) {
  73208. return;
  73209. }
  73210. var meshHighlight = this._meshes[mesh.uniqueId];
  73211. if (meshHighlight) {
  73212. if (meshHighlight.observerHighlight) {
  73213. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  73214. }
  73215. if (meshHighlight.observerDefault) {
  73216. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  73217. }
  73218. }
  73219. this._meshes[mesh.uniqueId] = null;
  73220. this._shouldRender = false;
  73221. for (var meshHighlightToCheck in this._meshes) {
  73222. if (meshHighlightToCheck) {
  73223. this._shouldRender = true;
  73224. break;
  73225. }
  73226. }
  73227. };
  73228. /**
  73229. * Returns true if the layer contains information to display, otherwise false.
  73230. */
  73231. HighlightLayer.prototype.shouldRender = function () {
  73232. return this.isEnabled && this._shouldRender;
  73233. };
  73234. /**
  73235. * Sets the main texture desired size which is the closest power of two
  73236. * of the engine canvas size.
  73237. */
  73238. HighlightLayer.prototype.setMainTextureSize = function () {
  73239. if (this._options.mainTextureFixedSize) {
  73240. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  73241. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  73242. }
  73243. else {
  73244. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  73245. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  73246. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  73247. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  73248. }
  73249. };
  73250. /**
  73251. * Force the stencil to the normal expected value for none glowing parts
  73252. */
  73253. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  73254. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  73255. };
  73256. /**
  73257. * Dispose only the render target textures and post process.
  73258. */
  73259. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  73260. this._blurTexture.dispose();
  73261. this._mainTexture.dispose();
  73262. this._downSamplePostprocess.dispose();
  73263. this._horizontalBlurPostprocess.dispose();
  73264. this._verticalBlurPostprocess.dispose();
  73265. };
  73266. /**
  73267. * Dispose the highlight layer and free resources.
  73268. */
  73269. HighlightLayer.prototype.dispose = function () {
  73270. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73271. if (vertexBuffer) {
  73272. vertexBuffer.dispose();
  73273. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73274. }
  73275. if (this._indexBuffer) {
  73276. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73277. this._indexBuffer = null;
  73278. }
  73279. // Clean textures and post processes
  73280. this.disposeTextureAndPostProcesses();
  73281. if (this._meshes) {
  73282. // Clean mesh references
  73283. for (var id in this._meshes) {
  73284. var meshHighlight = this._meshes[id];
  73285. if (meshHighlight && meshHighlight.mesh) {
  73286. if (meshHighlight.observerHighlight) {
  73287. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  73288. }
  73289. if (meshHighlight.observerDefault) {
  73290. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  73291. }
  73292. }
  73293. }
  73294. this._meshes = null;
  73295. }
  73296. if (this._excludedMeshes) {
  73297. for (var id in this._excludedMeshes) {
  73298. var meshHighlight = this._excludedMeshes[id];
  73299. if (meshHighlight) {
  73300. if (meshHighlight.beforeRender) {
  73301. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  73302. }
  73303. if (meshHighlight.afterRender) {
  73304. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  73305. }
  73306. }
  73307. }
  73308. this._excludedMeshes = null;
  73309. }
  73310. // Remove from scene
  73311. var index = this._scene.highlightLayers.indexOf(this, 0);
  73312. if (index > -1) {
  73313. this._scene.highlightLayers.splice(index, 1);
  73314. }
  73315. // Callback
  73316. this.onDisposeObservable.notifyObservers(this);
  73317. this.onDisposeObservable.clear();
  73318. this.onBeforeRenderMainTextureObservable.clear();
  73319. this.onBeforeBlurObservable.clear();
  73320. this.onBeforeComposeObservable.clear();
  73321. this.onAfterComposeObservable.clear();
  73322. this.onSizeChangedObservable.clear();
  73323. };
  73324. /**
  73325. * The neutral color used during the preparation of the glow effect.
  73326. * This is black by default as the blend operation is a blend operation.
  73327. */
  73328. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  73329. /**
  73330. * Stencil value used for glowing meshes.
  73331. */
  73332. HighlightLayer.glowingMeshStencilReference = 0x02;
  73333. /**
  73334. * Stencil value used for the other meshes in the scene.
  73335. */
  73336. HighlightLayer.normalMeshStencilReference = 0x01;
  73337. return HighlightLayer;
  73338. }());
  73339. BABYLON.HighlightLayer = HighlightLayer;
  73340. })(BABYLON || (BABYLON = {}));
  73341. //# sourceMappingURL=babylon.highlightlayer.js.map
  73342. var BABYLON;
  73343. (function (BABYLON) {
  73344. var AssetTaskState;
  73345. (function (AssetTaskState) {
  73346. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  73347. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  73348. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  73349. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  73350. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  73351. var AbstractAssetTask = /** @class */ (function () {
  73352. function AbstractAssetTask(name) {
  73353. this.name = name;
  73354. this.isCompleted = false;
  73355. this.taskState = AssetTaskState.INIT;
  73356. }
  73357. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  73358. var _this = this;
  73359. this.taskState = AssetTaskState.RUNNING;
  73360. this.runTask(scene, function () {
  73361. _this.onDoneCallback(onSuccess, onError);
  73362. }, function (msg, exception) {
  73363. _this.onErrorCallback(onError, msg, exception);
  73364. });
  73365. };
  73366. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73367. throw new Error("runTask is not implemented");
  73368. };
  73369. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  73370. this.taskState = AssetTaskState.ERROR;
  73371. this.errorObject = {
  73372. message: message,
  73373. exception: exception
  73374. };
  73375. if (this.onError) {
  73376. this.onError(this, message, exception);
  73377. }
  73378. onError();
  73379. };
  73380. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  73381. try {
  73382. this.taskState = AssetTaskState.DONE;
  73383. this.isCompleted = true;
  73384. if (this.onSuccess) {
  73385. this.onSuccess(this);
  73386. }
  73387. onSuccess();
  73388. }
  73389. catch (e) {
  73390. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  73391. }
  73392. };
  73393. return AbstractAssetTask;
  73394. }());
  73395. BABYLON.AbstractAssetTask = AbstractAssetTask;
  73396. var AssetsProgressEvent = /** @class */ (function () {
  73397. function AssetsProgressEvent(remainingCount, totalCount, task) {
  73398. this.remainingCount = remainingCount;
  73399. this.totalCount = totalCount;
  73400. this.task = task;
  73401. }
  73402. return AssetsProgressEvent;
  73403. }());
  73404. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  73405. var MeshAssetTask = /** @class */ (function (_super) {
  73406. __extends(MeshAssetTask, _super);
  73407. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  73408. var _this = _super.call(this, name) || this;
  73409. _this.name = name;
  73410. _this.meshesNames = meshesNames;
  73411. _this.rootUrl = rootUrl;
  73412. _this.sceneFilename = sceneFilename;
  73413. return _this;
  73414. }
  73415. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73416. var _this = this;
  73417. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  73418. _this.loadedMeshes = meshes;
  73419. _this.loadedParticleSystems = particleSystems;
  73420. _this.loadedSkeletons = skeletons;
  73421. onSuccess();
  73422. }, null, function (scene, message, exception) {
  73423. onError(message, exception);
  73424. });
  73425. };
  73426. return MeshAssetTask;
  73427. }(AbstractAssetTask));
  73428. BABYLON.MeshAssetTask = MeshAssetTask;
  73429. var TextFileAssetTask = /** @class */ (function (_super) {
  73430. __extends(TextFileAssetTask, _super);
  73431. function TextFileAssetTask(name, url) {
  73432. var _this = _super.call(this, name) || this;
  73433. _this.name = name;
  73434. _this.url = url;
  73435. return _this;
  73436. }
  73437. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73438. var _this = this;
  73439. BABYLON.Tools.LoadFile(this.url, function (data) {
  73440. _this.text = data;
  73441. onSuccess();
  73442. }, undefined, scene.database, false, function (request, exception) {
  73443. if (request) {
  73444. onError(request.status + " " + request.statusText, exception);
  73445. }
  73446. });
  73447. };
  73448. return TextFileAssetTask;
  73449. }(AbstractAssetTask));
  73450. BABYLON.TextFileAssetTask = TextFileAssetTask;
  73451. var BinaryFileAssetTask = /** @class */ (function (_super) {
  73452. __extends(BinaryFileAssetTask, _super);
  73453. function BinaryFileAssetTask(name, url) {
  73454. var _this = _super.call(this, name) || this;
  73455. _this.name = name;
  73456. _this.url = url;
  73457. return _this;
  73458. }
  73459. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73460. var _this = this;
  73461. BABYLON.Tools.LoadFile(this.url, function (data) {
  73462. _this.data = data;
  73463. onSuccess();
  73464. }, undefined, scene.database, true, function (request, exception) {
  73465. if (request) {
  73466. onError(request.status + " " + request.statusText, exception);
  73467. }
  73468. });
  73469. };
  73470. return BinaryFileAssetTask;
  73471. }(AbstractAssetTask));
  73472. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  73473. var ImageAssetTask = /** @class */ (function (_super) {
  73474. __extends(ImageAssetTask, _super);
  73475. function ImageAssetTask(name, url) {
  73476. var _this = _super.call(this, name) || this;
  73477. _this.name = name;
  73478. _this.url = url;
  73479. return _this;
  73480. }
  73481. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73482. var _this = this;
  73483. var img = new Image();
  73484. BABYLON.Tools.SetCorsBehavior(this.url, img);
  73485. img.onload = function () {
  73486. _this.image = img;
  73487. onSuccess();
  73488. };
  73489. img.onerror = function (err) {
  73490. onError("Error loading image", err);
  73491. };
  73492. img.src = this.url;
  73493. };
  73494. return ImageAssetTask;
  73495. }(AbstractAssetTask));
  73496. BABYLON.ImageAssetTask = ImageAssetTask;
  73497. var TextureAssetTask = /** @class */ (function (_super) {
  73498. __extends(TextureAssetTask, _super);
  73499. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  73500. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73501. var _this = _super.call(this, name) || this;
  73502. _this.name = name;
  73503. _this.url = url;
  73504. _this.noMipmap = noMipmap;
  73505. _this.invertY = invertY;
  73506. _this.samplingMode = samplingMode;
  73507. return _this;
  73508. }
  73509. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73510. var onload = function () {
  73511. onSuccess();
  73512. };
  73513. var onerror = function (msg, exception) {
  73514. onError(msg, exception);
  73515. };
  73516. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  73517. };
  73518. return TextureAssetTask;
  73519. }(AbstractAssetTask));
  73520. BABYLON.TextureAssetTask = TextureAssetTask;
  73521. var CubeTextureAssetTask = /** @class */ (function (_super) {
  73522. __extends(CubeTextureAssetTask, _super);
  73523. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  73524. var _this = _super.call(this, name) || this;
  73525. _this.name = name;
  73526. _this.url = url;
  73527. _this.extensions = extensions;
  73528. _this.noMipmap = noMipmap;
  73529. _this.files = files;
  73530. return _this;
  73531. }
  73532. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73533. var onload = function () {
  73534. onSuccess();
  73535. };
  73536. var onerror = function (msg, exception) {
  73537. onError(msg, exception);
  73538. };
  73539. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  73540. };
  73541. return CubeTextureAssetTask;
  73542. }(AbstractAssetTask));
  73543. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  73544. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  73545. __extends(HDRCubeTextureAssetTask, _super);
  73546. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  73547. if (noMipmap === void 0) { noMipmap = false; }
  73548. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73549. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73550. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73551. var _this = _super.call(this, name) || this;
  73552. _this.name = name;
  73553. _this.url = url;
  73554. _this.size = size;
  73555. _this.noMipmap = noMipmap;
  73556. _this.generateHarmonics = generateHarmonics;
  73557. _this.useInGammaSpace = useInGammaSpace;
  73558. _this.usePMREMGenerator = usePMREMGenerator;
  73559. return _this;
  73560. }
  73561. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  73562. var onload = function () {
  73563. onSuccess();
  73564. };
  73565. var onerror = function (message, exception) {
  73566. onError(message, exception);
  73567. };
  73568. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  73569. };
  73570. return HDRCubeTextureAssetTask;
  73571. }(AbstractAssetTask));
  73572. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  73573. var AssetsManager = /** @class */ (function () {
  73574. function AssetsManager(scene) {
  73575. this.tasks = new Array();
  73576. this.waitingTasksCount = 0;
  73577. //Observables
  73578. this.onTaskSuccessObservable = new BABYLON.Observable();
  73579. this.onTaskErrorObservable = new BABYLON.Observable();
  73580. this.onTasksDoneObservable = new BABYLON.Observable();
  73581. this.onProgressObservable = new BABYLON.Observable();
  73582. this.useDefaultLoadingScreen = true;
  73583. this._scene = scene;
  73584. }
  73585. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  73586. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  73587. this.tasks.push(task);
  73588. return task;
  73589. };
  73590. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  73591. var task = new TextFileAssetTask(taskName, url);
  73592. this.tasks.push(task);
  73593. return task;
  73594. };
  73595. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  73596. var task = new BinaryFileAssetTask(taskName, url);
  73597. this.tasks.push(task);
  73598. return task;
  73599. };
  73600. AssetsManager.prototype.addImageTask = function (taskName, url) {
  73601. var task = new ImageAssetTask(taskName, url);
  73602. this.tasks.push(task);
  73603. return task;
  73604. };
  73605. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  73606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73607. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  73608. this.tasks.push(task);
  73609. return task;
  73610. };
  73611. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  73612. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  73613. this.tasks.push(task);
  73614. return task;
  73615. };
  73616. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  73617. if (noMipmap === void 0) { noMipmap = false; }
  73618. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73619. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73620. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73621. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  73622. this.tasks.push(task);
  73623. return task;
  73624. };
  73625. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  73626. this.waitingTasksCount--;
  73627. try {
  73628. if (this.onProgress) {
  73629. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  73630. }
  73631. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  73632. }
  73633. catch (e) {
  73634. BABYLON.Tools.Error("Error running progress callbacks.");
  73635. console.log(e);
  73636. }
  73637. if (this.waitingTasksCount === 0) {
  73638. try {
  73639. if (this.onFinish) {
  73640. this.onFinish(this.tasks);
  73641. }
  73642. this.onTasksDoneObservable.notifyObservers(this.tasks);
  73643. }
  73644. catch (e) {
  73645. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  73646. console.log(e);
  73647. }
  73648. this._scene.getEngine().hideLoadingUI();
  73649. }
  73650. };
  73651. AssetsManager.prototype._runTask = function (task) {
  73652. var _this = this;
  73653. var done = function () {
  73654. try {
  73655. if (_this.onTaskSuccess) {
  73656. _this.onTaskSuccess(task);
  73657. }
  73658. _this.onTaskSuccessObservable.notifyObservers(task);
  73659. _this._decreaseWaitingTasksCount(task);
  73660. }
  73661. catch (e) {
  73662. error("Error executing task success callbacks", e);
  73663. }
  73664. };
  73665. var error = function (message, exception) {
  73666. task.errorObject = task.errorObject || {
  73667. message: message,
  73668. exception: exception
  73669. };
  73670. if (_this.onTaskError) {
  73671. _this.onTaskError(task);
  73672. }
  73673. _this.onTaskErrorObservable.notifyObservers(task);
  73674. _this._decreaseWaitingTasksCount(task);
  73675. };
  73676. task.run(this._scene, done, error);
  73677. };
  73678. AssetsManager.prototype.reset = function () {
  73679. this.tasks = new Array();
  73680. return this;
  73681. };
  73682. AssetsManager.prototype.load = function () {
  73683. this.waitingTasksCount = this.tasks.length;
  73684. if (this.waitingTasksCount === 0) {
  73685. if (this.onFinish) {
  73686. this.onFinish(this.tasks);
  73687. }
  73688. this.onTasksDoneObservable.notifyObservers(this.tasks);
  73689. return this;
  73690. }
  73691. if (this.useDefaultLoadingScreen) {
  73692. this._scene.getEngine().displayLoadingUI();
  73693. }
  73694. for (var index = 0; index < this.tasks.length; index++) {
  73695. var task = this.tasks[index];
  73696. this._runTask(task);
  73697. }
  73698. return this;
  73699. };
  73700. return AssetsManager;
  73701. }());
  73702. BABYLON.AssetsManager = AssetsManager;
  73703. })(BABYLON || (BABYLON = {}));
  73704. //# sourceMappingURL=babylon.assetsManager.js.map
  73705. var BABYLON;
  73706. (function (BABYLON) {
  73707. var serializedGeometries = [];
  73708. var serializeGeometry = function (geometry, serializationGeometries) {
  73709. if (serializedGeometries[geometry.id]) {
  73710. return;
  73711. }
  73712. if (geometry.doNotSerialize) {
  73713. return;
  73714. }
  73715. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  73716. serializationGeometries.boxes.push(geometry.serialize());
  73717. }
  73718. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  73719. serializationGeometries.spheres.push(geometry.serialize());
  73720. }
  73721. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  73722. serializationGeometries.cylinders.push(geometry.serialize());
  73723. }
  73724. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  73725. serializationGeometries.toruses.push(geometry.serialize());
  73726. }
  73727. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  73728. serializationGeometries.grounds.push(geometry.serialize());
  73729. }
  73730. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  73731. serializationGeometries.planes.push(geometry.serialize());
  73732. }
  73733. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  73734. serializationGeometries.torusKnots.push(geometry.serialize());
  73735. }
  73736. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  73737. throw new Error("Unknown primitive type");
  73738. }
  73739. else {
  73740. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  73741. }
  73742. serializedGeometries[geometry.id] = true;
  73743. };
  73744. var serializeMesh = function (mesh, serializationScene) {
  73745. var serializationObject = {};
  73746. // Geometry
  73747. var geometry = mesh._geometry;
  73748. if (geometry) {
  73749. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  73750. // 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
  73751. serializeGeometry(geometry, serializationScene.geometries);
  73752. }
  73753. }
  73754. // Custom
  73755. if (mesh.serialize) {
  73756. mesh.serialize(serializationObject);
  73757. }
  73758. return serializationObject;
  73759. };
  73760. var finalizeSingleMesh = function (mesh, serializationObject) {
  73761. //only works if the mesh is already loaded
  73762. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  73763. //serialize material
  73764. if (mesh.material) {
  73765. if (mesh.material instanceof BABYLON.StandardMaterial) {
  73766. serializationObject.materials = serializationObject.materials || [];
  73767. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  73768. serializationObject.materials.push(mesh.material.serialize());
  73769. }
  73770. }
  73771. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  73772. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  73773. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  73774. serializationObject.multiMaterials.push(mesh.material.serialize());
  73775. }
  73776. }
  73777. }
  73778. //serialize geometry
  73779. var geometry = mesh._geometry;
  73780. if (geometry) {
  73781. if (!serializationObject.geometries) {
  73782. serializationObject.geometries = {};
  73783. serializationObject.geometries.boxes = [];
  73784. serializationObject.geometries.spheres = [];
  73785. serializationObject.geometries.cylinders = [];
  73786. serializationObject.geometries.toruses = [];
  73787. serializationObject.geometries.grounds = [];
  73788. serializationObject.geometries.planes = [];
  73789. serializationObject.geometries.torusKnots = [];
  73790. serializationObject.geometries.vertexData = [];
  73791. }
  73792. serializeGeometry(geometry, serializationObject.geometries);
  73793. }
  73794. // Skeletons
  73795. if (mesh.skeleton) {
  73796. serializationObject.skeletons = serializationObject.skeletons || [];
  73797. serializationObject.skeletons.push(mesh.skeleton.serialize());
  73798. }
  73799. //serialize the actual mesh
  73800. serializationObject.meshes = serializationObject.meshes || [];
  73801. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  73802. }
  73803. };
  73804. var SceneSerializer = /** @class */ (function () {
  73805. function SceneSerializer() {
  73806. }
  73807. SceneSerializer.ClearCache = function () {
  73808. serializedGeometries = [];
  73809. };
  73810. SceneSerializer.Serialize = function (scene) {
  73811. var serializationObject = {};
  73812. SceneSerializer.ClearCache();
  73813. // Scene
  73814. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  73815. serializationObject.autoClear = scene.autoClear;
  73816. serializationObject.clearColor = scene.clearColor.asArray();
  73817. serializationObject.ambientColor = scene.ambientColor.asArray();
  73818. serializationObject.gravity = scene.gravity.asArray();
  73819. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  73820. serializationObject.workerCollisions = scene.workerCollisions;
  73821. // Fog
  73822. if (scene.fogMode && scene.fogMode !== 0) {
  73823. serializationObject.fogMode = scene.fogMode;
  73824. serializationObject.fogColor = scene.fogColor.asArray();
  73825. serializationObject.fogStart = scene.fogStart;
  73826. serializationObject.fogEnd = scene.fogEnd;
  73827. serializationObject.fogDensity = scene.fogDensity;
  73828. }
  73829. //Physics
  73830. if (scene.isPhysicsEnabled()) {
  73831. var physicEngine = scene.getPhysicsEngine();
  73832. if (physicEngine) {
  73833. serializationObject.physicsEnabled = true;
  73834. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  73835. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  73836. }
  73837. }
  73838. // Metadata
  73839. if (scene.metadata) {
  73840. serializationObject.metadata = scene.metadata;
  73841. }
  73842. // Morph targets
  73843. serializationObject.morphTargetManagers = [];
  73844. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  73845. var abstractMesh = _a[_i];
  73846. var manager = abstractMesh.morphTargetManager;
  73847. if (manager) {
  73848. serializationObject.morphTargetManagers.push(manager.serialize());
  73849. }
  73850. }
  73851. // Lights
  73852. serializationObject.lights = [];
  73853. var index;
  73854. var light;
  73855. for (index = 0; index < scene.lights.length; index++) {
  73856. light = scene.lights[index];
  73857. if (!light.doNotSerialize) {
  73858. serializationObject.lights.push(light.serialize());
  73859. }
  73860. }
  73861. // Cameras
  73862. serializationObject.cameras = [];
  73863. for (index = 0; index < scene.cameras.length; index++) {
  73864. var camera = scene.cameras[index];
  73865. if (!camera.doNotSerialize) {
  73866. serializationObject.cameras.push(camera.serialize());
  73867. }
  73868. }
  73869. if (scene.activeCamera) {
  73870. serializationObject.activeCameraID = scene.activeCamera.id;
  73871. }
  73872. // Animations
  73873. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  73874. // Materials
  73875. serializationObject.materials = [];
  73876. serializationObject.multiMaterials = [];
  73877. var material;
  73878. for (index = 0; index < scene.materials.length; index++) {
  73879. material = scene.materials[index];
  73880. if (!material.doNotSerialize) {
  73881. serializationObject.materials.push(material.serialize());
  73882. }
  73883. }
  73884. // MultiMaterials
  73885. serializationObject.multiMaterials = [];
  73886. for (index = 0; index < scene.multiMaterials.length; index++) {
  73887. var multiMaterial = scene.multiMaterials[index];
  73888. serializationObject.multiMaterials.push(multiMaterial.serialize());
  73889. }
  73890. // Skeletons
  73891. serializationObject.skeletons = [];
  73892. for (index = 0; index < scene.skeletons.length; index++) {
  73893. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  73894. }
  73895. // Transform nodes
  73896. serializationObject.transformNodes = [];
  73897. for (index = 0; index < scene.transformNodes.length; index++) {
  73898. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  73899. }
  73900. // Geometries
  73901. serializationObject.geometries = {};
  73902. serializationObject.geometries.boxes = [];
  73903. serializationObject.geometries.spheres = [];
  73904. serializationObject.geometries.cylinders = [];
  73905. serializationObject.geometries.toruses = [];
  73906. serializationObject.geometries.grounds = [];
  73907. serializationObject.geometries.planes = [];
  73908. serializationObject.geometries.torusKnots = [];
  73909. serializationObject.geometries.vertexData = [];
  73910. serializedGeometries = [];
  73911. var geometries = scene.getGeometries();
  73912. for (index = 0; index < geometries.length; index++) {
  73913. var geometry = geometries[index];
  73914. if (geometry.isReady()) {
  73915. serializeGeometry(geometry, serializationObject.geometries);
  73916. }
  73917. }
  73918. // Meshes
  73919. serializationObject.meshes = [];
  73920. for (index = 0; index < scene.meshes.length; index++) {
  73921. var abstractMesh = scene.meshes[index];
  73922. if (abstractMesh instanceof BABYLON.Mesh) {
  73923. var mesh = abstractMesh;
  73924. if (!mesh.doNotSerialize) {
  73925. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  73926. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  73927. }
  73928. }
  73929. }
  73930. }
  73931. // Particles Systems
  73932. serializationObject.particleSystems = [];
  73933. for (index = 0; index < scene.particleSystems.length; index++) {
  73934. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  73935. }
  73936. // Lens flares
  73937. serializationObject.lensFlareSystems = [];
  73938. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  73939. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  73940. }
  73941. // Shadows
  73942. serializationObject.shadowGenerators = [];
  73943. for (index = 0; index < scene.lights.length; index++) {
  73944. light = scene.lights[index];
  73945. var shadowGenerator = light.getShadowGenerator();
  73946. if (shadowGenerator) {
  73947. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73948. }
  73949. }
  73950. // Action Manager
  73951. if (scene.actionManager) {
  73952. serializationObject.actions = scene.actionManager.serialize("scene");
  73953. }
  73954. // Audio
  73955. serializationObject.sounds = [];
  73956. for (index = 0; index < scene.soundTracks.length; index++) {
  73957. var soundtrack = scene.soundTracks[index];
  73958. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  73959. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  73960. }
  73961. }
  73962. return serializationObject;
  73963. };
  73964. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  73965. if (withParents === void 0) { withParents = false; }
  73966. if (withChildren === void 0) { withChildren = false; }
  73967. var serializationObject = {};
  73968. SceneSerializer.ClearCache();
  73969. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  73970. if (withParents || withChildren) {
  73971. //deliberate for loop! not for each, appended should be processed as well.
  73972. for (var i = 0; i < toSerialize.length; ++i) {
  73973. if (withChildren) {
  73974. toSerialize[i].getDescendants().forEach(function (node) {
  73975. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  73976. toSerialize.push(node);
  73977. }
  73978. });
  73979. }
  73980. //make sure the array doesn't contain the object already
  73981. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  73982. toSerialize.push(toSerialize[i].parent);
  73983. }
  73984. }
  73985. }
  73986. toSerialize.forEach(function (mesh) {
  73987. finalizeSingleMesh(mesh, serializationObject);
  73988. });
  73989. return serializationObject;
  73990. };
  73991. return SceneSerializer;
  73992. }());
  73993. BABYLON.SceneSerializer = SceneSerializer;
  73994. })(BABYLON || (BABYLON = {}));
  73995. //# sourceMappingURL=babylon.sceneSerializer.js.map
  73996. var BABYLON;
  73997. (function (BABYLON) {
  73998. var ReflectionProbe = /** @class */ (function () {
  73999. function ReflectionProbe(name, size, scene, generateMipMaps) {
  74000. if (generateMipMaps === void 0) { generateMipMaps = true; }
  74001. var _this = this;
  74002. this.name = name;
  74003. this._viewMatrix = BABYLON.Matrix.Identity();
  74004. this._target = BABYLON.Vector3.Zero();
  74005. this._add = BABYLON.Vector3.Zero();
  74006. this.invertYAxis = false;
  74007. this.position = BABYLON.Vector3.Zero();
  74008. this._scene = scene;
  74009. this._scene.reflectionProbes.push(this);
  74010. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  74011. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  74012. switch (faceIndex) {
  74013. case 0:
  74014. _this._add.copyFromFloats(1, 0, 0);
  74015. break;
  74016. case 1:
  74017. _this._add.copyFromFloats(-1, 0, 0);
  74018. break;
  74019. case 2:
  74020. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  74021. break;
  74022. case 3:
  74023. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  74024. break;
  74025. case 4:
  74026. _this._add.copyFromFloats(0, 0, 1);
  74027. break;
  74028. case 5:
  74029. _this._add.copyFromFloats(0, 0, -1);
  74030. break;
  74031. }
  74032. if (_this._attachedMesh) {
  74033. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  74034. }
  74035. _this.position.addToRef(_this._add, _this._target);
  74036. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  74037. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  74038. scene._forcedViewPosition = _this.position;
  74039. });
  74040. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  74041. scene._forcedViewPosition = null;
  74042. scene.updateTransformMatrix(true);
  74043. });
  74044. if (scene.activeCamera) {
  74045. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74046. }
  74047. }
  74048. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  74049. get: function () {
  74050. return this._renderTargetTexture.samples;
  74051. },
  74052. set: function (value) {
  74053. this._renderTargetTexture.samples = value;
  74054. },
  74055. enumerable: true,
  74056. configurable: true
  74057. });
  74058. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  74059. get: function () {
  74060. return this._renderTargetTexture.refreshRate;
  74061. },
  74062. set: function (value) {
  74063. this._renderTargetTexture.refreshRate = value;
  74064. },
  74065. enumerable: true,
  74066. configurable: true
  74067. });
  74068. ReflectionProbe.prototype.getScene = function () {
  74069. return this._scene;
  74070. };
  74071. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  74072. get: function () {
  74073. return this._renderTargetTexture;
  74074. },
  74075. enumerable: true,
  74076. configurable: true
  74077. });
  74078. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  74079. get: function () {
  74080. return this._renderTargetTexture.renderList;
  74081. },
  74082. enumerable: true,
  74083. configurable: true
  74084. });
  74085. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  74086. this._attachedMesh = mesh;
  74087. };
  74088. /**
  74089. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  74090. *
  74091. * @param renderingGroupId The rendering group id corresponding to its index
  74092. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  74093. */
  74094. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  74095. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  74096. };
  74097. ReflectionProbe.prototype.dispose = function () {
  74098. var index = this._scene.reflectionProbes.indexOf(this);
  74099. if (index !== -1) {
  74100. // Remove from the scene if found
  74101. this._scene.reflectionProbes.splice(index, 1);
  74102. }
  74103. if (this._renderTargetTexture) {
  74104. this._renderTargetTexture.dispose();
  74105. this._renderTargetTexture = null;
  74106. }
  74107. };
  74108. return ReflectionProbe;
  74109. }());
  74110. BABYLON.ReflectionProbe = ReflectionProbe;
  74111. })(BABYLON || (BABYLON = {}));
  74112. //# sourceMappingURL=babylon.reflectionProbe.js.map
  74113. var BABYLON;
  74114. (function (BABYLON) {
  74115. var Layer = /** @class */ (function () {
  74116. function Layer(name, imgUrl, scene, isBackground, color) {
  74117. this.name = name;
  74118. this.scale = new BABYLON.Vector2(1, 1);
  74119. this.offset = new BABYLON.Vector2(0, 0);
  74120. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  74121. this.layerMask = 0x0FFFFFFF;
  74122. this._vertexBuffers = {};
  74123. // Events
  74124. /**
  74125. * An event triggered when the layer is disposed.
  74126. * @type {BABYLON.Observable}
  74127. */
  74128. this.onDisposeObservable = new BABYLON.Observable();
  74129. /**
  74130. * An event triggered before rendering the scene
  74131. * @type {BABYLON.Observable}
  74132. */
  74133. this.onBeforeRenderObservable = new BABYLON.Observable();
  74134. /**
  74135. * An event triggered after rendering the scene
  74136. * @type {BABYLON.Observable}
  74137. */
  74138. this.onAfterRenderObservable = new BABYLON.Observable();
  74139. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  74140. this.isBackground = isBackground === undefined ? true : isBackground;
  74141. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  74142. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  74143. this._scene.layers.push(this);
  74144. var engine = this._scene.getEngine();
  74145. // VBO
  74146. var vertices = [];
  74147. vertices.push(1, 1);
  74148. vertices.push(-1, 1);
  74149. vertices.push(-1, -1);
  74150. vertices.push(1, -1);
  74151. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74152. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  74153. this._createIndexBuffer();
  74154. // Effects
  74155. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  74156. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  74157. }
  74158. Object.defineProperty(Layer.prototype, "onDispose", {
  74159. set: function (callback) {
  74160. if (this._onDisposeObserver) {
  74161. this.onDisposeObservable.remove(this._onDisposeObserver);
  74162. }
  74163. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  74164. },
  74165. enumerable: true,
  74166. configurable: true
  74167. });
  74168. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  74169. set: function (callback) {
  74170. if (this._onBeforeRenderObserver) {
  74171. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  74172. }
  74173. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  74174. },
  74175. enumerable: true,
  74176. configurable: true
  74177. });
  74178. Object.defineProperty(Layer.prototype, "onAfterRender", {
  74179. set: function (callback) {
  74180. if (this._onAfterRenderObserver) {
  74181. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74182. }
  74183. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  74184. },
  74185. enumerable: true,
  74186. configurable: true
  74187. });
  74188. Layer.prototype._createIndexBuffer = function () {
  74189. var engine = this._scene.getEngine();
  74190. // Indices
  74191. var indices = [];
  74192. indices.push(0);
  74193. indices.push(1);
  74194. indices.push(2);
  74195. indices.push(0);
  74196. indices.push(2);
  74197. indices.push(3);
  74198. this._indexBuffer = engine.createIndexBuffer(indices);
  74199. };
  74200. Layer.prototype._rebuild = function () {
  74201. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74202. if (vb) {
  74203. vb._rebuild();
  74204. }
  74205. this._createIndexBuffer();
  74206. };
  74207. Layer.prototype.render = function () {
  74208. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  74209. // Check
  74210. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  74211. return;
  74212. var engine = this._scene.getEngine();
  74213. this.onBeforeRenderObservable.notifyObservers(this);
  74214. // Render
  74215. engine.enableEffect(currentEffect);
  74216. engine.setState(false);
  74217. // Texture
  74218. currentEffect.setTexture("textureSampler", this.texture);
  74219. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  74220. // Color
  74221. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  74222. // Scale / offset
  74223. currentEffect.setVector2("offset", this.offset);
  74224. currentEffect.setVector2("scale", this.scale);
  74225. // VBOs
  74226. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  74227. // Draw order
  74228. if (!this.alphaTest) {
  74229. engine.setAlphaMode(this.alphaBlendingMode);
  74230. engine.draw(true, 0, 6);
  74231. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74232. }
  74233. else {
  74234. engine.draw(true, 0, 6);
  74235. }
  74236. this.onAfterRenderObservable.notifyObservers(this);
  74237. };
  74238. Layer.prototype.dispose = function () {
  74239. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74240. if (vertexBuffer) {
  74241. vertexBuffer.dispose();
  74242. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74243. }
  74244. if (this._indexBuffer) {
  74245. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74246. this._indexBuffer = null;
  74247. }
  74248. if (this.texture) {
  74249. this.texture.dispose();
  74250. this.texture = null;
  74251. }
  74252. // Remove from scene
  74253. var index = this._scene.layers.indexOf(this);
  74254. this._scene.layers.splice(index, 1);
  74255. // Callback
  74256. this.onDisposeObservable.notifyObservers(this);
  74257. this.onDisposeObservable.clear();
  74258. this.onAfterRenderObservable.clear();
  74259. this.onBeforeRenderObservable.clear();
  74260. };
  74261. return Layer;
  74262. }());
  74263. BABYLON.Layer = Layer;
  74264. })(BABYLON || (BABYLON = {}));
  74265. //# sourceMappingURL=babylon.layer.js.map
  74266. var BABYLON;
  74267. (function (BABYLON) {
  74268. var TextureTools = /** @class */ (function () {
  74269. function TextureTools() {
  74270. }
  74271. /**
  74272. * Uses the GPU to create a copy texture rescaled at a given size
  74273. * @param texture Texture to copy from
  74274. * @param width Desired width
  74275. * @param height Desired height
  74276. * @return Generated texture
  74277. */
  74278. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  74279. if (useBilinearMode === void 0) { useBilinearMode = true; }
  74280. var scene = texture.getScene();
  74281. var engine = scene.getEngine();
  74282. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  74283. rtt.wrapU = texture.wrapU;
  74284. rtt.wrapV = texture.wrapV;
  74285. rtt.uOffset = texture.uOffset;
  74286. rtt.vOffset = texture.vOffset;
  74287. rtt.uScale = texture.uScale;
  74288. rtt.vScale = texture.vScale;
  74289. rtt.uAng = texture.uAng;
  74290. rtt.vAng = texture.vAng;
  74291. rtt.wAng = texture.wAng;
  74292. rtt.coordinatesIndex = texture.coordinatesIndex;
  74293. rtt.level = texture.level;
  74294. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  74295. rtt._texture.isReady = false;
  74296. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74297. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74298. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  74299. passPostProcess.getEffect().executeWhenCompiled(function () {
  74300. passPostProcess.onApply = function (effect) {
  74301. effect.setTexture("textureSampler", texture);
  74302. };
  74303. var internalTexture = rtt.getInternalTexture();
  74304. if (internalTexture) {
  74305. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  74306. engine.unBindFramebuffer(internalTexture);
  74307. rtt.disposeFramebufferObjects();
  74308. passPostProcess.dispose();
  74309. internalTexture.isReady = true;
  74310. }
  74311. });
  74312. return rtt;
  74313. };
  74314. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  74315. if (!scene._environmentBRDFTexture) {
  74316. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74317. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74318. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74319. scene._environmentBRDFTexture = texture;
  74320. }
  74321. return scene._environmentBRDFTexture;
  74322. };
  74323. 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=";
  74324. return TextureTools;
  74325. }());
  74326. BABYLON.TextureTools = TextureTools;
  74327. })(BABYLON || (BABYLON = {}));
  74328. //# sourceMappingURL=babylon.textureTools.js.map
  74329. var BABYLON;
  74330. (function (BABYLON) {
  74331. var FramingBehavior = /** @class */ (function () {
  74332. function FramingBehavior() {
  74333. this._mode = FramingBehavior.FitFrustumSidesMode;
  74334. this._radiusScale = 1.0;
  74335. this._positionScale = 0.5;
  74336. this._defaultElevation = 0.3;
  74337. this._elevationReturnTime = 1500;
  74338. this._elevationReturnWaitTime = 1000;
  74339. this._zoomStopsAnimation = false;
  74340. this._framingTime = 1500;
  74341. this._isPointerDown = false;
  74342. this._lastInteractionTime = -Infinity;
  74343. // Framing control
  74344. this._animatables = new Array();
  74345. this._betaIsAnimating = false;
  74346. }
  74347. Object.defineProperty(FramingBehavior.prototype, "name", {
  74348. get: function () {
  74349. return "Framing";
  74350. },
  74351. enumerable: true,
  74352. configurable: true
  74353. });
  74354. Object.defineProperty(FramingBehavior.prototype, "mode", {
  74355. /**
  74356. * Gets current mode used by the behavior.
  74357. */
  74358. get: function () {
  74359. return this._mode;
  74360. },
  74361. /**
  74362. * Sets the current mode used by the behavior
  74363. */
  74364. set: function (mode) {
  74365. this._mode = mode;
  74366. },
  74367. enumerable: true,
  74368. configurable: true
  74369. });
  74370. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  74371. /**
  74372. * Gets the scale applied to the radius
  74373. */
  74374. get: function () {
  74375. return this._radiusScale;
  74376. },
  74377. /**
  74378. * Sets the scale applied to the radius (1 by default)
  74379. */
  74380. set: function (radius) {
  74381. this._radiusScale = radius;
  74382. },
  74383. enumerable: true,
  74384. configurable: true
  74385. });
  74386. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  74387. /**
  74388. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  74389. */
  74390. get: function () {
  74391. return this._positionScale;
  74392. },
  74393. /**
  74394. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  74395. */
  74396. set: function (scale) {
  74397. this._positionScale = scale;
  74398. },
  74399. enumerable: true,
  74400. configurable: true
  74401. });
  74402. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  74403. /**
  74404. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  74405. * behaviour is triggered, in radians.
  74406. */
  74407. get: function () {
  74408. return this._defaultElevation;
  74409. },
  74410. /**
  74411. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  74412. * behaviour is triggered, in radians.
  74413. */
  74414. set: function (elevation) {
  74415. this._defaultElevation = elevation;
  74416. },
  74417. enumerable: true,
  74418. configurable: true
  74419. });
  74420. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  74421. /**
  74422. * Gets the time (in milliseconds) taken to return to the default beta position.
  74423. * Negative value indicates camera should not return to default.
  74424. */
  74425. get: function () {
  74426. return this._elevationReturnTime;
  74427. },
  74428. /**
  74429. * Sets the time (in milliseconds) taken to return to the default beta position.
  74430. * Negative value indicates camera should not return to default.
  74431. */
  74432. set: function (speed) {
  74433. this._elevationReturnTime = speed;
  74434. },
  74435. enumerable: true,
  74436. configurable: true
  74437. });
  74438. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  74439. /**
  74440. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  74441. */
  74442. get: function () {
  74443. return this._elevationReturnWaitTime;
  74444. },
  74445. /**
  74446. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  74447. */
  74448. set: function (time) {
  74449. this._elevationReturnWaitTime = time;
  74450. },
  74451. enumerable: true,
  74452. configurable: true
  74453. });
  74454. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  74455. /**
  74456. * Gets the flag that indicates if user zooming should stop animation.
  74457. */
  74458. get: function () {
  74459. return this._zoomStopsAnimation;
  74460. },
  74461. /**
  74462. * Sets the flag that indicates if user zooming should stop animation.
  74463. */
  74464. set: function (flag) {
  74465. this._zoomStopsAnimation = flag;
  74466. },
  74467. enumerable: true,
  74468. configurable: true
  74469. });
  74470. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  74471. /**
  74472. * Gets the transition time when framing the mesh, in milliseconds
  74473. */
  74474. get: function () {
  74475. return this._framingTime;
  74476. },
  74477. /**
  74478. * Sets the transition time when framing the mesh, in milliseconds
  74479. */
  74480. set: function (time) {
  74481. this._framingTime = time;
  74482. },
  74483. enumerable: true,
  74484. configurable: true
  74485. });
  74486. FramingBehavior.prototype.init = function () {
  74487. // Do notihng
  74488. };
  74489. FramingBehavior.prototype.attach = function (camera) {
  74490. var _this = this;
  74491. this._attachedCamera = camera;
  74492. var scene = this._attachedCamera.getScene();
  74493. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  74494. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  74495. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74496. _this._isPointerDown = true;
  74497. return;
  74498. }
  74499. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  74500. _this._isPointerDown = false;
  74501. }
  74502. });
  74503. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  74504. if (mesh) {
  74505. _this.zoomOnMesh(mesh);
  74506. }
  74507. });
  74508. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74509. // Stop the animation if there is user interaction and the animation should stop for this interaction
  74510. _this._applyUserInteraction();
  74511. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  74512. // back to the default position after a given timeout
  74513. _this._maintainCameraAboveGround();
  74514. });
  74515. };
  74516. FramingBehavior.prototype.detach = function () {
  74517. if (!this._attachedCamera) {
  74518. return;
  74519. }
  74520. var scene = this._attachedCamera.getScene();
  74521. if (this._onPrePointerObservableObserver) {
  74522. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  74523. }
  74524. if (this._onAfterCheckInputsObserver) {
  74525. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74526. }
  74527. if (this._onMeshTargetChangedObserver) {
  74528. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74529. }
  74530. this._attachedCamera = null;
  74531. };
  74532. /**
  74533. * Targets the given mesh and updates zoom level accordingly.
  74534. * @param mesh The mesh to target.
  74535. * @param radius Optional. If a cached radius position already exists, overrides default.
  74536. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  74537. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  74538. * @param onAnimationEnd Callback triggered at the end of the framing animation
  74539. */
  74540. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  74541. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  74542. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  74543. mesh.computeWorldMatrix(true);
  74544. var boundingBox = mesh.getBoundingInfo().boundingBox;
  74545. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  74546. };
  74547. /**
  74548. * Targets the given mesh and updates zoom level accordingly.
  74549. * @param mesh The mesh to target.
  74550. * @param radius Optional. If a cached radius position already exists, overrides default.
  74551. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  74552. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  74553. * @param onAnimationEnd Callback triggered at the end of the framing animation
  74554. */
  74555. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  74556. var _this = this;
  74557. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  74558. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  74559. var zoomTarget;
  74560. if (!this._attachedCamera) {
  74561. return;
  74562. }
  74563. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  74564. var bottom = minimumWorld.y;
  74565. var top = maximumWorld.y;
  74566. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  74567. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  74568. if (focusOnOriginXZ) {
  74569. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  74570. }
  74571. else {
  74572. var centerWorld = minimumWorld.add(radiusWorld);
  74573. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  74574. }
  74575. if (!this._vectorTransition) {
  74576. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  74577. }
  74578. this._betaIsAnimating = true;
  74579. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  74580. if (animatable) {
  74581. this._animatables.push(animatable);
  74582. }
  74583. // sets the radius and lower radius bounds
  74584. // Small delta ensures camera is not always at lower zoom limit.
  74585. var radius = 0;
  74586. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  74587. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  74588. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  74589. radius = position;
  74590. }
  74591. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  74592. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  74593. if (this._attachedCamera.lowerRadiusLimit === null) {
  74594. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  74595. }
  74596. }
  74597. // Set sensibilities
  74598. var extend = maximumWorld.subtract(minimumWorld).length();
  74599. this._attachedCamera.panningSensibility = 5000 / extend;
  74600. this._attachedCamera.wheelPrecision = 100 / radius;
  74601. // transition to new radius
  74602. if (!this._radiusTransition) {
  74603. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  74604. }
  74605. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  74606. if (onAnimationEnd) {
  74607. onAnimationEnd();
  74608. }
  74609. if (_this._attachedCamera) {
  74610. _this._attachedCamera.storeState();
  74611. }
  74612. });
  74613. if (animatable) {
  74614. this._animatables.push(animatable);
  74615. }
  74616. };
  74617. /**
  74618. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  74619. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  74620. * frustum width.
  74621. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  74622. * to fully enclose the mesh in the viewing frustum.
  74623. */
  74624. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  74625. var size = maximumWorld.subtract(minimumWorld);
  74626. var boxVectorGlobalDiagonal = size.length();
  74627. var frustumSlope = this._getFrustumSlope();
  74628. // Formula for setting distance
  74629. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  74630. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  74631. // Horizon distance
  74632. var radius = radiusWithoutFraming * this._radiusScale;
  74633. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  74634. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  74635. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  74636. var camera = this._attachedCamera;
  74637. if (!camera) {
  74638. return 0;
  74639. }
  74640. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  74641. // Don't exceed the requested limit
  74642. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  74643. }
  74644. // Don't exceed the upper radius limit
  74645. if (camera.upperRadiusLimit) {
  74646. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  74647. }
  74648. return distance;
  74649. };
  74650. /**
  74651. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  74652. * is automatically returned to its default position (expected to be above ground plane).
  74653. */
  74654. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  74655. var _this = this;
  74656. if (this._elevationReturnTime < 0) {
  74657. return;
  74658. }
  74659. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  74660. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  74661. var limitBeta = Math.PI * 0.5;
  74662. // Bring the camera back up if below the ground plane
  74663. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  74664. this._betaIsAnimating = true;
  74665. //Transition to new position
  74666. this.stopAllAnimations();
  74667. if (!this._betaTransition) {
  74668. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  74669. }
  74670. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  74671. _this._clearAnimationLocks();
  74672. _this.stopAllAnimations();
  74673. });
  74674. if (animatabe) {
  74675. this._animatables.push(animatabe);
  74676. }
  74677. }
  74678. };
  74679. /**
  74680. * Returns the frustum slope based on the canvas ratio and camera FOV
  74681. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  74682. */
  74683. FramingBehavior.prototype._getFrustumSlope = function () {
  74684. // Calculate the viewport ratio
  74685. // Aspect Ratio is Height/Width.
  74686. var camera = this._attachedCamera;
  74687. if (!camera) {
  74688. return BABYLON.Vector2.Zero();
  74689. }
  74690. var engine = camera.getScene().getEngine();
  74691. var aspectRatio = engine.getAspectRatio(camera);
  74692. // Camera FOV is the vertical field of view (top-bottom) in radians.
  74693. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  74694. var frustumSlopeY = Math.tan(camera.fov / 2);
  74695. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  74696. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  74697. // along the forward vector.
  74698. var frustumSlopeX = frustumSlopeY * aspectRatio;
  74699. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  74700. };
  74701. /**
  74702. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  74703. */
  74704. FramingBehavior.prototype._clearAnimationLocks = function () {
  74705. this._betaIsAnimating = false;
  74706. };
  74707. /**
  74708. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74709. */
  74710. FramingBehavior.prototype._applyUserInteraction = function () {
  74711. if (this.isUserIsMoving) {
  74712. this._lastInteractionTime = BABYLON.Tools.Now;
  74713. this.stopAllAnimations();
  74714. this._clearAnimationLocks();
  74715. }
  74716. };
  74717. /**
  74718. * Stops and removes all animations that have been applied to the camera
  74719. */
  74720. FramingBehavior.prototype.stopAllAnimations = function () {
  74721. if (this._attachedCamera) {
  74722. this._attachedCamera.animations = [];
  74723. }
  74724. while (this._animatables.length) {
  74725. if (this._animatables[0]) {
  74726. this._animatables[0].onAnimationEnd = null;
  74727. this._animatables[0].stop();
  74728. }
  74729. this._animatables.shift();
  74730. }
  74731. };
  74732. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  74733. /**
  74734. * Gets a value indicating if the user is moving the camera
  74735. */
  74736. get: function () {
  74737. if (!this._attachedCamera) {
  74738. return false;
  74739. }
  74740. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74741. this._attachedCamera.inertialBetaOffset !== 0 ||
  74742. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74743. this._attachedCamera.inertialPanningX !== 0 ||
  74744. this._attachedCamera.inertialPanningY !== 0 ||
  74745. this._isPointerDown;
  74746. },
  74747. enumerable: true,
  74748. configurable: true
  74749. });
  74750. /**
  74751. * The easing function used by animations
  74752. */
  74753. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  74754. /**
  74755. * The easing mode used by animations
  74756. */
  74757. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  74758. // Statics
  74759. /**
  74760. * The camera can move all the way towards the mesh.
  74761. */
  74762. FramingBehavior.IgnoreBoundsSizeMode = 0;
  74763. /**
  74764. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  74765. */
  74766. FramingBehavior.FitFrustumSidesMode = 1;
  74767. return FramingBehavior;
  74768. }());
  74769. BABYLON.FramingBehavior = FramingBehavior;
  74770. })(BABYLON || (BABYLON = {}));
  74771. //# sourceMappingURL=babylon.framingBehavior.js.map
  74772. var BABYLON;
  74773. (function (BABYLON) {
  74774. /**
  74775. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  74776. */
  74777. var BouncingBehavior = /** @class */ (function () {
  74778. function BouncingBehavior() {
  74779. /**
  74780. * The duration of the animation, in milliseconds
  74781. */
  74782. this.transitionDuration = 450;
  74783. /**
  74784. * Length of the distance animated by the transition when lower radius is reached
  74785. */
  74786. this.lowerRadiusTransitionRange = 2;
  74787. /**
  74788. * Length of the distance animated by the transition when upper radius is reached
  74789. */
  74790. this.upperRadiusTransitionRange = -2;
  74791. this._autoTransitionRange = false;
  74792. // Animations
  74793. this._radiusIsAnimating = false;
  74794. this._radiusBounceTransition = null;
  74795. this._animatables = new Array();
  74796. }
  74797. Object.defineProperty(BouncingBehavior.prototype, "name", {
  74798. get: function () {
  74799. return "Bouncing";
  74800. },
  74801. enumerable: true,
  74802. configurable: true
  74803. });
  74804. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  74805. /**
  74806. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  74807. */
  74808. get: function () {
  74809. return this._autoTransitionRange;
  74810. },
  74811. /**
  74812. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  74813. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  74814. */
  74815. set: function (value) {
  74816. var _this = this;
  74817. if (this._autoTransitionRange === value) {
  74818. return;
  74819. }
  74820. this._autoTransitionRange = value;
  74821. var camera = this._attachedCamera;
  74822. if (!camera) {
  74823. return;
  74824. }
  74825. if (value) {
  74826. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  74827. if (!mesh) {
  74828. return;
  74829. }
  74830. mesh.computeWorldMatrix(true);
  74831. var diagonal = mesh.getBoundingInfo().diagonalLength;
  74832. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  74833. _this.upperRadiusTransitionRange = diagonal * 0.05;
  74834. });
  74835. }
  74836. else if (this._onMeshTargetChangedObserver) {
  74837. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74838. }
  74839. },
  74840. enumerable: true,
  74841. configurable: true
  74842. });
  74843. BouncingBehavior.prototype.init = function () {
  74844. // Do notihng
  74845. };
  74846. BouncingBehavior.prototype.attach = function (camera) {
  74847. var _this = this;
  74848. this._attachedCamera = camera;
  74849. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74850. if (!_this._attachedCamera) {
  74851. return;
  74852. }
  74853. // Add the bounce animation to the lower radius limit
  74854. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  74855. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  74856. }
  74857. // Add the bounce animation to the upper radius limit
  74858. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  74859. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  74860. }
  74861. });
  74862. };
  74863. BouncingBehavior.prototype.detach = function () {
  74864. if (!this._attachedCamera) {
  74865. return;
  74866. }
  74867. if (this._onAfterCheckInputsObserver) {
  74868. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74869. }
  74870. if (this._onMeshTargetChangedObserver) {
  74871. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74872. }
  74873. this._attachedCamera = null;
  74874. };
  74875. /**
  74876. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  74877. * @param radiusLimit The limit to check against.
  74878. * @return Bool to indicate if at limit.
  74879. */
  74880. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  74881. if (!this._attachedCamera) {
  74882. return false;
  74883. }
  74884. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  74885. return true;
  74886. }
  74887. return false;
  74888. };
  74889. /**
  74890. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  74891. * @param radiusDelta The delta by which to animate to. Can be negative.
  74892. */
  74893. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  74894. var _this = this;
  74895. if (!this._attachedCamera) {
  74896. return;
  74897. }
  74898. if (!this._radiusBounceTransition) {
  74899. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  74900. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  74901. }
  74902. // Prevent zoom until bounce has completed
  74903. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  74904. this._attachedCamera.wheelPrecision = Infinity;
  74905. this._attachedCamera.inertialRadiusOffset = 0;
  74906. // Animate to the radius limit
  74907. this.stopAllAnimations();
  74908. this._radiusIsAnimating = true;
  74909. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  74910. if (animatable) {
  74911. this._animatables.push(animatable);
  74912. }
  74913. };
  74914. /**
  74915. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  74916. */
  74917. BouncingBehavior.prototype._clearAnimationLocks = function () {
  74918. this._radiusIsAnimating = false;
  74919. if (this._attachedCamera) {
  74920. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  74921. }
  74922. };
  74923. /**
  74924. * Stops and removes all animations that have been applied to the camera
  74925. */
  74926. BouncingBehavior.prototype.stopAllAnimations = function () {
  74927. if (this._attachedCamera) {
  74928. this._attachedCamera.animations = [];
  74929. }
  74930. while (this._animatables.length) {
  74931. this._animatables[0].onAnimationEnd = null;
  74932. this._animatables[0].stop();
  74933. this._animatables.shift();
  74934. }
  74935. };
  74936. /**
  74937. * The easing function used by animations
  74938. */
  74939. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  74940. /**
  74941. * The easing mode used by animations
  74942. */
  74943. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  74944. return BouncingBehavior;
  74945. }());
  74946. BABYLON.BouncingBehavior = BouncingBehavior;
  74947. })(BABYLON || (BABYLON = {}));
  74948. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  74949. var BABYLON;
  74950. (function (BABYLON) {
  74951. var AutoRotationBehavior = /** @class */ (function () {
  74952. function AutoRotationBehavior() {
  74953. this._zoomStopsAnimation = false;
  74954. this._idleRotationSpeed = 0.05;
  74955. this._idleRotationWaitTime = 2000;
  74956. this._idleRotationSpinupTime = 2000;
  74957. this._isPointerDown = false;
  74958. this._lastFrameTime = null;
  74959. this._lastInteractionTime = -Infinity;
  74960. this._cameraRotationSpeed = 0;
  74961. this._lastFrameRadius = 0;
  74962. }
  74963. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  74964. get: function () {
  74965. return "AutoRotation";
  74966. },
  74967. enumerable: true,
  74968. configurable: true
  74969. });
  74970. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  74971. /**
  74972. * Gets the flag that indicates if user zooming should stop animation.
  74973. */
  74974. get: function () {
  74975. return this._zoomStopsAnimation;
  74976. },
  74977. /**
  74978. * Sets the flag that indicates if user zooming should stop animation.
  74979. */
  74980. set: function (flag) {
  74981. this._zoomStopsAnimation = flag;
  74982. },
  74983. enumerable: true,
  74984. configurable: true
  74985. });
  74986. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  74987. /**
  74988. * Gets the default speed at which the camera rotates around the model.
  74989. */
  74990. get: function () {
  74991. return this._idleRotationSpeed;
  74992. },
  74993. /**
  74994. * Sets the default speed at which the camera rotates around the model.
  74995. */
  74996. set: function (speed) {
  74997. this._idleRotationSpeed = speed;
  74998. },
  74999. enumerable: true,
  75000. configurable: true
  75001. });
  75002. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  75003. /**
  75004. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  75005. */
  75006. get: function () {
  75007. return this._idleRotationWaitTime;
  75008. },
  75009. /**
  75010. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  75011. */
  75012. set: function (time) {
  75013. this._idleRotationWaitTime = time;
  75014. },
  75015. enumerable: true,
  75016. configurable: true
  75017. });
  75018. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  75019. /**
  75020. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  75021. */
  75022. get: function () {
  75023. return this._idleRotationSpinupTime;
  75024. },
  75025. /**
  75026. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  75027. */
  75028. set: function (time) {
  75029. this._idleRotationSpinupTime = time;
  75030. },
  75031. enumerable: true,
  75032. configurable: true
  75033. });
  75034. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  75035. /**
  75036. * Gets a value indicating if the camera is currently rotating because of this behavior
  75037. */
  75038. get: function () {
  75039. return Math.abs(this._cameraRotationSpeed) > 0;
  75040. },
  75041. enumerable: true,
  75042. configurable: true
  75043. });
  75044. AutoRotationBehavior.prototype.init = function () {
  75045. // Do notihng
  75046. };
  75047. AutoRotationBehavior.prototype.attach = function (camera) {
  75048. var _this = this;
  75049. this._attachedCamera = camera;
  75050. var scene = this._attachedCamera.getScene();
  75051. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  75052. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  75053. _this._isPointerDown = true;
  75054. return;
  75055. }
  75056. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  75057. _this._isPointerDown = false;
  75058. }
  75059. });
  75060. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  75061. var now = BABYLON.Tools.Now;
  75062. var dt = 0;
  75063. if (_this._lastFrameTime != null) {
  75064. dt = now - _this._lastFrameTime;
  75065. }
  75066. _this._lastFrameTime = now;
  75067. // Stop the animation if there is user interaction and the animation should stop for this interaction
  75068. _this._applyUserInteraction();
  75069. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  75070. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  75071. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  75072. // Step camera rotation by rotation speed
  75073. if (_this._attachedCamera) {
  75074. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  75075. }
  75076. });
  75077. };
  75078. AutoRotationBehavior.prototype.detach = function () {
  75079. if (!this._attachedCamera) {
  75080. return;
  75081. }
  75082. var scene = this._attachedCamera.getScene();
  75083. if (this._onPrePointerObservableObserver) {
  75084. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  75085. }
  75086. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  75087. this._attachedCamera = null;
  75088. };
  75089. /**
  75090. * Returns true if user is scrolling.
  75091. * @return true if user is scrolling.
  75092. */
  75093. AutoRotationBehavior.prototype._userIsZooming = function () {
  75094. if (!this._attachedCamera) {
  75095. return false;
  75096. }
  75097. return this._attachedCamera.inertialRadiusOffset !== 0;
  75098. };
  75099. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  75100. if (!this._attachedCamera) {
  75101. return false;
  75102. }
  75103. var zoomHasHitLimit = false;
  75104. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  75105. zoomHasHitLimit = true;
  75106. }
  75107. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  75108. this._lastFrameRadius = this._attachedCamera.radius;
  75109. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  75110. };
  75111. /**
  75112. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  75113. */
  75114. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  75115. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  75116. this._lastInteractionTime = BABYLON.Tools.Now;
  75117. }
  75118. };
  75119. // Tools
  75120. AutoRotationBehavior.prototype._userIsMoving = function () {
  75121. if (!this._attachedCamera) {
  75122. return false;
  75123. }
  75124. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  75125. this._attachedCamera.inertialBetaOffset !== 0 ||
  75126. this._attachedCamera.inertialRadiusOffset !== 0 ||
  75127. this._attachedCamera.inertialPanningX !== 0 ||
  75128. this._attachedCamera.inertialPanningY !== 0 ||
  75129. this._isPointerDown;
  75130. };
  75131. return AutoRotationBehavior;
  75132. }());
  75133. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  75134. })(BABYLON || (BABYLON = {}));
  75135. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  75136. var BABYLON;
  75137. (function (BABYLON) {
  75138. var NullEngineOptions = /** @class */ (function () {
  75139. function NullEngineOptions() {
  75140. this.renderWidth = 512;
  75141. this.renderHeight = 256;
  75142. this.textureSize = 512;
  75143. }
  75144. return NullEngineOptions;
  75145. }());
  75146. BABYLON.NullEngineOptions = NullEngineOptions;
  75147. /**
  75148. * The null engine class provides support for headless version of babylon.js.
  75149. * This can be used in server side scenario or for testing purposes
  75150. */
  75151. var NullEngine = /** @class */ (function (_super) {
  75152. __extends(NullEngine, _super);
  75153. function NullEngine(options) {
  75154. if (options === void 0) { options = new NullEngineOptions(); }
  75155. var _this = _super.call(this, null) || this;
  75156. _this._options = options;
  75157. // Init caps
  75158. // We consider we are on a webgl1 capable device
  75159. _this._caps = new BABYLON.EngineCapabilities();
  75160. _this._caps.maxTexturesImageUnits = 16;
  75161. _this._caps.maxVertexTextureImageUnits = 16;
  75162. _this._caps.maxTextureSize = 512;
  75163. _this._caps.maxCubemapTextureSize = 512;
  75164. _this._caps.maxRenderTextureSize = 512;
  75165. _this._caps.maxVertexAttribs = 16;
  75166. _this._caps.maxVaryingVectors = 16;
  75167. _this._caps.maxFragmentUniformVectors = 16;
  75168. _this._caps.maxVertexUniformVectors = 16;
  75169. // Extensions
  75170. _this._caps.standardDerivatives = false;
  75171. _this._caps.astc = null;
  75172. _this._caps.s3tc = null;
  75173. _this._caps.pvrtc = null;
  75174. _this._caps.etc1 = null;
  75175. _this._caps.etc2 = null;
  75176. _this._caps.textureAnisotropicFilterExtension = null;
  75177. _this._caps.maxAnisotropy = 0;
  75178. _this._caps.uintIndices = false;
  75179. _this._caps.fragmentDepthSupported = false;
  75180. _this._caps.highPrecisionShaderSupported = true;
  75181. _this._caps.colorBufferFloat = false;
  75182. _this._caps.textureFloat = false;
  75183. _this._caps.textureFloatLinearFiltering = false;
  75184. _this._caps.textureFloatRender = false;
  75185. _this._caps.textureHalfFloat = false;
  75186. _this._caps.textureHalfFloatLinearFiltering = false;
  75187. _this._caps.textureHalfFloatRender = false;
  75188. _this._caps.textureLOD = false;
  75189. _this._caps.drawBuffersExtension = false;
  75190. _this._caps.depthTextureExtension = false;
  75191. _this._caps.vertexArrayObject = false;
  75192. _this._caps.instancedArrays = false;
  75193. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  75194. // Wrappers
  75195. if (typeof URL === "undefined") {
  75196. URL = {
  75197. createObjectURL: function () { },
  75198. revokeObjectURL: function () { }
  75199. };
  75200. }
  75201. if (typeof Blob === "undefined") {
  75202. Blob = function () { };
  75203. }
  75204. return _this;
  75205. }
  75206. NullEngine.prototype.createVertexBuffer = function (vertices) {
  75207. return {
  75208. capacity: 0,
  75209. references: 1,
  75210. is32Bits: false
  75211. };
  75212. };
  75213. NullEngine.prototype.createIndexBuffer = function (indices) {
  75214. return {
  75215. capacity: 0,
  75216. references: 1,
  75217. is32Bits: false
  75218. };
  75219. };
  75220. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  75221. if (stencil === void 0) { stencil = false; }
  75222. };
  75223. NullEngine.prototype.getRenderWidth = function (useScreen) {
  75224. if (useScreen === void 0) { useScreen = false; }
  75225. if (!useScreen && this._currentRenderTarget) {
  75226. return this._currentRenderTarget.width;
  75227. }
  75228. return this._options.renderWidth;
  75229. };
  75230. NullEngine.prototype.getRenderHeight = function (useScreen) {
  75231. if (useScreen === void 0) { useScreen = false; }
  75232. if (!useScreen && this._currentRenderTarget) {
  75233. return this._currentRenderTarget.height;
  75234. }
  75235. return this._options.renderHeight;
  75236. };
  75237. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  75238. this._cachedViewport = viewport;
  75239. };
  75240. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  75241. return {
  75242. transformFeedback: null,
  75243. __SPECTOR_rebuildProgram: null
  75244. };
  75245. };
  75246. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  75247. return [];
  75248. };
  75249. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  75250. return [];
  75251. };
  75252. NullEngine.prototype.bindSamplers = function (effect) {
  75253. this._currentEffect = null;
  75254. };
  75255. NullEngine.prototype.enableEffect = function (effect) {
  75256. this._currentEffect = effect;
  75257. if (effect.onBind) {
  75258. effect.onBind(effect);
  75259. }
  75260. effect.onBindObservable.notifyObservers(effect);
  75261. };
  75262. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  75263. if (zOffset === void 0) { zOffset = 0; }
  75264. if (reverseSide === void 0) { reverseSide = false; }
  75265. };
  75266. NullEngine.prototype.setIntArray = function (uniform, array) {
  75267. };
  75268. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  75269. };
  75270. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  75271. };
  75272. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  75273. };
  75274. NullEngine.prototype.setFloatArray = function (uniform, array) {
  75275. };
  75276. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  75277. };
  75278. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  75279. };
  75280. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  75281. };
  75282. NullEngine.prototype.setArray = function (uniform, array) {
  75283. };
  75284. NullEngine.prototype.setArray2 = function (uniform, array) {
  75285. };
  75286. NullEngine.prototype.setArray3 = function (uniform, array) {
  75287. };
  75288. NullEngine.prototype.setArray4 = function (uniform, array) {
  75289. };
  75290. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  75291. };
  75292. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  75293. };
  75294. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  75295. };
  75296. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  75297. };
  75298. NullEngine.prototype.setFloat = function (uniform, value) {
  75299. };
  75300. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  75301. };
  75302. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  75303. };
  75304. NullEngine.prototype.setBool = function (uniform, bool) {
  75305. };
  75306. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  75307. };
  75308. NullEngine.prototype.setColor3 = function (uniform, color3) {
  75309. };
  75310. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  75311. };
  75312. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  75313. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  75314. if (this._alphaMode === mode) {
  75315. return;
  75316. }
  75317. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  75318. if (!noDepthWriteChange) {
  75319. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  75320. }
  75321. this._alphaMode = mode;
  75322. };
  75323. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  75324. };
  75325. NullEngine.prototype.wipeCaches = function (bruteForce) {
  75326. if (this.preventCacheWipeBetweenFrames) {
  75327. return;
  75328. }
  75329. this.resetTextureCache();
  75330. this._currentEffect = null;
  75331. if (bruteForce) {
  75332. this._currentProgram = null;
  75333. this._stencilState.reset();
  75334. this._depthCullingState.reset();
  75335. this.setDepthFunctionToLessOrEqual();
  75336. this._alphaState.reset();
  75337. }
  75338. this._cachedVertexBuffers = null;
  75339. this._cachedIndexBuffer = null;
  75340. this._cachedEffectForVertexBuffers = null;
  75341. };
  75342. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  75343. };
  75344. NullEngine.prototype._createTexture = function () {
  75345. return {};
  75346. };
  75347. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  75348. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  75349. if (onLoad === void 0) { onLoad = null; }
  75350. if (onError === void 0) { onError = null; }
  75351. if (buffer === void 0) { buffer = null; }
  75352. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  75353. var url = String(urlArg);
  75354. texture.url = url;
  75355. texture.generateMipMaps = !noMipmap;
  75356. texture.samplingMode = samplingMode;
  75357. texture.invertY = invertY;
  75358. texture.baseWidth = this._options.textureSize;
  75359. texture.baseHeight = this._options.textureSize;
  75360. texture.width = this._options.textureSize;
  75361. texture.height = this._options.textureSize;
  75362. if (format) {
  75363. texture.format = format;
  75364. }
  75365. texture.isReady = true;
  75366. if (onLoad) {
  75367. onLoad();
  75368. }
  75369. return texture;
  75370. };
  75371. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  75372. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  75373. if (options !== undefined && typeof options === "object") {
  75374. fullOptions.generateMipMaps = options.generateMipMaps;
  75375. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  75376. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  75377. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  75378. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  75379. }
  75380. else {
  75381. fullOptions.generateMipMaps = options;
  75382. fullOptions.generateDepthBuffer = true;
  75383. fullOptions.generateStencilBuffer = false;
  75384. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75385. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  75386. }
  75387. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  75388. var width = size.width || size;
  75389. var height = size.height || size;
  75390. texture._depthStencilBuffer = {};
  75391. texture._framebuffer = {};
  75392. texture.baseWidth = width;
  75393. texture.baseHeight = height;
  75394. texture.width = width;
  75395. texture.height = height;
  75396. texture.isReady = true;
  75397. texture.samples = 1;
  75398. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  75399. texture.samplingMode = fullOptions.samplingMode;
  75400. texture.type = fullOptions.type;
  75401. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  75402. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  75403. return texture;
  75404. };
  75405. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  75406. texture.samplingMode = samplingMode;
  75407. };
  75408. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  75409. if (this._currentRenderTarget) {
  75410. this.unBindFramebuffer(this._currentRenderTarget);
  75411. }
  75412. this._currentRenderTarget = texture;
  75413. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  75414. if (this._cachedViewport && !forceFullscreenViewport) {
  75415. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  75416. }
  75417. };
  75418. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  75419. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  75420. this._currentRenderTarget = null;
  75421. if (onBeforeUnbind) {
  75422. if (texture._MSAAFramebuffer) {
  75423. this._currentFramebuffer = texture._framebuffer;
  75424. }
  75425. onBeforeUnbind();
  75426. }
  75427. this._currentFramebuffer = null;
  75428. };
  75429. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  75430. var vbo = {
  75431. capacity: 1,
  75432. references: 1,
  75433. is32Bits: false
  75434. };
  75435. return vbo;
  75436. };
  75437. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  75438. if (offset === void 0) { offset = 0; }
  75439. };
  75440. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  75441. };
  75442. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  75443. if (this._activeTexturesCache[this._activeTextureChannel] !== texture) {
  75444. this._activeTexturesCache[this._activeTextureChannel] = texture;
  75445. }
  75446. };
  75447. NullEngine.prototype._bindTexture = function (channel, texture) {
  75448. if (channel < 0) {
  75449. return;
  75450. }
  75451. this._bindTextureDirectly(0, texture);
  75452. };
  75453. NullEngine.prototype._releaseBuffer = function (buffer) {
  75454. buffer.references--;
  75455. if (buffer.references === 0) {
  75456. return true;
  75457. }
  75458. return false;
  75459. };
  75460. return NullEngine;
  75461. }(BABYLON.Engine));
  75462. BABYLON.NullEngine = NullEngine;
  75463. })(BABYLON || (BABYLON = {}));
  75464. //# sourceMappingURL=babylon.nullEngine.js.map
  75465. var BABYLON;
  75466. (function (BABYLON) {
  75467. /**
  75468. * This class can be used to get instrumentation data from a Babylon engine
  75469. */
  75470. var EngineInstrumentation = /** @class */ (function () {
  75471. function EngineInstrumentation(engine) {
  75472. this.engine = engine;
  75473. this._captureGPUFrameTime = false;
  75474. this._gpuFrameTime = new BABYLON.PerfCounter();
  75475. this._captureShaderCompilationTime = false;
  75476. this._shaderCompilationTime = new BABYLON.PerfCounter();
  75477. // Observers
  75478. this._onBeginFrameObserver = null;
  75479. this._onEndFrameObserver = null;
  75480. this._onBeforeShaderCompilationObserver = null;
  75481. this._onAfterShaderCompilationObserver = null;
  75482. }
  75483. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  75484. // Properties
  75485. /**
  75486. * Gets the perf counter used for GPU frame time
  75487. */
  75488. get: function () {
  75489. return this._gpuFrameTime;
  75490. },
  75491. enumerable: true,
  75492. configurable: true
  75493. });
  75494. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  75495. /**
  75496. * Gets the GPU frame time capture status
  75497. */
  75498. get: function () {
  75499. return this._captureGPUFrameTime;
  75500. },
  75501. /**
  75502. * Enable or disable the GPU frame time capture
  75503. */
  75504. set: function (value) {
  75505. var _this = this;
  75506. if (value === this._captureGPUFrameTime) {
  75507. return;
  75508. }
  75509. this._captureGPUFrameTime = value;
  75510. if (value) {
  75511. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  75512. if (!_this._gpuFrameTimeToken) {
  75513. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  75514. }
  75515. });
  75516. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  75517. if (!_this._gpuFrameTimeToken) {
  75518. return;
  75519. }
  75520. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  75521. if (time > -1) {
  75522. _this._gpuFrameTimeToken = null;
  75523. _this._gpuFrameTime.fetchNewFrame();
  75524. _this._gpuFrameTime.addCount(time, true);
  75525. }
  75526. });
  75527. }
  75528. else {
  75529. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  75530. this._onBeginFrameObserver = null;
  75531. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  75532. this._onEndFrameObserver = null;
  75533. }
  75534. },
  75535. enumerable: true,
  75536. configurable: true
  75537. });
  75538. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  75539. /**
  75540. * Gets the perf counter used for shader compilation time
  75541. */
  75542. get: function () {
  75543. return this._shaderCompilationTime;
  75544. },
  75545. enumerable: true,
  75546. configurable: true
  75547. });
  75548. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  75549. /**
  75550. * Gets the shader compilation time capture status
  75551. */
  75552. get: function () {
  75553. return this._captureShaderCompilationTime;
  75554. },
  75555. /**
  75556. * Enable or disable the shader compilation time capture
  75557. */
  75558. set: function (value) {
  75559. var _this = this;
  75560. if (value === this._captureShaderCompilationTime) {
  75561. return;
  75562. }
  75563. this._captureShaderCompilationTime = value;
  75564. if (value) {
  75565. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  75566. _this._shaderCompilationTime.fetchNewFrame();
  75567. _this._shaderCompilationTime.beginMonitoring();
  75568. });
  75569. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  75570. _this._shaderCompilationTime.endMonitoring();
  75571. });
  75572. }
  75573. else {
  75574. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  75575. this._onBeforeShaderCompilationObserver = null;
  75576. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  75577. this._onAfterShaderCompilationObserver = null;
  75578. }
  75579. },
  75580. enumerable: true,
  75581. configurable: true
  75582. });
  75583. EngineInstrumentation.prototype.dispose = function () {
  75584. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  75585. this._onBeginFrameObserver = null;
  75586. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  75587. this._onEndFrameObserver = null;
  75588. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  75589. this._onBeforeShaderCompilationObserver = null;
  75590. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  75591. this._onAfterShaderCompilationObserver = null;
  75592. this.engine = null;
  75593. };
  75594. return EngineInstrumentation;
  75595. }());
  75596. BABYLON.EngineInstrumentation = EngineInstrumentation;
  75597. })(BABYLON || (BABYLON = {}));
  75598. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  75599. var BABYLON;
  75600. (function (BABYLON) {
  75601. /**
  75602. * This class can be used to get instrumentation data from a Babylon engine
  75603. */
  75604. var SceneInstrumentation = /** @class */ (function () {
  75605. function SceneInstrumentation(scene) {
  75606. var _this = this;
  75607. this.scene = scene;
  75608. this._captureActiveMeshesEvaluationTime = false;
  75609. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  75610. this._captureRenderTargetsRenderTime = false;
  75611. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  75612. this._captureFrameTime = false;
  75613. this._frameTime = new BABYLON.PerfCounter();
  75614. this._captureRenderTime = false;
  75615. this._renderTime = new BABYLON.PerfCounter();
  75616. this._captureInterFrameTime = false;
  75617. this._interFrameTime = new BABYLON.PerfCounter();
  75618. this._captureParticlesRenderTime = false;
  75619. this._particlesRenderTime = new BABYLON.PerfCounter();
  75620. this._captureSpritesRenderTime = false;
  75621. this._spritesRenderTime = new BABYLON.PerfCounter();
  75622. this._capturePhysicsTime = false;
  75623. this._physicsTime = new BABYLON.PerfCounter();
  75624. this._captureAnimationsTime = false;
  75625. this._animationsTime = new BABYLON.PerfCounter();
  75626. // Observers
  75627. this._onBeforeActiveMeshesEvaluationObserver = null;
  75628. this._onAfterActiveMeshesEvaluationObserver = null;
  75629. this._onBeforeRenderTargetsRenderObserver = null;
  75630. this._onAfterRenderTargetsRenderObserver = null;
  75631. this._onAfterRenderObserver = null;
  75632. this._onBeforeDrawPhaseObserver = null;
  75633. this._onAfterDrawPhaseObserver = null;
  75634. this._onBeforeAnimationsObserver = null;
  75635. this._onBeforeParticlesRenderingObserver = null;
  75636. this._onAfterParticlesRenderingObserver = null;
  75637. this._onBeforeSpritesRenderingObserver = null;
  75638. this._onAfterSpritesRenderingObserver = null;
  75639. this._onBeforePhysicsObserver = null;
  75640. this._onAfterPhysicsObserver = null;
  75641. this._onAfterAnimationsObserver = null;
  75642. // Before render
  75643. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  75644. if (_this._captureActiveMeshesEvaluationTime) {
  75645. _this._activeMeshesEvaluationTime.fetchNewFrame();
  75646. }
  75647. if (_this._captureRenderTargetsRenderTime) {
  75648. _this._renderTargetsRenderTime.fetchNewFrame();
  75649. }
  75650. if (_this._captureFrameTime) {
  75651. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  75652. _this._frameTime.beginMonitoring();
  75653. }
  75654. if (_this._captureInterFrameTime) {
  75655. _this._interFrameTime.endMonitoring();
  75656. }
  75657. if (_this._captureParticlesRenderTime) {
  75658. _this._particlesRenderTime.fetchNewFrame();
  75659. }
  75660. if (_this._captureSpritesRenderTime) {
  75661. _this._spritesRenderTime.fetchNewFrame();
  75662. }
  75663. if (_this._captureAnimationsTime) {
  75664. _this._animationsTime.beginMonitoring();
  75665. }
  75666. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  75667. });
  75668. // After render
  75669. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  75670. if (_this._captureFrameTime) {
  75671. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  75672. _this._frameTime.endMonitoring();
  75673. }
  75674. if (_this._captureRenderTime) {
  75675. _this._renderTime.endMonitoring(false);
  75676. }
  75677. if (_this._captureInterFrameTime) {
  75678. _this._interFrameTime.beginMonitoring();
  75679. }
  75680. });
  75681. }
  75682. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  75683. // Properties
  75684. /**
  75685. * Gets the perf counter used for active meshes evaluation time
  75686. */
  75687. get: function () {
  75688. return this._activeMeshesEvaluationTime;
  75689. },
  75690. enumerable: true,
  75691. configurable: true
  75692. });
  75693. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  75694. /**
  75695. * Gets the active meshes evaluation time capture status
  75696. */
  75697. get: function () {
  75698. return this._captureActiveMeshesEvaluationTime;
  75699. },
  75700. /**
  75701. * Enable or disable the active meshes evaluation time capture
  75702. */
  75703. set: function (value) {
  75704. var _this = this;
  75705. if (value === this._captureActiveMeshesEvaluationTime) {
  75706. return;
  75707. }
  75708. this._captureActiveMeshesEvaluationTime = value;
  75709. if (value) {
  75710. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  75711. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  75712. _this._activeMeshesEvaluationTime.beginMonitoring();
  75713. });
  75714. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  75715. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  75716. _this._activeMeshesEvaluationTime.endMonitoring();
  75717. });
  75718. }
  75719. else {
  75720. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  75721. this._onBeforeActiveMeshesEvaluationObserver = null;
  75722. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  75723. this._onAfterActiveMeshesEvaluationObserver = null;
  75724. }
  75725. },
  75726. enumerable: true,
  75727. configurable: true
  75728. });
  75729. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  75730. /**
  75731. * Gets the perf counter used for render targets render time
  75732. */
  75733. get: function () {
  75734. return this._renderTargetsRenderTime;
  75735. },
  75736. enumerable: true,
  75737. configurable: true
  75738. });
  75739. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  75740. /**
  75741. * Gets the render targets render time capture status
  75742. */
  75743. get: function () {
  75744. return this._captureRenderTargetsRenderTime;
  75745. },
  75746. /**
  75747. * Enable or disable the render targets render time capture
  75748. */
  75749. set: function (value) {
  75750. var _this = this;
  75751. if (value === this._captureRenderTargetsRenderTime) {
  75752. return;
  75753. }
  75754. this._captureRenderTargetsRenderTime = value;
  75755. if (value) {
  75756. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  75757. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  75758. _this._renderTargetsRenderTime.beginMonitoring();
  75759. });
  75760. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  75761. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  75762. _this._renderTargetsRenderTime.endMonitoring(false);
  75763. });
  75764. }
  75765. else {
  75766. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  75767. this._onBeforeRenderTargetsRenderObserver = null;
  75768. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  75769. this._onAfterRenderTargetsRenderObserver = null;
  75770. }
  75771. },
  75772. enumerable: true,
  75773. configurable: true
  75774. });
  75775. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  75776. /**
  75777. * Gets the perf counter used for particles render time
  75778. */
  75779. get: function () {
  75780. return this._particlesRenderTime;
  75781. },
  75782. enumerable: true,
  75783. configurable: true
  75784. });
  75785. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  75786. /**
  75787. * Gets the particles render time capture status
  75788. */
  75789. get: function () {
  75790. return this._captureParticlesRenderTime;
  75791. },
  75792. /**
  75793. * Enable or disable the particles render time capture
  75794. */
  75795. set: function (value) {
  75796. var _this = this;
  75797. if (value === this._captureParticlesRenderTime) {
  75798. return;
  75799. }
  75800. this._captureParticlesRenderTime = value;
  75801. if (value) {
  75802. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  75803. BABYLON.Tools.StartPerformanceCounter("Particles");
  75804. _this._particlesRenderTime.beginMonitoring();
  75805. });
  75806. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  75807. BABYLON.Tools.EndPerformanceCounter("Particles");
  75808. _this._particlesRenderTime.endMonitoring(false);
  75809. });
  75810. }
  75811. else {
  75812. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  75813. this._onBeforeParticlesRenderingObserver = null;
  75814. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  75815. this._onAfterParticlesRenderingObserver = null;
  75816. }
  75817. },
  75818. enumerable: true,
  75819. configurable: true
  75820. });
  75821. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  75822. /**
  75823. * Gets the perf counter used for sprites render time
  75824. */
  75825. get: function () {
  75826. return this._spritesRenderTime;
  75827. },
  75828. enumerable: true,
  75829. configurable: true
  75830. });
  75831. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  75832. /**
  75833. * Gets the sprites render time capture status
  75834. */
  75835. get: function () {
  75836. return this._captureSpritesRenderTime;
  75837. },
  75838. /**
  75839. * Enable or disable the sprites render time capture
  75840. */
  75841. set: function (value) {
  75842. var _this = this;
  75843. if (value === this._captureSpritesRenderTime) {
  75844. return;
  75845. }
  75846. this._captureSpritesRenderTime = value;
  75847. if (value) {
  75848. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  75849. BABYLON.Tools.StartPerformanceCounter("Sprites");
  75850. _this._spritesRenderTime.beginMonitoring();
  75851. });
  75852. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  75853. BABYLON.Tools.EndPerformanceCounter("Sprites");
  75854. _this._spritesRenderTime.endMonitoring(false);
  75855. });
  75856. }
  75857. else {
  75858. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  75859. this._onBeforeSpritesRenderingObserver = null;
  75860. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  75861. this._onAfterSpritesRenderingObserver = null;
  75862. }
  75863. },
  75864. enumerable: true,
  75865. configurable: true
  75866. });
  75867. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  75868. /**
  75869. * Gets the perf counter used for physics time
  75870. */
  75871. get: function () {
  75872. return this._physicsTime;
  75873. },
  75874. enumerable: true,
  75875. configurable: true
  75876. });
  75877. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  75878. /**
  75879. * Gets the physics time capture status
  75880. */
  75881. get: function () {
  75882. return this._capturePhysicsTime;
  75883. },
  75884. /**
  75885. * Enable or disable the physics time capture
  75886. */
  75887. set: function (value) {
  75888. var _this = this;
  75889. if (value === this._capturePhysicsTime) {
  75890. return;
  75891. }
  75892. this._capturePhysicsTime = value;
  75893. if (value) {
  75894. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  75895. BABYLON.Tools.StartPerformanceCounter("Physics");
  75896. _this._physicsTime.beginMonitoring();
  75897. });
  75898. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  75899. BABYLON.Tools.EndPerformanceCounter("Physics");
  75900. _this._physicsTime.endMonitoring();
  75901. });
  75902. }
  75903. else {
  75904. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  75905. this._onBeforePhysicsObserver = null;
  75906. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  75907. this._onAfterPhysicsObserver = null;
  75908. }
  75909. },
  75910. enumerable: true,
  75911. configurable: true
  75912. });
  75913. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  75914. /**
  75915. * Gets the perf counter used for animations time
  75916. */
  75917. get: function () {
  75918. return this._animationsTime;
  75919. },
  75920. enumerable: true,
  75921. configurable: true
  75922. });
  75923. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  75924. /**
  75925. * Gets the animations time capture status
  75926. */
  75927. get: function () {
  75928. return this._captureAnimationsTime;
  75929. },
  75930. /**
  75931. * Enable or disable the animations time capture
  75932. */
  75933. set: function (value) {
  75934. var _this = this;
  75935. if (value === this._captureAnimationsTime) {
  75936. return;
  75937. }
  75938. this._captureAnimationsTime = value;
  75939. if (value) {
  75940. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  75941. _this._animationsTime.endMonitoring();
  75942. });
  75943. }
  75944. else {
  75945. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  75946. this._onAfterAnimationsObserver = null;
  75947. }
  75948. },
  75949. enumerable: true,
  75950. configurable: true
  75951. });
  75952. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  75953. /**
  75954. * Gets the perf counter used for frame time capture
  75955. */
  75956. get: function () {
  75957. return this._frameTime;
  75958. },
  75959. enumerable: true,
  75960. configurable: true
  75961. });
  75962. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  75963. /**
  75964. * Gets the frame time capture status
  75965. */
  75966. get: function () {
  75967. return this._captureFrameTime;
  75968. },
  75969. /**
  75970. * Enable or disable the frame time capture
  75971. */
  75972. set: function (value) {
  75973. this._captureFrameTime = value;
  75974. },
  75975. enumerable: true,
  75976. configurable: true
  75977. });
  75978. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  75979. /**
  75980. * Gets the perf counter used for inter-frames time capture
  75981. */
  75982. get: function () {
  75983. return this._interFrameTime;
  75984. },
  75985. enumerable: true,
  75986. configurable: true
  75987. });
  75988. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  75989. /**
  75990. * Gets the inter-frames time capture status
  75991. */
  75992. get: function () {
  75993. return this._captureInterFrameTime;
  75994. },
  75995. /**
  75996. * Enable or disable the inter-frames time capture
  75997. */
  75998. set: function (value) {
  75999. this._captureInterFrameTime = value;
  76000. },
  76001. enumerable: true,
  76002. configurable: true
  76003. });
  76004. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  76005. /**
  76006. * Gets the perf counter used for render time capture
  76007. */
  76008. get: function () {
  76009. return this._renderTime;
  76010. },
  76011. enumerable: true,
  76012. configurable: true
  76013. });
  76014. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  76015. /**
  76016. * Gets the render time capture status
  76017. */
  76018. get: function () {
  76019. return this._captureRenderTime;
  76020. },
  76021. /**
  76022. * Enable or disable the render time capture
  76023. */
  76024. set: function (value) {
  76025. var _this = this;
  76026. if (value === this._captureRenderTime) {
  76027. return;
  76028. }
  76029. this._captureRenderTime = value;
  76030. if (value) {
  76031. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  76032. _this._renderTime.beginMonitoring();
  76033. BABYLON.Tools.StartPerformanceCounter("Main render");
  76034. });
  76035. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  76036. _this._renderTime.endMonitoring(false);
  76037. BABYLON.Tools.EndPerformanceCounter("Main render");
  76038. });
  76039. }
  76040. else {
  76041. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  76042. this._onBeforeDrawPhaseObserver = null;
  76043. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  76044. this._onAfterDrawPhaseObserver = null;
  76045. }
  76046. },
  76047. enumerable: true,
  76048. configurable: true
  76049. });
  76050. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  76051. /**
  76052. * Gets the perf counter used for frame time capture
  76053. */
  76054. get: function () {
  76055. return this.scene.getEngine()._drawCalls;
  76056. },
  76057. enumerable: true,
  76058. configurable: true
  76059. });
  76060. SceneInstrumentation.prototype.dispose = function () {
  76061. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  76062. this._onAfterRenderObserver = null;
  76063. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  76064. this._onBeforeActiveMeshesEvaluationObserver = null;
  76065. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  76066. this._onAfterActiveMeshesEvaluationObserver = null;
  76067. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  76068. this._onBeforeRenderTargetsRenderObserver = null;
  76069. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  76070. this._onAfterRenderTargetsRenderObserver = null;
  76071. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  76072. this._onBeforeAnimationsObserver = null;
  76073. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  76074. this._onBeforeParticlesRenderingObserver = null;
  76075. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  76076. this._onAfterParticlesRenderingObserver = null;
  76077. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  76078. this._onBeforeSpritesRenderingObserver = null;
  76079. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  76080. this._onAfterSpritesRenderingObserver = null;
  76081. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  76082. this._onBeforeDrawPhaseObserver = null;
  76083. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  76084. this._onAfterDrawPhaseObserver = null;
  76085. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  76086. this._onBeforePhysicsObserver = null;
  76087. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  76088. this._onAfterPhysicsObserver = null;
  76089. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  76090. this._onAfterAnimationsObserver = null;
  76091. this.scene = null;
  76092. };
  76093. return SceneInstrumentation;
  76094. }());
  76095. BABYLON.SceneInstrumentation = SceneInstrumentation;
  76096. })(BABYLON || (BABYLON = {}));
  76097. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  76098. var BABYLON;
  76099. (function (BABYLON) {
  76100. var _TimeToken = /** @class */ (function () {
  76101. function _TimeToken() {
  76102. this._timeElapsedQueryEnded = false;
  76103. }
  76104. return _TimeToken;
  76105. }());
  76106. BABYLON._TimeToken = _TimeToken;
  76107. })(BABYLON || (BABYLON = {}));
  76108. //# sourceMappingURL=babylon.timeToken.js.map
  76109. var BABYLON;
  76110. (function (BABYLON) {
  76111. /**
  76112. * Background material defines definition.
  76113. */
  76114. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  76115. __extends(BackgroundMaterialDefines, _super);
  76116. /**
  76117. * Constructor of the defines.
  76118. */
  76119. function BackgroundMaterialDefines() {
  76120. var _this = _super.call(this) || this;
  76121. /**
  76122. * True if the diffuse texture is in use.
  76123. */
  76124. _this.DIFFUSE = false;
  76125. /**
  76126. * The direct UV channel to use.
  76127. */
  76128. _this.DIFFUSEDIRECTUV = 0;
  76129. /**
  76130. * True if the diffuse texture is in gamma space.
  76131. */
  76132. _this.GAMMADIFFUSE = false;
  76133. /**
  76134. * True if the diffuse texture has opacity in the alpha channel.
  76135. */
  76136. _this.DIFFUSEHASALPHA = false;
  76137. /**
  76138. * True if you want the material to fade to transparent at grazing angle.
  76139. */
  76140. _this.OPACITYFRESNEL = false;
  76141. /**
  76142. * True if an extra blur needs to be added in the reflection.
  76143. */
  76144. _this.REFLECTIONBLUR = false;
  76145. /**
  76146. * True if you want the material to fade to reflection at grazing angle.
  76147. */
  76148. _this.REFLECTIONFRESNEL = false;
  76149. /**
  76150. * True if you want the material to falloff as far as you move away from the scene center.
  76151. */
  76152. _this.REFLECTIONFALLOFF = false;
  76153. /**
  76154. * False if the current Webgl implementation does not support the texture lod extension.
  76155. */
  76156. _this.TEXTURELODSUPPORT = false;
  76157. /**
  76158. * True to ensure the data are premultiplied.
  76159. */
  76160. _this.PREMULTIPLYALPHA = false;
  76161. /**
  76162. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  76163. */
  76164. _this.USERGBCOLOR = false;
  76165. /**
  76166. * True to add noise in order to reduce the banding effect.
  76167. */
  76168. _this.NOISE = false;
  76169. // Image Processing Configuration.
  76170. _this.IMAGEPROCESSING = false;
  76171. _this.VIGNETTE = false;
  76172. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  76173. _this.VIGNETTEBLENDMODEOPAQUE = false;
  76174. _this.TONEMAPPING = false;
  76175. _this.CONTRAST = false;
  76176. _this.COLORCURVES = false;
  76177. _this.COLORGRADING = false;
  76178. _this.COLORGRADING3D = false;
  76179. _this.SAMPLER3DGREENDEPTH = false;
  76180. _this.SAMPLER3DBGRMAP = false;
  76181. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  76182. _this.EXPOSURE = false;
  76183. // Reflection.
  76184. _this.REFLECTION = false;
  76185. _this.REFLECTIONMAP_3D = false;
  76186. _this.REFLECTIONMAP_SPHERICAL = false;
  76187. _this.REFLECTIONMAP_PLANAR = false;
  76188. _this.REFLECTIONMAP_CUBIC = false;
  76189. _this.REFLECTIONMAP_PROJECTION = false;
  76190. _this.REFLECTIONMAP_SKYBOX = false;
  76191. _this.REFLECTIONMAP_EXPLICIT = false;
  76192. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  76193. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  76194. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  76195. _this.INVERTCUBICMAP = false;
  76196. _this.REFLECTIONMAP_OPPOSITEZ = false;
  76197. _this.LODINREFLECTIONALPHA = false;
  76198. _this.GAMMAREFLECTION = false;
  76199. // Default BJS.
  76200. _this.MAINUV1 = false;
  76201. _this.MAINUV2 = false;
  76202. _this.UV1 = false;
  76203. _this.UV2 = false;
  76204. _this.CLIPPLANE = false;
  76205. _this.POINTSIZE = false;
  76206. _this.FOG = false;
  76207. _this.NORMAL = false;
  76208. _this.NUM_BONE_INFLUENCERS = 0;
  76209. _this.BonesPerMesh = 0;
  76210. _this.INSTANCES = false;
  76211. _this.SHADOWFLOAT = false;
  76212. _this.rebuild();
  76213. return _this;
  76214. }
  76215. return BackgroundMaterialDefines;
  76216. }(BABYLON.MaterialDefines));
  76217. /**
  76218. * Background material used to create an efficient environement around your scene.
  76219. */
  76220. var BackgroundMaterial = /** @class */ (function (_super) {
  76221. __extends(BackgroundMaterial, _super);
  76222. /**
  76223. * constructor
  76224. * @param name The name of the material
  76225. * @param scene The scene to add the material to
  76226. */
  76227. function BackgroundMaterial(name, scene) {
  76228. var _this = _super.call(this, name, scene) || this;
  76229. _this.primaryColor = BABYLON.Color3.White();
  76230. _this.primaryLevel = 1;
  76231. _this.secondaryColor = BABYLON.Color3.Gray();
  76232. _this.secondaryLevel = 1;
  76233. _this.tertiaryColor = BABYLON.Color3.Black();
  76234. _this.tertiaryLevel = 1;
  76235. _this.reflectionTexture = null;
  76236. _this.reflectionBlur = 0;
  76237. _this.diffuseTexture = null;
  76238. /**
  76239. * Specify the list of lights casting shadow on the material.
  76240. * All scene shadow lights will be included if null.
  76241. */
  76242. _this._shadowLights = null;
  76243. _this.shadowLights = null;
  76244. _this.shadowBlurScale = 1;
  76245. _this.shadowLevel = 0;
  76246. _this.sceneCenter = BABYLON.Vector3.Zero();
  76247. _this.opacityFresnel = true;
  76248. _this.reflectionFresnel = false;
  76249. _this.reflectionFalloffDistance = 0.0;
  76250. _this.reflectionAmount = 1.0;
  76251. _this.reflectionReflectance0 = 0.05;
  76252. _this.reflectionReflectance90 = 0.5;
  76253. _this.useRGBColor = true;
  76254. _this.enableNoise = false;
  76255. /**
  76256. * Number of Simultaneous lights allowed on the material.
  76257. */
  76258. _this._maxSimultaneousLights = 4;
  76259. _this.maxSimultaneousLights = 4;
  76260. /**
  76261. * Keep track of the image processing observer to allow dispose and replace.
  76262. */
  76263. _this._imageProcessingObserver = null;
  76264. // Temp values kept as cache in the material.
  76265. _this._renderTargets = new BABYLON.SmartArray(16);
  76266. _this._reflectionControls = BABYLON.Vector4.Zero();
  76267. // Setup the default processing configuration to the scene.
  76268. _this._attachImageProcessingConfiguration(null);
  76269. _this.getRenderTargetTextures = function () {
  76270. _this._renderTargets.reset();
  76271. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  76272. _this._renderTargets.push(_this._diffuseTexture);
  76273. }
  76274. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  76275. _this._renderTargets.push(_this._reflectionTexture);
  76276. }
  76277. return _this._renderTargets;
  76278. };
  76279. return _this;
  76280. }
  76281. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  76282. /**
  76283. * Sets the reflection reflectance fresnel values according to the default standard
  76284. * empirically know to work well :-)
  76285. */
  76286. set: function (value) {
  76287. var reflectionWeight = value;
  76288. if (reflectionWeight < 0.5) {
  76289. reflectionWeight = reflectionWeight * 2.0;
  76290. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  76291. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  76292. }
  76293. else {
  76294. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  76295. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  76296. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  76297. }
  76298. },
  76299. enumerable: true,
  76300. configurable: true
  76301. });
  76302. /**
  76303. * Attaches a new image processing configuration to the PBR Material.
  76304. * @param configuration (if null the scene configuration will be use)
  76305. */
  76306. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  76307. var _this = this;
  76308. if (configuration === this._imageProcessingConfiguration) {
  76309. return;
  76310. }
  76311. // Detaches observer.
  76312. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76313. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76314. }
  76315. // Pick the scene configuration if needed.
  76316. if (!configuration) {
  76317. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  76318. }
  76319. else {
  76320. this._imageProcessingConfiguration = configuration;
  76321. }
  76322. // Attaches observer.
  76323. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76324. _this._markAllSubMeshesAsImageProcessingDirty();
  76325. });
  76326. };
  76327. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  76328. /**
  76329. * Gets the image processing configuration used either in this material.
  76330. */
  76331. get: function () {
  76332. return this._imageProcessingConfiguration;
  76333. },
  76334. /**
  76335. * Sets the Default image processing configuration used either in the this material.
  76336. *
  76337. * If sets to null, the scene one is in use.
  76338. */
  76339. set: function (value) {
  76340. this._attachImageProcessingConfiguration(value);
  76341. // Ensure the effect will be rebuilt.
  76342. this._markAllSubMeshesAsTexturesDirty();
  76343. },
  76344. enumerable: true,
  76345. configurable: true
  76346. });
  76347. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  76348. /**
  76349. * Gets wether the color curves effect is enabled.
  76350. */
  76351. get: function () {
  76352. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76353. },
  76354. /**
  76355. * Sets wether the color curves effect is enabled.
  76356. */
  76357. set: function (value) {
  76358. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76359. },
  76360. enumerable: true,
  76361. configurable: true
  76362. });
  76363. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  76364. /**
  76365. * Gets wether the color grading effect is enabled.
  76366. */
  76367. get: function () {
  76368. return this.imageProcessingConfiguration.colorGradingEnabled;
  76369. },
  76370. /**
  76371. * Gets wether the color grading effect is enabled.
  76372. */
  76373. set: function (value) {
  76374. this.imageProcessingConfiguration.colorGradingEnabled = value;
  76375. },
  76376. enumerable: true,
  76377. configurable: true
  76378. });
  76379. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  76380. /**
  76381. * Gets wether tonemapping is enabled or not.
  76382. */
  76383. get: function () {
  76384. return this._imageProcessingConfiguration.toneMappingEnabled;
  76385. },
  76386. /**
  76387. * Sets wether tonemapping is enabled or not
  76388. */
  76389. set: function (value) {
  76390. this._imageProcessingConfiguration.toneMappingEnabled = value;
  76391. },
  76392. enumerable: true,
  76393. configurable: true
  76394. });
  76395. ;
  76396. ;
  76397. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  76398. /**
  76399. * The camera exposure used on this material.
  76400. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  76401. * This corresponds to a photographic exposure.
  76402. */
  76403. get: function () {
  76404. return this._imageProcessingConfiguration.exposure;
  76405. },
  76406. /**
  76407. * The camera exposure used on this material.
  76408. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  76409. * This corresponds to a photographic exposure.
  76410. */
  76411. set: function (value) {
  76412. this._imageProcessingConfiguration.exposure = value;
  76413. },
  76414. enumerable: true,
  76415. configurable: true
  76416. });
  76417. ;
  76418. ;
  76419. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  76420. /**
  76421. * Gets The camera contrast used on this material.
  76422. */
  76423. get: function () {
  76424. return this._imageProcessingConfiguration.contrast;
  76425. },
  76426. /**
  76427. * Sets The camera contrast used on this material.
  76428. */
  76429. set: function (value) {
  76430. this._imageProcessingConfiguration.contrast = value;
  76431. },
  76432. enumerable: true,
  76433. configurable: true
  76434. });
  76435. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  76436. /**
  76437. * Gets the Color Grading 2D Lookup Texture.
  76438. */
  76439. get: function () {
  76440. return this._imageProcessingConfiguration.colorGradingTexture;
  76441. },
  76442. /**
  76443. * Sets the Color Grading 2D Lookup Texture.
  76444. */
  76445. set: function (value) {
  76446. this.imageProcessingConfiguration.colorGradingTexture = value;
  76447. },
  76448. enumerable: true,
  76449. configurable: true
  76450. });
  76451. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  76452. /**
  76453. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  76454. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  76455. * 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;
  76456. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  76457. */
  76458. get: function () {
  76459. return this.imageProcessingConfiguration.colorCurves;
  76460. },
  76461. /**
  76462. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  76463. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  76464. * 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;
  76465. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  76466. */
  76467. set: function (value) {
  76468. this.imageProcessingConfiguration.colorCurves = value;
  76469. },
  76470. enumerable: true,
  76471. configurable: true
  76472. });
  76473. /**
  76474. * The entire material has been created in order to prevent overdraw.
  76475. * @returns false
  76476. */
  76477. BackgroundMaterial.prototype.needAlphaTesting = function () {
  76478. return true;
  76479. };
  76480. /**
  76481. * The entire material has been created in order to prevent overdraw.
  76482. * @returns true if blending is enable
  76483. */
  76484. BackgroundMaterial.prototype.needAlphaBlending = function () {
  76485. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  76486. };
  76487. /**
  76488. * Checks wether the material is ready to be rendered for a given mesh.
  76489. * @param mesh The mesh to render
  76490. * @param subMesh The submesh to check against
  76491. * @param useInstances Specify wether or not the material is used with instances
  76492. */
  76493. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  76494. var _this = this;
  76495. if (useInstances === void 0) { useInstances = false; }
  76496. if (subMesh.effect && this.isFrozen) {
  76497. if (this._wasPreviouslyReady) {
  76498. return true;
  76499. }
  76500. }
  76501. if (!subMesh._materialDefines) {
  76502. subMesh._materialDefines = new BackgroundMaterialDefines();
  76503. }
  76504. var scene = this.getScene();
  76505. var defines = subMesh._materialDefines;
  76506. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  76507. if (defines._renderId === scene.getRenderId()) {
  76508. return true;
  76509. }
  76510. }
  76511. var engine = scene.getEngine();
  76512. // Lights
  76513. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  76514. defines._needNormals = true;
  76515. // Textures
  76516. if (defines._areTexturesDirty) {
  76517. defines._needUVs = false;
  76518. if (scene.texturesEnabled) {
  76519. if (scene.getEngine().getCaps().textureLOD) {
  76520. defines.TEXTURELODSUPPORT = true;
  76521. }
  76522. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  76523. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  76524. return false;
  76525. }
  76526. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  76527. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  76528. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  76529. defines.OPACITYFRESNEL = this._opacityFresnel;
  76530. }
  76531. else {
  76532. defines.DIFFUSE = false;
  76533. defines.DIFFUSEHASALPHA = false;
  76534. defines.GAMMADIFFUSE = false;
  76535. defines.OPACITYFRESNEL = false;
  76536. }
  76537. var reflectionTexture = this._reflectionTexture;
  76538. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  76539. if (!reflectionTexture.isReadyOrNotBlocking()) {
  76540. return false;
  76541. }
  76542. defines.REFLECTION = true;
  76543. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  76544. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  76545. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  76546. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  76547. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  76548. defines.INVERTCUBICMAP = true;
  76549. }
  76550. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  76551. switch (reflectionTexture.coordinatesMode) {
  76552. case BABYLON.Texture.CUBIC_MODE:
  76553. case BABYLON.Texture.INVCUBIC_MODE:
  76554. defines.REFLECTIONMAP_CUBIC = true;
  76555. break;
  76556. case BABYLON.Texture.EXPLICIT_MODE:
  76557. defines.REFLECTIONMAP_EXPLICIT = true;
  76558. break;
  76559. case BABYLON.Texture.PLANAR_MODE:
  76560. defines.REFLECTIONMAP_PLANAR = true;
  76561. break;
  76562. case BABYLON.Texture.PROJECTION_MODE:
  76563. defines.REFLECTIONMAP_PROJECTION = true;
  76564. break;
  76565. case BABYLON.Texture.SKYBOX_MODE:
  76566. defines.REFLECTIONMAP_SKYBOX = true;
  76567. break;
  76568. case BABYLON.Texture.SPHERICAL_MODE:
  76569. defines.REFLECTIONMAP_SPHERICAL = true;
  76570. break;
  76571. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  76572. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  76573. break;
  76574. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  76575. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  76576. break;
  76577. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  76578. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  76579. break;
  76580. }
  76581. if (this.reflectionFresnel) {
  76582. defines.REFLECTIONFRESNEL = true;
  76583. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  76584. this._reflectionControls.x = this.reflectionAmount;
  76585. this._reflectionControls.y = this.reflectionReflectance0;
  76586. this._reflectionControls.z = this.reflectionReflectance90;
  76587. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  76588. }
  76589. else {
  76590. defines.REFLECTIONFRESNEL = false;
  76591. defines.REFLECTIONFALLOFF = false;
  76592. }
  76593. }
  76594. else {
  76595. defines.REFLECTION = false;
  76596. defines.REFLECTIONFALLOFF = false;
  76597. defines.REFLECTIONBLUR = false;
  76598. defines.REFLECTIONMAP_3D = false;
  76599. defines.REFLECTIONMAP_SPHERICAL = false;
  76600. defines.REFLECTIONMAP_PLANAR = false;
  76601. defines.REFLECTIONMAP_CUBIC = false;
  76602. defines.REFLECTIONMAP_PROJECTION = false;
  76603. defines.REFLECTIONMAP_SKYBOX = false;
  76604. defines.REFLECTIONMAP_EXPLICIT = false;
  76605. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  76606. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  76607. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  76608. defines.INVERTCUBICMAP = false;
  76609. defines.REFLECTIONMAP_OPPOSITEZ = false;
  76610. defines.LODINREFLECTIONALPHA = false;
  76611. defines.GAMMAREFLECTION = false;
  76612. }
  76613. }
  76614. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  76615. defines.USERGBCOLOR = this._useRGBColor;
  76616. defines.NOISE = this._enableNoise;
  76617. }
  76618. if (defines._areImageProcessingDirty) {
  76619. if (!this._imageProcessingConfiguration.isReady()) {
  76620. return false;
  76621. }
  76622. this._imageProcessingConfiguration.prepareDefines(defines);
  76623. }
  76624. // Misc.
  76625. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  76626. // Values that need to be evaluated on every frame
  76627. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  76628. // Attribs
  76629. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  76630. if (mesh) {
  76631. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  76632. mesh.createNormals(true);
  76633. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  76634. }
  76635. }
  76636. }
  76637. // Get correct effect
  76638. if (defines.isDirty) {
  76639. defines.markAsProcessed();
  76640. scene.resetCachedMaterial();
  76641. // Fallbacks
  76642. var fallbacks = new BABYLON.EffectFallbacks();
  76643. if (defines.FOG) {
  76644. fallbacks.addFallback(0, "FOG");
  76645. }
  76646. if (defines.POINTSIZE) {
  76647. fallbacks.addFallback(1, "POINTSIZE");
  76648. }
  76649. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  76650. if (defines.NUM_BONE_INFLUENCERS > 0) {
  76651. fallbacks.addCPUSkinningFallback(0, mesh);
  76652. }
  76653. //Attributes
  76654. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76655. if (defines.NORMAL) {
  76656. attribs.push(BABYLON.VertexBuffer.NormalKind);
  76657. }
  76658. if (defines.UV1) {
  76659. attribs.push(BABYLON.VertexBuffer.UVKind);
  76660. }
  76661. if (defines.UV2) {
  76662. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76663. }
  76664. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  76665. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  76666. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  76667. "vFogInfos", "vFogColor", "pointSize",
  76668. "vClipPlane", "mBones",
  76669. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  76670. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  76671. "shadowLevel", "alpha",
  76672. "vBackgroundCenter", "vReflectionControl",
  76673. "vDiffuseInfos", "diffuseMatrix",
  76674. ];
  76675. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  76676. var uniformBuffers = ["Material", "Scene"];
  76677. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  76678. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  76679. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  76680. uniformsNames: uniforms,
  76681. uniformBuffersNames: uniformBuffers,
  76682. samplers: samplers,
  76683. defines: defines,
  76684. maxSimultaneousLights: this._maxSimultaneousLights
  76685. });
  76686. var onCompiled = function (effect) {
  76687. if (_this.onCompiled) {
  76688. _this.onCompiled(effect);
  76689. }
  76690. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  76691. };
  76692. var join = defines.toString();
  76693. subMesh.setEffect(scene.getEngine().createEffect("background", {
  76694. attributes: attribs,
  76695. uniformsNames: uniforms,
  76696. uniformBuffersNames: uniformBuffers,
  76697. samplers: samplers,
  76698. defines: join,
  76699. fallbacks: fallbacks,
  76700. onCompiled: onCompiled,
  76701. onError: this.onError,
  76702. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  76703. }, engine), defines);
  76704. this.buildUniformLayout();
  76705. }
  76706. if (!subMesh.effect || !subMesh.effect.isReady()) {
  76707. return false;
  76708. }
  76709. defines._renderId = scene.getRenderId();
  76710. this._wasPreviouslyReady = true;
  76711. return true;
  76712. };
  76713. /**
  76714. * Build the uniform buffer used in the material.
  76715. */
  76716. BackgroundMaterial.prototype.buildUniformLayout = function () {
  76717. // Order is important !
  76718. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  76719. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  76720. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  76721. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  76722. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  76723. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  76724. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  76725. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  76726. this._uniformBuffer.addUniform("pointSize", 1);
  76727. this._uniformBuffer.addUniform("shadowLevel", 1);
  76728. this._uniformBuffer.addUniform("alpha", 1);
  76729. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  76730. this._uniformBuffer.addUniform("vReflectionControl", 4);
  76731. this._uniformBuffer.create();
  76732. };
  76733. /**
  76734. * Unbind the material.
  76735. */
  76736. BackgroundMaterial.prototype.unbind = function () {
  76737. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  76738. this._uniformBuffer.setTexture("diffuseSampler", null);
  76739. }
  76740. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  76741. this._uniformBuffer.setTexture("reflectionSampler", null);
  76742. }
  76743. _super.prototype.unbind.call(this);
  76744. };
  76745. /**
  76746. * Bind only the world matrix to the material.
  76747. * @param world The world matrix to bind.
  76748. */
  76749. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  76750. this._activeEffect.setMatrix("world", world);
  76751. };
  76752. /**
  76753. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  76754. * @param world The world matrix to bind.
  76755. * @param subMesh The submesh to bind for.
  76756. */
  76757. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  76758. var scene = this.getScene();
  76759. var defines = subMesh._materialDefines;
  76760. if (!defines) {
  76761. return;
  76762. }
  76763. var effect = subMesh.effect;
  76764. if (!effect) {
  76765. return;
  76766. }
  76767. this._activeEffect = effect;
  76768. // Matrices
  76769. this.bindOnlyWorldMatrix(world);
  76770. // Bones
  76771. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  76772. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  76773. if (mustRebind) {
  76774. this._uniformBuffer.bindToEffect(effect, "Material");
  76775. this.bindViewProjection(effect);
  76776. var reflectionTexture = this._reflectionTexture;
  76777. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  76778. // Texture uniforms
  76779. if (scene.texturesEnabled) {
  76780. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  76781. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  76782. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  76783. }
  76784. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  76785. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  76786. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  76787. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  76788. }
  76789. }
  76790. if (this.shadowLevel > 0) {
  76791. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  76792. }
  76793. this._uniformBuffer.updateFloat("alpha", this.alpha);
  76794. // Point size
  76795. if (this.pointsCloud) {
  76796. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  76797. }
  76798. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  76799. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  76800. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  76801. }
  76802. // Textures
  76803. if (scene.texturesEnabled) {
  76804. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  76805. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  76806. }
  76807. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  76808. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  76809. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  76810. }
  76811. else if (!defines.REFLECTIONBLUR) {
  76812. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  76813. }
  76814. else {
  76815. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  76816. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  76817. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  76818. }
  76819. if (defines.REFLECTIONFRESNEL) {
  76820. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  76821. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  76822. }
  76823. }
  76824. }
  76825. // Clip plane
  76826. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  76827. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  76828. }
  76829. if (mustRebind || !this.isFrozen) {
  76830. if (scene.lightsEnabled) {
  76831. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  76832. }
  76833. // View
  76834. this.bindView(effect);
  76835. // Fog
  76836. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  76837. // image processing
  76838. this._imageProcessingConfiguration.bind(this._activeEffect);
  76839. }
  76840. this._uniformBuffer.update();
  76841. this._afterBind(mesh);
  76842. };
  76843. /**
  76844. * Dispose the material.
  76845. * @forceDisposeEffect Force disposal of the associated effect.
  76846. * @forceDisposeTextures Force disposal of the associated textures.
  76847. */
  76848. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  76849. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  76850. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  76851. if (forceDisposeTextures) {
  76852. if (this.diffuseTexture) {
  76853. this.diffuseTexture.dispose();
  76854. }
  76855. if (this.reflectionTexture) {
  76856. this.reflectionTexture.dispose();
  76857. }
  76858. }
  76859. this._renderTargets.dispose();
  76860. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76861. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76862. }
  76863. _super.prototype.dispose.call(this, forceDisposeEffect);
  76864. };
  76865. /**
  76866. * Clones the material.
  76867. * @name The cloned name.
  76868. * @returns The cloned material.
  76869. */
  76870. BackgroundMaterial.prototype.clone = function (name) {
  76871. var _this = this;
  76872. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  76873. };
  76874. /**
  76875. * Serializes the current material to its JSON representation.
  76876. * @returns The JSON representation.
  76877. */
  76878. BackgroundMaterial.prototype.serialize = function () {
  76879. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76880. serializationObject.customType = "BABYLON.BackgroundMaterial";
  76881. return serializationObject;
  76882. };
  76883. /**
  76884. * Gets the class name of the material
  76885. * @returns "BackgroundMaterial"
  76886. */
  76887. BackgroundMaterial.prototype.getClassName = function () {
  76888. return "BackgroundMaterial";
  76889. };
  76890. /**
  76891. * Parse a JSON input to create back a background material.
  76892. * @param source
  76893. * @param scene
  76894. * @param rootUrl
  76895. * @returns the instantiated BackgroundMaterial.
  76896. */
  76897. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  76898. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  76899. };
  76900. /**
  76901. * Standard reflectance value at parallel view angle.
  76902. */
  76903. BackgroundMaterial.standardReflectance0 = 0.05;
  76904. /**
  76905. * Standard reflectance value at grazing angle.
  76906. */
  76907. BackgroundMaterial.standardReflectance90 = 0.5;
  76908. __decorate([
  76909. BABYLON.serializeAsColor3()
  76910. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  76911. __decorate([
  76912. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76913. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  76914. __decorate([
  76915. BABYLON.serialize()
  76916. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  76917. __decorate([
  76918. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76919. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  76920. __decorate([
  76921. BABYLON.serializeAsColor3()
  76922. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  76923. __decorate([
  76924. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76925. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  76926. __decorate([
  76927. BABYLON.serialize()
  76928. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  76929. __decorate([
  76930. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76931. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  76932. __decorate([
  76933. BABYLON.serializeAsColor3()
  76934. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  76935. __decorate([
  76936. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76937. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  76938. __decorate([
  76939. BABYLON.serialize()
  76940. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  76941. __decorate([
  76942. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  76943. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  76944. __decorate([
  76945. BABYLON.serializeAsTexture()
  76946. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  76947. __decorate([
  76948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76949. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  76950. __decorate([
  76951. BABYLON.serialize()
  76952. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  76953. __decorate([
  76954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76955. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  76956. __decorate([
  76957. BABYLON.serializeAsTexture()
  76958. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  76959. __decorate([
  76960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76961. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  76962. __decorate([
  76963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76964. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  76965. __decorate([
  76966. BABYLON.serialize()
  76967. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  76968. __decorate([
  76969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76970. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  76971. __decorate([
  76972. BABYLON.serialize()
  76973. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  76974. __decorate([
  76975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76976. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  76977. __decorate([
  76978. BABYLON.serializeAsVector3()
  76979. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  76980. __decorate([
  76981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76982. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  76983. __decorate([
  76984. BABYLON.serialize()
  76985. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  76986. __decorate([
  76987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76988. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  76989. __decorate([
  76990. BABYLON.serialize()
  76991. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  76992. __decorate([
  76993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  76994. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  76995. __decorate([
  76996. BABYLON.serialize()
  76997. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  76998. __decorate([
  76999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77000. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  77001. __decorate([
  77002. BABYLON.serialize()
  77003. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  77004. __decorate([
  77005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77006. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  77007. __decorate([
  77008. BABYLON.serialize()
  77009. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  77010. __decorate([
  77011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77012. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  77013. __decorate([
  77014. BABYLON.serialize()
  77015. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  77016. __decorate([
  77017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77018. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  77019. __decorate([
  77020. BABYLON.serialize()
  77021. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  77022. __decorate([
  77023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77024. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  77025. __decorate([
  77026. BABYLON.serialize()
  77027. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  77028. __decorate([
  77029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77030. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  77031. __decorate([
  77032. BABYLON.serialize()
  77033. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  77034. __decorate([
  77035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  77036. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  77037. __decorate([
  77038. BABYLON.serializeAsImageProcessingConfiguration()
  77039. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  77040. return BackgroundMaterial;
  77041. }(BABYLON.PushMaterial));
  77042. BABYLON.BackgroundMaterial = BackgroundMaterial;
  77043. })(BABYLON || (BABYLON = {}));
  77044. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  77045. var __assign = (this && this.__assign) || Object.assign || function(t) {
  77046. for (var s, i = 1, n = arguments.length; i < n; i++) {
  77047. s = arguments[i];
  77048. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  77049. t[p] = s[p];
  77050. }
  77051. return t;
  77052. };
  77053. var BABYLON;
  77054. (function (BABYLON) {
  77055. /**
  77056. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  77057. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  77058. * It also helps with the default setup of your imageProcessing configuration.
  77059. */
  77060. var EnvironmentHelper = /** @class */ (function () {
  77061. /**
  77062. * constructor
  77063. * @param options
  77064. * @param scene The scene to add the material to
  77065. */
  77066. function EnvironmentHelper(options, scene) {
  77067. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  77068. this._scene = scene;
  77069. this._setupBackground();
  77070. this._setupImageProcessing();
  77071. }
  77072. /**
  77073. * Creates the default options for the helper.
  77074. */
  77075. EnvironmentHelper._getDefaultOptions = function () {
  77076. return {
  77077. createGround: true,
  77078. groundSize: 15,
  77079. groundTexture: this._groundTextureCDNUrl,
  77080. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  77081. groundOpacity: 0.9,
  77082. enableGroundShadow: true,
  77083. groundShadowLevel: 0.5,
  77084. enableGroundMirror: false,
  77085. groundMirrorSizeRatio: 0.3,
  77086. groundMirrorBlurKernel: 64,
  77087. groundMirrorAmount: 1,
  77088. groundMirrorFresnelWeight: 1,
  77089. groundMirrorFallOffDistance: 0,
  77090. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  77091. createSkybox: true,
  77092. skyboxSize: 20,
  77093. skyboxTexture: this._skyboxTextureCDNUrl,
  77094. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  77095. backgroundYRotation: 0,
  77096. sizeAuto: true,
  77097. rootPosition: BABYLON.Vector3.Zero(),
  77098. setupImageProcessing: true,
  77099. environmentTexture: this._environmentTextureCDNUrl,
  77100. cameraExposure: 0.8,
  77101. cameraContrast: 1.2,
  77102. toneMappingEnabled: true,
  77103. };
  77104. };
  77105. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  77106. /**
  77107. * Gets the root mesh created by the helper.
  77108. */
  77109. get: function () {
  77110. return this._rootMesh;
  77111. },
  77112. enumerable: true,
  77113. configurable: true
  77114. });
  77115. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  77116. /**
  77117. * Gets the skybox created by the helper.
  77118. */
  77119. get: function () {
  77120. return this._skybox;
  77121. },
  77122. enumerable: true,
  77123. configurable: true
  77124. });
  77125. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  77126. /**
  77127. * Gets the skybox texture created by the helper.
  77128. */
  77129. get: function () {
  77130. return this._skyboxTexture;
  77131. },
  77132. enumerable: true,
  77133. configurable: true
  77134. });
  77135. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  77136. /**
  77137. * Gets the skybox material created by the helper.
  77138. */
  77139. get: function () {
  77140. return this._skyboxMaterial;
  77141. },
  77142. enumerable: true,
  77143. configurable: true
  77144. });
  77145. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  77146. /**
  77147. * Gets the ground mesh created by the helper.
  77148. */
  77149. get: function () {
  77150. return this._ground;
  77151. },
  77152. enumerable: true,
  77153. configurable: true
  77154. });
  77155. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  77156. /**
  77157. * Gets the ground texture created by the helper.
  77158. */
  77159. get: function () {
  77160. return this._groundTexture;
  77161. },
  77162. enumerable: true,
  77163. configurable: true
  77164. });
  77165. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  77166. /**
  77167. * Gets the ground mirror created by the helper.
  77168. */
  77169. get: function () {
  77170. return this._groundMirror;
  77171. },
  77172. enumerable: true,
  77173. configurable: true
  77174. });
  77175. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  77176. /**
  77177. * Gets the ground mirror render list to helps pushing the meshes
  77178. * you wish in the ground reflection.
  77179. */
  77180. get: function () {
  77181. if (this._groundMirror) {
  77182. return this._groundMirror.renderList;
  77183. }
  77184. return null;
  77185. },
  77186. enumerable: true,
  77187. configurable: true
  77188. });
  77189. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  77190. /**
  77191. * Gets the ground material created by the helper.
  77192. */
  77193. get: function () {
  77194. return this._groundMaterial;
  77195. },
  77196. enumerable: true,
  77197. configurable: true
  77198. });
  77199. /**
  77200. * Updates the background according to the new options
  77201. * @param options
  77202. */
  77203. EnvironmentHelper.prototype.updateOptions = function (options) {
  77204. var newOptions = __assign({}, this._options, options);
  77205. if (this._ground && !newOptions.createGround) {
  77206. this._ground.dispose();
  77207. this._ground = null;
  77208. }
  77209. if (this._groundMaterial && !newOptions.createGround) {
  77210. this._groundMaterial.dispose();
  77211. this._groundMaterial = null;
  77212. }
  77213. if (this._options.groundTexture && !newOptions.groundTexture && this._groundTexture) {
  77214. this._groundTexture.dispose();
  77215. this._groundTexture = null;
  77216. }
  77217. if (this._skybox && !newOptions.createSkybox) {
  77218. this._skybox.dispose();
  77219. this._skybox = null;
  77220. }
  77221. if (this._skyboxMaterial && !newOptions.createSkybox) {
  77222. this._skyboxMaterial.dispose();
  77223. this._skyboxMaterial = null;
  77224. }
  77225. if (this._options.skyboxTexture && !newOptions.skyboxTexture && this._skyboxTexture) {
  77226. this._skyboxTexture.dispose();
  77227. this._skyboxTexture = null;
  77228. }
  77229. if (this._groundMirror && !newOptions.enableGroundMirror) {
  77230. this._groundMirror.dispose();
  77231. this._groundMirror = null;
  77232. }
  77233. this._setupBackground();
  77234. if (this._options.environmentTexture && !newOptions.environmentTexture && this._scene.environmentTexture) {
  77235. this._scene.environmentTexture.dispose();
  77236. }
  77237. this._setupImageProcessing();
  77238. };
  77239. /**
  77240. * Sets the primary color of all the available elements.
  77241. * @param color
  77242. */
  77243. EnvironmentHelper.prototype.setMainColor = function (color) {
  77244. if (this.groundMaterial) {
  77245. this.groundMaterial.primaryColor = color;
  77246. }
  77247. if (this.skyboxMaterial) {
  77248. this.skyboxMaterial.primaryColor = color;
  77249. }
  77250. if (this.groundMirror) {
  77251. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  77252. }
  77253. };
  77254. /**
  77255. * Setup the image processing according to the specified options.
  77256. */
  77257. EnvironmentHelper.prototype._setupImageProcessing = function () {
  77258. if (this._options.setupImageProcessing) {
  77259. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  77260. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  77261. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  77262. this._setupEnvironmentTexture();
  77263. }
  77264. };
  77265. /**
  77266. * Setup the environment texture according to the specified options.
  77267. */
  77268. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  77269. if (this._scene.environmentTexture) {
  77270. return;
  77271. }
  77272. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  77273. this._scene.environmentTexture = this._options.environmentTexture;
  77274. return;
  77275. }
  77276. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  77277. this._scene.environmentTexture = environmentTexture;
  77278. };
  77279. /**
  77280. * Setup the background according to the specified options.
  77281. */
  77282. EnvironmentHelper.prototype._setupBackground = function () {
  77283. if (!this._rootMesh) {
  77284. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  77285. }
  77286. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  77287. var sceneSize = this._getSceneSize();
  77288. if (this._options.createGround) {
  77289. this._setupGround(sceneSize);
  77290. this._setupGroundMaterial();
  77291. this._setupGroundDiffuseTexture();
  77292. if (this._options.enableGroundMirror) {
  77293. this._setupGroundMirrorTexture(sceneSize);
  77294. this._setupMirrorInGroundMaterial();
  77295. }
  77296. }
  77297. if (this._options.createSkybox) {
  77298. this._setupSkybox(sceneSize);
  77299. this._setupSkyboxMaterial();
  77300. this._setupSkyboxReflectionTexture();
  77301. }
  77302. this._rootMesh.position.x = sceneSize.rootPosition.x;
  77303. this._rootMesh.position.z = sceneSize.rootPosition.z;
  77304. this._rootMesh.position.y = sceneSize.rootPosition.y;
  77305. };
  77306. /**
  77307. * Get the scene sizes according to the setup.
  77308. */
  77309. EnvironmentHelper.prototype._getSceneSize = function () {
  77310. var groundSize = this._options.groundSize;
  77311. var skyboxSize = this._options.skyboxSize;
  77312. var rootPosition = this._options.rootPosition;
  77313. var sceneExtends = this._scene.getWorldExtends();
  77314. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  77315. var bias = 0.0001;
  77316. if (this._options.sizeAuto) {
  77317. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  77318. this._scene.activeCamera.upperRadiusLimit) {
  77319. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  77320. }
  77321. if (this._scene.activeCamera) {
  77322. bias = (this._scene.activeCamera.maxZ - this._scene.activeCamera.minZ) / 10000;
  77323. }
  77324. var sceneDiagonalLenght = sceneDiagonal.length();
  77325. if (sceneDiagonalLenght > groundSize) {
  77326. groundSize = sceneDiagonalLenght * 2;
  77327. }
  77328. // 10 % bigger.
  77329. groundSize *= 1.1;
  77330. skyboxSize *= 1.5;
  77331. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  77332. rootPosition.y = sceneExtends.min.y - bias;
  77333. }
  77334. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  77335. };
  77336. /**
  77337. * Setup the ground according to the specified options.
  77338. */
  77339. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  77340. if (!this._ground) {
  77341. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  77342. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  77343. this._ground.parent = this._rootMesh;
  77344. }
  77345. this._ground.receiveShadows = this._options.enableGroundShadow;
  77346. };
  77347. /**
  77348. * Setup the ground material according to the specified options.
  77349. */
  77350. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  77351. if (!this._groundMaterial) {
  77352. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  77353. }
  77354. this._groundMaterial.alpha = this._options.groundOpacity;
  77355. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  77356. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  77357. this._groundMaterial.primaryLevel = 1;
  77358. this._groundMaterial.primaryColor = this._options.groundColor;
  77359. this._groundMaterial.secondaryLevel = 0;
  77360. this._groundMaterial.tertiaryLevel = 0;
  77361. this._groundMaterial.useRGBColor = false;
  77362. this._groundMaterial.enableNoise = true;
  77363. if (this._ground) {
  77364. this._ground.material = this._groundMaterial;
  77365. }
  77366. };
  77367. /**
  77368. * Setup the ground diffuse texture according to the specified options.
  77369. */
  77370. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  77371. if (!this._groundMaterial) {
  77372. return;
  77373. }
  77374. if (this._groundTexture) {
  77375. return;
  77376. }
  77377. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  77378. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  77379. return;
  77380. }
  77381. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  77382. diffuseTexture.gammaSpace = false;
  77383. diffuseTexture.hasAlpha = true;
  77384. this._groundMaterial.diffuseTexture = diffuseTexture;
  77385. };
  77386. /**
  77387. * Setup the ground mirror texture according to the specified options.
  77388. */
  77389. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  77390. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77391. if (!this._groundMirror) {
  77392. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  77393. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  77394. this._groundMirror.anisotropicFilteringLevel = 1;
  77395. this._groundMirror.wrapU = wrapping;
  77396. this._groundMirror.wrapV = wrapping;
  77397. this._groundMirror.gammaSpace = false;
  77398. if (this._groundMirror.renderList) {
  77399. for (var i = 0; i < this._scene.meshes.length; i++) {
  77400. var mesh = this._scene.meshes[i];
  77401. if (mesh !== this._ground &&
  77402. mesh !== this._skybox &&
  77403. mesh !== this._rootMesh) {
  77404. this._groundMirror.renderList.push(mesh);
  77405. }
  77406. }
  77407. }
  77408. }
  77409. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  77410. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  77411. };
  77412. /**
  77413. * Setup the ground to receive the mirror texture.
  77414. */
  77415. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  77416. if (this._groundMaterial) {
  77417. this._groundMaterial.reflectionTexture = this._groundMirror;
  77418. this._groundMaterial.reflectionFresnel = true;
  77419. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  77420. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  77421. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  77422. }
  77423. };
  77424. /**
  77425. * Setup the skybox according to the specified options.
  77426. */
  77427. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  77428. if (!this._skybox) {
  77429. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  77430. }
  77431. this._skybox.parent = this._rootMesh;
  77432. };
  77433. /**
  77434. * Setup the skybox material according to the specified options.
  77435. */
  77436. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  77437. if (!this._skybox) {
  77438. return;
  77439. }
  77440. if (!this._skyboxMaterial) {
  77441. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  77442. }
  77443. this._skyboxMaterial.useRGBColor = false;
  77444. this._skyboxMaterial.primaryLevel = 1;
  77445. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  77446. this._skyboxMaterial.secondaryLevel = 0;
  77447. this._skyboxMaterial.tertiaryLevel = 0;
  77448. this._skyboxMaterial.enableNoise = true;
  77449. this._skybox.material = this._skyboxMaterial;
  77450. };
  77451. /**
  77452. * Setup the skybox reflection texture according to the specified options.
  77453. */
  77454. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  77455. if (!this._skyboxMaterial) {
  77456. return;
  77457. }
  77458. if (this._skyboxTexture) {
  77459. return;
  77460. }
  77461. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  77462. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  77463. return;
  77464. }
  77465. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  77466. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  77467. this._skyboxTexture.gammaSpace = false;
  77468. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  77469. };
  77470. /**
  77471. * Dispose all the elements created by the Helper.
  77472. */
  77473. EnvironmentHelper.prototype.dispose = function () {
  77474. if (this._groundMaterial) {
  77475. this._groundMaterial.dispose(true, true);
  77476. }
  77477. if (this._skyboxMaterial) {
  77478. this._skyboxMaterial.dispose(true, true);
  77479. }
  77480. this._rootMesh.dispose(true);
  77481. };
  77482. /**
  77483. * Default ground texture URL.
  77484. */
  77485. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  77486. /**
  77487. * Default skybox texture URL.
  77488. */
  77489. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  77490. /**
  77491. * Default environment texture URL.
  77492. */
  77493. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  77494. return EnvironmentHelper;
  77495. }());
  77496. BABYLON.EnvironmentHelper = EnvironmentHelper;
  77497. })(BABYLON || (BABYLON = {}));
  77498. //# sourceMappingURL=babylon.environmentHelper.js.map
  77499. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\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=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 AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\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\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\nvoid main() {\ngl_PointSize=1.0;\ngl_Position=vec4(position,1.0);\n}","gpuRenderParticlesPixelShader":"void main() {\ngl_FragColor=vec4(1.0);\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\nuniform float timeDelta;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec3 outVelocity;\nvoid main() {\nif (age>=life) {\n\noutPosition=vec3(0,0,0);\n\noutAge=0.0;\noutLife=life;\n\noutVelocity=vec3(0,1,0);\n} else {\noutPosition=position+velocity*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutVelocity=velocity;\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=abs(texture2D(textureSampler,vUV).r);\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,1.0);\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=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#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 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}","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);\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\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\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\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#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\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  77500. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor.rgb+=mix(-0.5/255.0,0.5/255.0,rand);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#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}\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 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#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;\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":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\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\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\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#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#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 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\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","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 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};"};
  77501. (function universalModuleDefinition(root, factory) {
  77502. var f = factory();
  77503. if (root && root["BABYLON"]) {
  77504. return;
  77505. }
  77506. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  77507. globalObject["BABYLON"] = f;
  77508. if(true)
  77509. module.exports = f;
  77510. else if(typeof define === 'function' && define.amd)
  77511. define(["BABYLON"], factory);
  77512. else if(typeof exports === 'object')
  77513. exports["BABYLON"] = f;
  77514. else {
  77515. root["BABYLON"] = f;
  77516. }
  77517. })(this, function() {
  77518. return BABYLON;
  77519. });
  77520. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
  77521. /***/ }),
  77522. /* 1 */
  77523. /***/ (function(module, exports) {
  77524. var g;
  77525. // This works in non-strict mode
  77526. g = (function() {
  77527. return this;
  77528. })();
  77529. try {
  77530. // This works if eval is allowed (see CSP)
  77531. g = g || Function("return this")() || (1,eval)("this");
  77532. } catch(e) {
  77533. // This works if the window reference is available
  77534. if(typeof window === "object")
  77535. g = window;
  77536. }
  77537. // g can still be undefined, but nothing to do about it...
  77538. // We return undefined, instead of nothing here, so it's
  77539. // easier to handle this case. if(!global) { ...}
  77540. module.exports = g;
  77541. /***/ }),
  77542. /* 2 */
  77543. /***/ (function(module, exports, __webpack_require__) {
  77544. "use strict";
  77545. Object.defineProperty(exports, "__esModule", { value: true });
  77546. var babylonjs_1 = __webpack_require__(0);
  77547. var helper_1 = __webpack_require__(3);
  77548. var HTMLMapper = (function () {
  77549. function HTMLMapper() {
  77550. }
  77551. HTMLMapper.prototype.map = function (element) {
  77552. var config = {};
  77553. var _loop_1 = function (attrIdx) {
  77554. var attr = element.attributes.item(attrIdx);
  77555. var split = attr.nodeName.split('.');
  77556. split.reduce(function (currentConfig, key, idx) {
  77557. var camelKey = helper_1.kebabToCamel(key);
  77558. if (idx === split.length - 1) {
  77559. var val = attr.nodeValue;
  77560. if (val === "true") {
  77561. val = true;
  77562. }
  77563. else if (val === "false") {
  77564. val = false;
  77565. }
  77566. else {
  77567. var number = parseFloat(val);
  77568. if (!isNaN(number)) {
  77569. val = number;
  77570. }
  77571. }
  77572. currentConfig[camelKey] = val;
  77573. }
  77574. else {
  77575. currentConfig[camelKey] = currentConfig[camelKey] || {};
  77576. }
  77577. return currentConfig[camelKey];
  77578. }, config);
  77579. };
  77580. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  77581. _loop_1(attrIdx);
  77582. }
  77583. return config;
  77584. };
  77585. return HTMLMapper;
  77586. }());
  77587. var JSONMapper = (function () {
  77588. function JSONMapper() {
  77589. }
  77590. JSONMapper.prototype.map = function (rawSource) {
  77591. return JSON.parse(rawSource);
  77592. };
  77593. return JSONMapper;
  77594. }());
  77595. var DOMMapper = (function () {
  77596. function DOMMapper() {
  77597. }
  77598. DOMMapper.prototype.map = function (baseElement) {
  77599. var htmlMapper = new HTMLMapper();
  77600. var config = htmlMapper.map(baseElement);
  77601. var traverseChildren = function (element, partConfig) {
  77602. var children = element.children;
  77603. if (children.length) {
  77604. for (var i = 0; i < children.length; ++i) {
  77605. var item = children.item(i);
  77606. var configMapped = htmlMapper.map(item);
  77607. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  77608. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  77609. partConfig[key] = [];
  77610. }
  77611. else {
  77612. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  77613. partConfig.push(configMapped);
  77614. }
  77615. else if (partConfig[key]) {
  77616. element.setAttribute('array', 'true');
  77617. var oldItem = partConfig[key];
  77618. partConfig = [oldItem, configMapped];
  77619. }
  77620. else {
  77621. partConfig[key] = configMapped;
  77622. }
  77623. }
  77624. traverseChildren(item, partConfig[key] || configMapped);
  77625. }
  77626. }
  77627. return partConfig;
  77628. };
  77629. traverseChildren(baseElement, config);
  77630. return config;
  77631. };
  77632. return DOMMapper;
  77633. }());
  77634. var MapperManager = (function () {
  77635. function MapperManager() {
  77636. this.mappers = {
  77637. "html": new HTMLMapper(),
  77638. "json": new JSONMapper(),
  77639. "dom": new DOMMapper()
  77640. };
  77641. }
  77642. MapperManager.prototype.getMapper = function (type) {
  77643. if (!this.mappers[type]) {
  77644. babylonjs_1.Tools.Error("No mapper defined for " + type);
  77645. }
  77646. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  77647. };
  77648. MapperManager.prototype.registerMapper = function (type, mapper) {
  77649. this.mappers[type] = mapper;
  77650. };
  77651. MapperManager.DefaultMapper = 'json';
  77652. return MapperManager;
  77653. }());
  77654. exports.MapperManager = MapperManager;
  77655. exports.mapperManager = new MapperManager();
  77656. exports.default = exports.mapperManager;
  77657. /***/ }),
  77658. /* 3 */
  77659. /***/ (function(module, exports, __webpack_require__) {
  77660. "use strict";
  77661. Object.defineProperty(exports, "__esModule", { value: true });
  77662. function isUrl(urlToCheck) {
  77663. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  77664. return true;
  77665. }
  77666. return false;
  77667. }
  77668. exports.isUrl = isUrl;
  77669. function loadFile(url) {
  77670. return new Promise(function (resolve, reject) {
  77671. var xhr = new XMLHttpRequest();
  77672. xhr.open('GET', url);
  77673. xhr.send();
  77674. xhr.onreadystatechange = function () {
  77675. var DONE = 4;
  77676. var OK = 200;
  77677. if (xhr.readyState === DONE) {
  77678. if (xhr.status === OK) {
  77679. resolve(xhr.responseText);
  77680. }
  77681. }
  77682. else {
  77683. console.log('Error: ' + xhr.status, url);
  77684. reject('Error: ' + xhr.status);
  77685. }
  77686. };
  77687. });
  77688. }
  77689. exports.loadFile = loadFile;
  77690. function kebabToCamel(s) {
  77691. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  77692. }
  77693. exports.kebabToCamel = kebabToCamel;
  77694. function camelToKebab(str) {
  77695. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  77696. }
  77697. exports.camelToKebab = camelToKebab;
  77698. /***/ }),
  77699. /* 4 */
  77700. /***/ (function(module, exports, __webpack_require__) {
  77701. "use strict";
  77702. Object.defineProperty(exports, "__esModule", { value: true });
  77703. var babylonjs_1 = __webpack_require__(0);
  77704. var ViewerManager = (function () {
  77705. function ViewerManager() {
  77706. this.viewers = {};
  77707. this.onViewerAddedObservable = new babylonjs_1.Observable();
  77708. }
  77709. ViewerManager.prototype.addViewer = function (viewer) {
  77710. this.viewers[viewer.getBaseId()] = viewer;
  77711. this._onViewerAdded(viewer);
  77712. };
  77713. ViewerManager.prototype.getViewerById = function (id) {
  77714. return this.viewers[id];
  77715. };
  77716. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  77717. for (var id in this.viewers) {
  77718. if (this.viewers[id].containerElement === element) {
  77719. return this.getViewerById(id);
  77720. }
  77721. }
  77722. };
  77723. ViewerManager.prototype.getViewerPromiseById = function (id) {
  77724. var _this = this;
  77725. return new Promise(function (resolve, reject) {
  77726. var localViewer = _this.getViewerById(id);
  77727. if (localViewer) {
  77728. return resolve(localViewer);
  77729. }
  77730. var viewerFunction = function (viewer) {
  77731. if (viewer.getBaseId() === id) {
  77732. resolve(viewer);
  77733. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  77734. }
  77735. };
  77736. _this.onViewerAddedObservable.add(viewerFunction);
  77737. });
  77738. };
  77739. ViewerManager.prototype._onViewerAdded = function (viewer) {
  77740. this.onViewerAdded && this.onViewerAdded(viewer);
  77741. this.onViewerAddedObservable.notifyObservers(viewer);
  77742. };
  77743. return ViewerManager;
  77744. }());
  77745. exports.viewerManager = new ViewerManager();
  77746. /***/ }),
  77747. /* 5 */
  77748. /***/ (function(module, exports, __webpack_require__) {
  77749. "use strict";
  77750. var __extends = (this && this.__extends) || (function () {
  77751. var extendStatics = Object.setPrototypeOf ||
  77752. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  77753. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  77754. return function (d, b) {
  77755. extendStatics(d, b);
  77756. function __() { this.constructor = d; }
  77757. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  77758. };
  77759. })();
  77760. Object.defineProperty(exports, "__esModule", { value: true });
  77761. var viewer_1 = __webpack_require__(6);
  77762. var babylonjs_1 = __webpack_require__(0);
  77763. var BABYLON = __webpack_require__(0);
  77764. window['BABYLON'] = BABYLON;
  77765. var DefaultViewer = (function (_super) {
  77766. __extends(DefaultViewer, _super);
  77767. function DefaultViewer(containerElement, initialConfiguration) {
  77768. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  77769. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  77770. _this.containerElement = containerElement;
  77771. _this.onModelLoaded = function (meshes) {
  77772. _this.setModelMetaData();
  77773. setTimeout(function () {
  77774. _this.hideLoadingScreen();
  77775. }, 500);
  77776. _this.scene.createDefaultCameraOrLight(true, true, true);
  77777. _this.camera = _this.scene.activeCamera;
  77778. meshes[0].rotation.y += Math.PI;
  77779. _this.setupCamera(meshes);
  77780. _this.setupLights(meshes);
  77781. return _this.initEnvironment();
  77782. };
  77783. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  77784. return _this;
  77785. }
  77786. DefaultViewer.prototype.initScene = function () {
  77787. var _this = this;
  77788. return _super.prototype.initScene.call(this).then(function () {
  77789. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  77790. return _this.scene;
  77791. });
  77792. };
  77793. DefaultViewer.prototype.onTemplatesLoaded = function () {
  77794. var _this = this;
  77795. this.showLoadingScreen();
  77796. var viewerElement = this.templateManager.getTemplate('viewer');
  77797. var navbar = this.templateManager.getTemplate('navBar');
  77798. if (viewerElement && navbar) {
  77799. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  77800. var navbarShown_1 = true;
  77801. var timeoutCancel_1;
  77802. var triggerNavbar = function (show, evt) {
  77803. if (show === void 0) { show = false; }
  77804. if (!navbar || evt.button > 0)
  77805. return;
  77806. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  77807. if (show === navbarShown_1)
  77808. return;
  77809. if (show) {
  77810. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  77811. navbarShown_1 = show;
  77812. }
  77813. else {
  77814. var visibilityTimeout = 2000;
  77815. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  77816. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  77817. }
  77818. timeoutCancel_1 = setTimeout(function () {
  77819. if (navbar) {
  77820. navbar.parent.style.bottom = '-' + navbarHeight_1;
  77821. }
  77822. navbarShown_1 = show;
  77823. }, visibilityTimeout);
  77824. }
  77825. };
  77826. viewerElement.parent.addEventListener('pointerout', triggerNavbar.bind(this, false));
  77827. viewerElement.parent.addEventListener('pointerdown', triggerNavbar.bind(this, true));
  77828. viewerElement.parent.addEventListener('pointerup', triggerNavbar.bind(this, false));
  77829. navbar.parent.addEventListener('pointerover', triggerNavbar.bind(this, true));
  77830. this.registerNavbarButtons();
  77831. }
  77832. var closeButton = document.getElementById('close-button');
  77833. if (closeButton) {
  77834. closeButton.addEventListener('pointerdown', function () {
  77835. _this.hideOverlayScreen();
  77836. });
  77837. }
  77838. return _super.prototype.onTemplatesLoaded.call(this);
  77839. };
  77840. DefaultViewer.prototype.registerNavbarButtons = function () {
  77841. var _this = this;
  77842. var isFullscreen = false;
  77843. var navbar = this.templateManager.getTemplate('navBar');
  77844. var viewerTemplate = this.templateManager.getTemplate('viewer');
  77845. if (!navbar || !viewerTemplate)
  77846. return;
  77847. var viewerElement = viewerTemplate.parent;
  77848. navbar.onEventTriggered.add(function (data) {
  77849. switch (data.event.type) {
  77850. case 'pointerdown':
  77851. var event_1 = data.event;
  77852. if (event_1.button === 0) {
  77853. switch (data.selector) {
  77854. case '#fullscreen-button':
  77855. if (!isFullscreen) {
  77856. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  77857. requestFullScreen.call(viewerElement);
  77858. }
  77859. else {
  77860. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen;
  77861. exitFullscreen.call(document);
  77862. }
  77863. isFullscreen = !isFullscreen;
  77864. break;
  77865. case '#help-button':
  77866. _this.showOverlayScreen('help');
  77867. break;
  77868. }
  77869. }
  77870. break;
  77871. }
  77872. });
  77873. };
  77874. DefaultViewer.prototype.prepareContainerElement = function () {
  77875. this.containerElement.style.position = 'relative';
  77876. this.containerElement.style.display = 'flex';
  77877. };
  77878. DefaultViewer.prototype.loadModel = function (model) {
  77879. var _this = this;
  77880. if (model === void 0) { model = this.configuration.model; }
  77881. this.showLoadingScreen();
  77882. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  77883. console.log(error);
  77884. _this.hideLoadingScreen();
  77885. _this.showOverlayScreen('error');
  77886. return _this.scene;
  77887. });
  77888. };
  77889. DefaultViewer.prototype.setModelMetaData = function () {
  77890. var navbar = this.templateManager.getTemplate('navBar');
  77891. if (!navbar)
  77892. return;
  77893. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  77894. if (metadataContainer && typeof this.configuration.model === 'object') {
  77895. if (this.configuration.model.title) {
  77896. var element = metadataContainer.querySelector('span.model-title');
  77897. if (element) {
  77898. element.innerHTML = this.configuration.model.title;
  77899. }
  77900. }
  77901. if (this.configuration.model.subtitle) {
  77902. var element = metadataContainer.querySelector('span.model-subtitle');
  77903. if (element) {
  77904. element.innerHTML = this.configuration.model.subtitle;
  77905. }
  77906. }
  77907. if (this.configuration.model.thumbnail) {
  77908. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + this.configuration.model.thumbnail + "')";
  77909. }
  77910. }
  77911. };
  77912. DefaultViewer.prototype.initEnvironment = function () {
  77913. if (this.configuration.skybox) {
  77914. var texture = void 0;
  77915. if (this.configuration.skybox.cubeTexture) {
  77916. if (typeof this.configuration.skybox.cubeTexture.url === 'string') {
  77917. texture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(this.configuration.skybox.cubeTexture.url, this.scene);
  77918. }
  77919. else {
  77920. texture = babylonjs_1.CubeTexture.CreateFromImages(this.configuration.skybox.cubeTexture.url, this.scene, this.configuration.skybox.cubeTexture.noMipMap);
  77921. }
  77922. }
  77923. if (texture) {
  77924. this.extendClassWithConfig(texture, this.configuration.skybox.cubeTexture);
  77925. var scale = this.configuration.skybox.scale || this.scene.activeCamera && (this.scene.activeCamera.maxZ - this.scene.activeCamera.minZ) / 2 || 1;
  77926. var box = this.scene.createDefaultSkybox(texture, this.configuration.skybox.pbr, scale, this.configuration.skybox.blur);
  77927. if (this.configuration.skybox.material && this.configuration.skybox.material.imageProcessingConfiguration && box) {
  77928. box.material.imageProcessingConfiguration = new babylonjs_1.ImageProcessingConfiguration();
  77929. }
  77930. this.extendClassWithConfig(box, this.configuration.skybox);
  77931. }
  77932. }
  77933. if (this.configuration.ground) {
  77934. var groundConfig = (typeof this.configuration.ground === 'boolean') ? {} : this.configuration.ground;
  77935. var ground = babylonjs_1.Mesh.CreateGround('ground', groundConfig.size || 1000, groundConfig.size || 1000, 8, this.scene);
  77936. if (this.configuration.ground === true || groundConfig.shadowOnly) {
  77937. ground.material = new babylonjs_1.ShadowOnlyMaterial('groundmat', this.scene);
  77938. }
  77939. else {
  77940. ground.material = new babylonjs_1.StandardMaterial('groundmat', this.scene);
  77941. }
  77942. if (this.configuration.ground === true) {
  77943. ground.receiveShadows = true;
  77944. ground.material.alpha = 0.4;
  77945. }
  77946. this.extendClassWithConfig(ground, groundConfig);
  77947. }
  77948. return Promise.resolve(this.scene);
  77949. };
  77950. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  77951. var _this = this;
  77952. var template = this.templateManager.getTemplate('overlay');
  77953. if (!template)
  77954. return Promise.reject('Overlay template not found');
  77955. return template.show((function (template) {
  77956. var canvasRect = _this.containerElement.getBoundingClientRect();
  77957. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  77958. template.parent.style.display = 'flex';
  77959. template.parent.style.width = canvasRect.width + "px";
  77960. template.parent.style.height = canvasRect.height + "px";
  77961. template.parent.style.opacity = "1";
  77962. var subTemplate = _this.templateManager.getTemplate(subScreen);
  77963. if (!subTemplate) {
  77964. return Promise.reject(subScreen + ' template not found');
  77965. }
  77966. return subTemplate.show((function (template) {
  77967. template.parent.style.display = 'flex';
  77968. return Promise.resolve(template);
  77969. }));
  77970. }));
  77971. };
  77972. DefaultViewer.prototype.hideOverlayScreen = function () {
  77973. var template = this.templateManager.getTemplate('overlay');
  77974. if (!template)
  77975. return Promise.reject('Overlay template not found');
  77976. return template.hide((function (template) {
  77977. template.parent.style.opacity = "0";
  77978. var onTransitionEnd = function () {
  77979. template.parent.removeEventListener("transitionend", onTransitionEnd);
  77980. template.parent.style.display = 'none';
  77981. };
  77982. template.parent.addEventListener("transitionend", onTransitionEnd);
  77983. var overlays = template.parent.querySelectorAll('.overlay');
  77984. if (overlays) {
  77985. for (var i = 0; i < overlays.length; ++i) {
  77986. var htmlElement = overlays.item(i);
  77987. htmlElement.style.display = 'none';
  77988. }
  77989. }
  77990. return Promise.resolve(template);
  77991. }));
  77992. };
  77993. DefaultViewer.prototype.showLoadingScreen = function () {
  77994. var _this = this;
  77995. var template = this.templateManager.getTemplate('loadingScreen');
  77996. if (!template)
  77997. return Promise.reject('oading Screen template not found');
  77998. return template.show((function (template) {
  77999. var canvasRect = _this.containerElement.getBoundingClientRect();
  78000. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  78001. template.parent.style.display = 'flex';
  78002. template.parent.style.width = canvasRect.width + "px";
  78003. template.parent.style.height = canvasRect.height + "px";
  78004. template.parent.style.opacity = "1";
  78005. template.parent.style.backgroundColor = "black";
  78006. return Promise.resolve(template);
  78007. }));
  78008. };
  78009. DefaultViewer.prototype.hideLoadingScreen = function () {
  78010. var template = this.templateManager.getTemplate('loadingScreen');
  78011. if (!template)
  78012. return Promise.reject('oading Screen template not found');
  78013. return template.hide((function (template) {
  78014. template.parent.style.opacity = "0";
  78015. var onTransitionEnd = function () {
  78016. template.parent.removeEventListener("transitionend", onTransitionEnd);
  78017. template.parent.style.display = 'none';
  78018. };
  78019. template.parent.addEventListener("transitionend", onTransitionEnd);
  78020. return Promise.resolve(template);
  78021. }));
  78022. };
  78023. DefaultViewer.prototype.setupLights = function (focusMeshes) {
  78024. var _this = this;
  78025. if (focusMeshes === void 0) { focusMeshes = []; }
  78026. var sceneConfig = this.configuration.scene || { defaultLight: true };
  78027. if (!sceneConfig.defaultLight && (this.configuration.lights && Object.keys(this.configuration.lights).length)) {
  78028. this.scene.lights.forEach(function (l) {
  78029. l.dispose();
  78030. });
  78031. Object.keys(this.configuration.lights).forEach(function (name, idx) {
  78032. var lightConfig = _this.configuration.lights && _this.configuration.lights[name] || { name: name, type: 0 };
  78033. lightConfig.name = name;
  78034. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  78035. if (!constructor)
  78036. return;
  78037. var light = constructor();
  78038. if (light.isEnabled() !== !lightConfig.disabled) {
  78039. light.setEnabled(!lightConfig.disabled);
  78040. }
  78041. _this.extendClassWithConfig(light, lightConfig);
  78042. if (light instanceof babylonjs_1.ShadowLight) {
  78043. if (lightConfig.shadowEnabled) {
  78044. var shadowGenerator = new BABYLON.ShadowGenerator(512, light);
  78045. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  78046. var shadownMap = shadowGenerator.getShadowMap();
  78047. if (!shadownMap)
  78048. return;
  78049. var renderList = shadownMap.renderList;
  78050. for (var index = 0; index < focusMeshes.length; index++) {
  78051. renderList && renderList.push(focusMeshes[index]);
  78052. }
  78053. }
  78054. }
  78055. });
  78056. }
  78057. };
  78058. DefaultViewer.prototype.setupCamera = function (focusMeshes) {
  78059. if (focusMeshes === void 0) { focusMeshes = []; }
  78060. var cameraConfig = this.configuration.camera || {};
  78061. var sceneConfig = this.configuration.scene || { autoRotate: false, defaultCamera: true };
  78062. if (!this.configuration.camera && sceneConfig.defaultCamera) {
  78063. if (sceneConfig.autoRotate) {
  78064. this.camera.useAutoRotationBehavior = true;
  78065. }
  78066. return;
  78067. }
  78068. if (cameraConfig.position) {
  78069. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  78070. }
  78071. if (cameraConfig.rotation) {
  78072. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  78073. }
  78074. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  78075. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  78076. if (cameraConfig.behaviors) {
  78077. for (var name_1 in cameraConfig.behaviors) {
  78078. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  78079. }
  78080. }
  78081. ;
  78082. if (sceneConfig.autoRotate) {
  78083. this.camera.useAutoRotationBehavior = true;
  78084. }
  78085. };
  78086. DefaultViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  78087. var behavior;
  78088. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  78089. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  78090. switch (type) {
  78091. case 0:
  78092. behavior = new babylonjs_1.AutoRotationBehavior();
  78093. break;
  78094. case 1:
  78095. behavior = new babylonjs_1.BouncingBehavior();
  78096. break;
  78097. case 2:
  78098. behavior = new babylonjs_1.FramingBehavior();
  78099. break;
  78100. default:
  78101. behavior = null;
  78102. break;
  78103. }
  78104. if (behavior) {
  78105. if (typeof behaviorConfig === "object") {
  78106. this.extendClassWithConfig(behavior, behaviorConfig);
  78107. }
  78108. this.camera.addBehavior(behavior);
  78109. }
  78110. switch (type) {
  78111. case 0:
  78112. break;
  78113. case 1:
  78114. break;
  78115. case 2:
  78116. if (config.zoomOnBoundingInfo) {
  78117. var meshes = payload;
  78118. var bounding = meshes[0].getHierarchyBoundingVectors();
  78119. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  78120. }
  78121. break;
  78122. }
  78123. };
  78124. DefaultViewer.prototype.extendClassWithConfig = function (object, config) {
  78125. var _this = this;
  78126. if (!config)
  78127. return;
  78128. Object.keys(config).forEach(function (key) {
  78129. if (key in object && typeof object[key] !== 'function') {
  78130. if (typeof object[key] === 'function')
  78131. return;
  78132. if (typeof object[key] === 'object') {
  78133. _this.extendClassWithConfig(object[key], config[key]);
  78134. }
  78135. else {
  78136. object[key] = config[key];
  78137. }
  78138. }
  78139. });
  78140. };
  78141. return DefaultViewer;
  78142. }(viewer_1.AbstractViewer));
  78143. exports.DefaultViewer = DefaultViewer;
  78144. /***/ }),
  78145. /* 6 */
  78146. /***/ (function(module, exports, __webpack_require__) {
  78147. "use strict";
  78148. Object.defineProperty(exports, "__esModule", { value: true });
  78149. var viewerManager_1 = __webpack_require__(4);
  78150. var templateManager_1 = __webpack_require__(17);
  78151. var loader_1 = __webpack_require__(19);
  78152. var babylonjs_1 = __webpack_require__(0);
  78153. var promiseObservable_1 = __webpack_require__(28);
  78154. var AbstractViewer = (function () {
  78155. function AbstractViewer(containerElement, initialConfiguration) {
  78156. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  78157. var _this = this;
  78158. this.containerElement = containerElement;
  78159. if (containerElement.id) {
  78160. this.baseId = containerElement.id;
  78161. }
  78162. else {
  78163. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  78164. }
  78165. this.onSceneInitObservable = new promiseObservable_1.PromiseObservable();
  78166. this.onEngineInitObservable = new promiseObservable_1.PromiseObservable();
  78167. this.onModelLoadedObservable = new promiseObservable_1.PromiseObservable();
  78168. viewerManager_1.viewerManager.addViewer(this);
  78169. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  78170. this.prepareContainerElement();
  78171. loader_1.default.loadConfiguration(initialConfiguration).then(function (configuration) {
  78172. _this.configuration = configuration;
  78173. if (_this.configuration.observers) {
  78174. if (_this.configuration.observers.onEngineInit) {
  78175. _this.onEngineInitObservable.add(window[_this.configuration.observers.onEngineInit]);
  78176. }
  78177. if (_this.configuration.observers.onSceneInit) {
  78178. _this.onSceneInitObservable.add(window[_this.configuration.observers.onSceneInit]);
  78179. }
  78180. if (_this.configuration.observers.onModelLoaded) {
  78181. _this.onModelLoadedObservable.add(window[_this.configuration.observers.onModelLoaded]);
  78182. }
  78183. }
  78184. var templateConfiguration = _this.configuration.templates || {};
  78185. _this.templateManager.initTemplate(templateConfiguration);
  78186. _this.templateManager.onAllLoaded.add(function () {
  78187. _this.onTemplatesLoaded();
  78188. });
  78189. });
  78190. }
  78191. AbstractViewer.prototype.getBaseId = function () {
  78192. return this.baseId;
  78193. };
  78194. AbstractViewer.prototype.onTemplatesLoaded = function () {
  78195. var _this = this;
  78196. return this.initEngine().then(function () {
  78197. return _this.loadModel();
  78198. }).then(function () {
  78199. return _this;
  78200. });
  78201. };
  78202. AbstractViewer.prototype.initEngine = function () {
  78203. var _this = this;
  78204. var canvasElement = this.templateManager.getCanvas();
  78205. if (!canvasElement) {
  78206. return Promise.reject('Canvas element not found!');
  78207. }
  78208. var config = this.configuration.engine || {};
  78209. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing);
  78210. babylonjs_1.Database.IDBStorageEnabled = false;
  78211. window.addEventListener('resize', function () {
  78212. _this.engine.resize();
  78213. });
  78214. this.engine.runRenderLoop(function () {
  78215. _this.scene && _this.scene.render();
  78216. });
  78217. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  78218. this.engine.setHardwareScalingLevel(scale);
  78219. return this.onEngineInitObservable.notifyWithPromise(this.engine).then(function () {
  78220. return _this.engine;
  78221. });
  78222. };
  78223. AbstractViewer.prototype.initScene = function () {
  78224. var _this = this;
  78225. if (this.scene) {
  78226. this.scene.dispose();
  78227. }
  78228. this.scene = new babylonjs_1.Scene(this.engine);
  78229. this.scene.createDefaultCameraOrLight(true, true, true);
  78230. if (this.configuration.scene && this.configuration.scene.debug) {
  78231. this.scene.debugLayer.show();
  78232. }
  78233. return this.onSceneInitObservable.notifyWithPromise(this.scene).then(function () {
  78234. return _this.scene;
  78235. });
  78236. };
  78237. AbstractViewer.prototype.loadModel = function (model, clearScene) {
  78238. var _this = this;
  78239. if (model === void 0) { model = this.configuration.model; }
  78240. if (clearScene === void 0) { clearScene = true; }
  78241. var modelUrl = (typeof model === 'string') ? model : model.url;
  78242. var parts = modelUrl.split('/');
  78243. var filename = parts.pop();
  78244. var base = parts.join('/') + '/';
  78245. var plugin = (typeof model === 'string') ? undefined : model.loader;
  78246. return Promise.resolve().then(function () {
  78247. if (!_this.scene || clearScene)
  78248. return _this.initScene();
  78249. else
  78250. return _this.scene;
  78251. }).then(function () {
  78252. return new Promise(function (resolve, reject) {
  78253. babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, _this.scene, function (meshes) {
  78254. resolve(meshes);
  78255. }, undefined, function (e, m, exception) {
  78256. console.log(m, exception);
  78257. reject(m);
  78258. }, plugin);
  78259. });
  78260. }).then(function (meshes) {
  78261. return _this.onModelLoadedObservable.notifyWithPromise(meshes).then(function () {
  78262. return _this.scene;
  78263. });
  78264. });
  78265. };
  78266. return AbstractViewer;
  78267. }());
  78268. exports.AbstractViewer = AbstractViewer;
  78269. /***/ }),
  78270. /* 7 */
  78271. /***/ (function(module, exports) {
  78272. module.exports = "<viewer></viewer>\r\n<loading-screen></loading-screen>\r\n<overlay></overlay>";
  78273. /***/ }),
  78274. /* 8 */
  78275. /***/ (function(module, exports) {
  78276. module.exports = "<style>\r\n /* Loading Screen element */\r\n\r\n loading-screen {\r\n position: absolute;\r\n z-index: 100;\r\n opacity: 1;\r\n pointer-events: none;\r\n display: flex;\r\n justify-content: center;\r\n align-items: center;\r\n -webkit-transition: opacity 2s ease;\r\n -moz-transition: opacity 2s ease;\r\n transition: opacity 2s ease;\r\n }\r\n\r\n img.loading-image {\r\n -webkit-animation: spin 2s linear infinite;\r\n animation: spin 2s linear infinite;\r\n }\r\n\r\n @-webkit-keyframes spin {\r\n 0% {\r\n -webkit-transform: rotate(0deg);\r\n }\r\n 100% {\r\n -webkit-transform: rotate(360deg);\r\n }\r\n }\r\n\r\n @keyframes spin {\r\n 0% {\r\n transform: rotate(0deg);\r\n }\r\n 100% {\r\n transform: rotate(360deg);\r\n }\r\n }\r\n</style>\r\n\r\n<img class=\"loading-image\" src=\"{{loadingImage}}\">";
  78277. /***/ }),
  78278. /* 9 */
  78279. /***/ (function(module, exports) {
  78280. module.exports = "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"
  78281. /***/ }),
  78282. /* 10 */
  78283. /***/ (function(module, exports) {
  78284. module.exports = "<style>\r\n viewer {\r\n position: relative;\r\n overflow: hidden;\r\n /* Start stage */\r\n flex: 1;\r\n z-index: 1;\r\n justify-content: center;\r\n align-items: center;\r\n\r\n width: 100%;\r\n height: 100%;\r\n }\r\n\r\n .babylonjs-canvas {\r\n flex: 1;\r\n width: 100%;\r\n height: 100%;\r\n touch-action: none;\r\n }\r\n</style>\r\n\r\n<canvas class=\"babylonjs-canvas\" id=\"{{canvasId}}\">\r\n</canvas>\r\n\r\n<nav-bar></nav-bar>";
  78285. /***/ }),
  78286. /* 11 */
  78287. /***/ (function(module, exports) {
  78288. module.exports = "<style>\r\n overlay {\r\n position: absolute;\r\n z-index: 99;\r\n opacity: 0;\r\n display: flex;\r\n justify-content: center;\r\n align-items: center;\r\n -webkit-transition: opacity 1s ease;\r\n -moz-transition: opacity 1s ease;\r\n transition: opacity 1s ease;\r\n }\r\n\r\n .overlay-item {\r\n width: 100%;\r\n height: 100%;\r\n display: none;\r\n align-items: center;\r\n justify-content: center;\r\n background-color: rgba(121, 121, 121, 0.3);\r\n }\r\n\r\n error.overlay-item {\r\n background-color: rgba(121, 121, 121, 1);\r\n }\r\n\r\n div#close-button {\r\n position: absolute;\r\n top: 10px;\r\n right: 10px;\r\n width: 30px;\r\n height: 30px;\r\n cursor: pointer;\r\n }\r\n\r\n div#close-button img {\r\n width: 100%;\r\n }\r\n</style>\r\n\r\n<div id=\"close-button\">\r\n <img src=\"{{closeImage}}\" alt=\"{{closeText}}\">\r\n</div>\r\n<help class=\"overlay-item\"></help>\r\n<error class=\"overlay-item\"></error>\r\n<share class=\"overlay-item\"></share>";
  78289. /***/ }),
  78290. /* 12 */
  78291. /***/ (function(module, exports) {
  78292. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAAASAAAAEgARslrPgAAAPpJREFUaN7tmEEOgjAQAFHwh4SD/s5IPPBDMRkPlqQhYCzdtYvZORJTZtrAEqvKcRzHcZydANTAFbgorN0Cd+CkKd/z5ikZEeTHsPagEhHJT4xAJ7BuF8lP9BoBLfCY3SjrJGY7H695Fg+Qjvi5vGREMXmJiOLyORFm5LdEmJNPiTAr/02EefkoYmkgjSvXsgegVsTSSdje+YQIFfmjUsch8boNVh7Y5GFXSn6/D/GnV2XKsDMnP/uNvYiUIWUuYsuENROxRd5MRI588QgJ+WIRkvJFIviDv1Vq4Cax8wtrxycxAI14QLhRE05C/FMgnESvJu84juM4jgIvJPHlXUrVOPYAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTctMTAtMzBUMTA6NTQ6NDArMDA6MDBIpOL5AAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE3LTEwLTMwVDEwOjU0OjQwKzAwOjAwOflaRQAAACh0RVh0c3ZnOmJhc2UtdXJpAGZpbGU6Ly8vdG1wL21hZ2ljay1GZmF2R0Zvc8JGurIAAAAASUVORK5CYII="
  78293. /***/ }),
  78294. /* 13 */
  78295. /***/ (function(module, exports) {
  78296. module.exports = "Error loading the model";
  78297. /***/ }),
  78298. /* 14 */
  78299. /***/ (function(module, exports, __webpack_require__) {
  78300. "use strict";
  78301. /* WEBPACK VAR INJECTION */(function(global) {
  78302. Object.defineProperty(exports, "__esModule", { value: true });
  78303. var mappers_1 = __webpack_require__(2);
  78304. exports.mapperManager = mappers_1.mapperManager;
  78305. var viewerManager_1 = __webpack_require__(4);
  78306. exports.viewerManager = viewerManager_1.viewerManager;
  78307. var defaultViewer_1 = __webpack_require__(5);
  78308. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  78309. var viewer_1 = __webpack_require__(6);
  78310. exports.AbstractViewer = viewer_1.AbstractViewer;
  78311. __webpack_require__(0);
  78312. __webpack_require__(29);
  78313. __webpack_require__(30);
  78314. var initializer_1 = __webpack_require__(31);
  78315. exports.InitTags = initializer_1.InitTags;
  78316. global.Promise = Promise || __webpack_require__(32).Promise;
  78317. exports.disableInit = false;
  78318. setTimeout(function () {
  78319. if (exports.disableInit)
  78320. return;
  78321. initializer_1.InitTags();
  78322. });
  78323. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
  78324. /***/ }),
  78325. /* 15 */
  78326. /***/ (function(module, exports, __webpack_require__) {
  78327. var require;var require;/*
  78328. * Copyright (c) 2015 cannon.js Authors
  78329. *
  78330. * Permission is hereby granted, free of charge, to any person
  78331. * obtaining a copy of this software and associated documentation
  78332. * files (the "Software"), to deal in the Software without
  78333. * restriction, including without limitation the rights to use, copy,
  78334. * modify, merge, publish, distribute, sublicense, and/or sell copies
  78335. * of the Software, and to permit persons to whom the Software is
  78336. * furnished to do so, subject to the following conditions:
  78337. *
  78338. * The above copyright notice and this permission notice shall be
  78339. * included in all copies or substantial portions of the Software.
  78340. *
  78341. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  78342. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  78343. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  78344. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  78345. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  78346. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  78347. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  78348. */
  78349. !function(e){if(true)module.exports=e();else if("function"==typeof define&&false)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.CANNON=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return require(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  78350. module.exports={
  78351. "name": "cannon",
  78352. "version": "0.6.2",
  78353. "description": "A lightweight 3D physics engine written in JavaScript.",
  78354. "homepage": "https://github.com/schteppe/cannon.js",
  78355. "author": "Stefan Hedman <schteppe@gmail.com> (http://steffe.se)",
  78356. "keywords": [
  78357. "cannon.js",
  78358. "cannon",
  78359. "physics",
  78360. "engine",
  78361. "3d"
  78362. ],
  78363. "main": "./build/cannon.js",
  78364. "engines": {
  78365. "node": "*"
  78366. },
  78367. "repository": {
  78368. "type": "git",
  78369. "url": "https://github.com/schteppe/cannon.js.git"
  78370. },
  78371. "bugs": {
  78372. "url": "https://github.com/schteppe/cannon.js/issues"
  78373. },
  78374. "licenses": [
  78375. {
  78376. "type": "MIT"
  78377. }
  78378. ],
  78379. "devDependencies": {
  78380. "jshint": "latest",
  78381. "uglify-js": "latest",
  78382. "nodeunit": "^0.9.0",
  78383. "grunt": "~0.4.0",
  78384. "grunt-contrib-jshint": "~0.1.1",
  78385. "grunt-contrib-nodeunit": "^0.4.1",
  78386. "grunt-contrib-concat": "~0.1.3",
  78387. "grunt-contrib-uglify": "^0.5.1",
  78388. "grunt-browserify": "^2.1.4",
  78389. "grunt-contrib-yuidoc": "^0.5.2",
  78390. "browserify": "*"
  78391. },
  78392. "dependencies": {}
  78393. }
  78394. },{}],2:[function(_dereq_,module,exports){
  78395. // Export classes
  78396. module.exports = {
  78397. version : _dereq_('../package.json').version,
  78398. AABB : _dereq_('./collision/AABB'),
  78399. ArrayCollisionMatrix : _dereq_('./collision/ArrayCollisionMatrix'),
  78400. Body : _dereq_('./objects/Body'),
  78401. Box : _dereq_('./shapes/Box'),
  78402. Broadphase : _dereq_('./collision/Broadphase'),
  78403. Constraint : _dereq_('./constraints/Constraint'),
  78404. ContactEquation : _dereq_('./equations/ContactEquation'),
  78405. Narrowphase : _dereq_('./world/Narrowphase'),
  78406. ConeTwistConstraint : _dereq_('./constraints/ConeTwistConstraint'),
  78407. ContactMaterial : _dereq_('./material/ContactMaterial'),
  78408. ConvexPolyhedron : _dereq_('./shapes/ConvexPolyhedron'),
  78409. Cylinder : _dereq_('./shapes/Cylinder'),
  78410. DistanceConstraint : _dereq_('./constraints/DistanceConstraint'),
  78411. Equation : _dereq_('./equations/Equation'),
  78412. EventTarget : _dereq_('./utils/EventTarget'),
  78413. FrictionEquation : _dereq_('./equations/FrictionEquation'),
  78414. GSSolver : _dereq_('./solver/GSSolver'),
  78415. GridBroadphase : _dereq_('./collision/GridBroadphase'),
  78416. Heightfield : _dereq_('./shapes/Heightfield'),
  78417. HingeConstraint : _dereq_('./constraints/HingeConstraint'),
  78418. LockConstraint : _dereq_('./constraints/LockConstraint'),
  78419. Mat3 : _dereq_('./math/Mat3'),
  78420. Material : _dereq_('./material/Material'),
  78421. NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'),
  78422. ObjectCollisionMatrix : _dereq_('./collision/ObjectCollisionMatrix'),
  78423. Pool : _dereq_('./utils/Pool'),
  78424. Particle : _dereq_('./shapes/Particle'),
  78425. Plane : _dereq_('./shapes/Plane'),
  78426. PointToPointConstraint : _dereq_('./constraints/PointToPointConstraint'),
  78427. Quaternion : _dereq_('./math/Quaternion'),
  78428. Ray : _dereq_('./collision/Ray'),
  78429. RaycastVehicle : _dereq_('./objects/RaycastVehicle'),
  78430. RaycastResult : _dereq_('./collision/RaycastResult'),
  78431. RigidVehicle : _dereq_('./objects/RigidVehicle'),
  78432. RotationalEquation : _dereq_('./equations/RotationalEquation'),
  78433. RotationalMotorEquation : _dereq_('./equations/RotationalMotorEquation'),
  78434. SAPBroadphase : _dereq_('./collision/SAPBroadphase'),
  78435. SPHSystem : _dereq_('./objects/SPHSystem'),
  78436. Shape : _dereq_('./shapes/Shape'),
  78437. Solver : _dereq_('./solver/Solver'),
  78438. Sphere : _dereq_('./shapes/Sphere'),
  78439. SplitSolver : _dereq_('./solver/SplitSolver'),
  78440. Spring : _dereq_('./objects/Spring'),
  78441. Trimesh : _dereq_('./shapes/Trimesh'),
  78442. Vec3 : _dereq_('./math/Vec3'),
  78443. Vec3Pool : _dereq_('./utils/Vec3Pool'),
  78444. World : _dereq_('./world/World'),
  78445. };
  78446. },{"../package.json":1,"./collision/AABB":3,"./collision/ArrayCollisionMatrix":4,"./collision/Broadphase":5,"./collision/GridBroadphase":6,"./collision/NaiveBroadphase":7,"./collision/ObjectCollisionMatrix":8,"./collision/Ray":9,"./collision/RaycastResult":10,"./collision/SAPBroadphase":11,"./constraints/ConeTwistConstraint":12,"./constraints/Constraint":13,"./constraints/DistanceConstraint":14,"./constraints/HingeConstraint":15,"./constraints/LockConstraint":16,"./constraints/PointToPointConstraint":17,"./equations/ContactEquation":19,"./equations/Equation":20,"./equations/FrictionEquation":21,"./equations/RotationalEquation":22,"./equations/RotationalMotorEquation":23,"./material/ContactMaterial":24,"./material/Material":25,"./math/Mat3":27,"./math/Quaternion":28,"./math/Vec3":30,"./objects/Body":31,"./objects/RaycastVehicle":32,"./objects/RigidVehicle":33,"./objects/SPHSystem":34,"./objects/Spring":35,"./shapes/Box":37,"./shapes/ConvexPolyhedron":38,"./shapes/Cylinder":39,"./shapes/Heightfield":40,"./shapes/Particle":41,"./shapes/Plane":42,"./shapes/Shape":43,"./shapes/Sphere":44,"./shapes/Trimesh":45,"./solver/GSSolver":46,"./solver/Solver":47,"./solver/SplitSolver":48,"./utils/EventTarget":49,"./utils/Pool":51,"./utils/Vec3Pool":54,"./world/Narrowphase":55,"./world/World":56}],3:[function(_dereq_,module,exports){
  78447. var Vec3 = _dereq_('../math/Vec3');
  78448. var Utils = _dereq_('../utils/Utils');
  78449. module.exports = AABB;
  78450. /**
  78451. * Axis aligned bounding box class.
  78452. * @class AABB
  78453. * @constructor
  78454. * @param {Object} [options]
  78455. * @param {Vec3} [options.upperBound]
  78456. * @param {Vec3} [options.lowerBound]
  78457. */
  78458. function AABB(options){
  78459. options = options || {};
  78460. /**
  78461. * The lower bound of the bounding box.
  78462. * @property lowerBound
  78463. * @type {Vec3}
  78464. */
  78465. this.lowerBound = new Vec3();
  78466. if(options.lowerBound){
  78467. this.lowerBound.copy(options.lowerBound);
  78468. }
  78469. /**
  78470. * The upper bound of the bounding box.
  78471. * @property upperBound
  78472. * @type {Vec3}
  78473. */
  78474. this.upperBound = new Vec3();
  78475. if(options.upperBound){
  78476. this.upperBound.copy(options.upperBound);
  78477. }
  78478. }
  78479. var tmp = new Vec3();
  78480. /**
  78481. * Set the AABB bounds from a set of points.
  78482. * @method setFromPoints
  78483. * @param {Array} points An array of Vec3's.
  78484. * @param {Vec3} position
  78485. * @param {Quaternion} quaternion
  78486. * @param {number} skinSize
  78487. * @return {AABB} The self object
  78488. */
  78489. AABB.prototype.setFromPoints = function(points, position, quaternion, skinSize){
  78490. var l = this.lowerBound,
  78491. u = this.upperBound,
  78492. q = quaternion;
  78493. // Set to the first point
  78494. l.copy(points[0]);
  78495. if(q){
  78496. q.vmult(l, l);
  78497. }
  78498. u.copy(l);
  78499. for(var i = 1; i<points.length; i++){
  78500. var p = points[i];
  78501. if(q){
  78502. q.vmult(p, tmp);
  78503. p = tmp;
  78504. }
  78505. if(p.x > u.x){ u.x = p.x; }
  78506. if(p.x < l.x){ l.x = p.x; }
  78507. if(p.y > u.y){ u.y = p.y; }
  78508. if(p.y < l.y){ l.y = p.y; }
  78509. if(p.z > u.z){ u.z = p.z; }
  78510. if(p.z < l.z){ l.z = p.z; }
  78511. }
  78512. // Add offset
  78513. if (position) {
  78514. position.vadd(l, l);
  78515. position.vadd(u, u);
  78516. }
  78517. if(skinSize){
  78518. l.x -= skinSize;
  78519. l.y -= skinSize;
  78520. l.z -= skinSize;
  78521. u.x += skinSize;
  78522. u.y += skinSize;
  78523. u.z += skinSize;
  78524. }
  78525. return this;
  78526. };
  78527. /**
  78528. * Copy bounds from an AABB to this AABB
  78529. * @method copy
  78530. * @param {AABB} aabb Source to copy from
  78531. * @return {AABB} The this object, for chainability
  78532. */
  78533. AABB.prototype.copy = function(aabb){
  78534. this.lowerBound.copy(aabb.lowerBound);
  78535. this.upperBound.copy(aabb.upperBound);
  78536. return this;
  78537. };
  78538. /**
  78539. * Clone an AABB
  78540. * @method clone
  78541. */
  78542. AABB.prototype.clone = function(){
  78543. return new AABB().copy(this);
  78544. };
  78545. /**
  78546. * Extend this AABB so that it covers the given AABB too.
  78547. * @method extend
  78548. * @param {AABB} aabb
  78549. */
  78550. AABB.prototype.extend = function(aabb){
  78551. // Extend lower bound
  78552. var l = aabb.lowerBound.x;
  78553. if(this.lowerBound.x > l){
  78554. this.lowerBound.x = l;
  78555. }
  78556. // Upper
  78557. var u = aabb.upperBound.x;
  78558. if(this.upperBound.x < u){
  78559. this.upperBound.x = u;
  78560. }
  78561. // Extend lower bound
  78562. var l = aabb.lowerBound.y;
  78563. if(this.lowerBound.y > l){
  78564. this.lowerBound.y = l;
  78565. }
  78566. // Upper
  78567. var u = aabb.upperBound.y;
  78568. if(this.upperBound.y < u){
  78569. this.upperBound.y = u;
  78570. }
  78571. // Extend lower bound
  78572. var l = aabb.lowerBound.z;
  78573. if(this.lowerBound.z > l){
  78574. this.lowerBound.z = l;
  78575. }
  78576. // Upper
  78577. var u = aabb.upperBound.z;
  78578. if(this.upperBound.z < u){
  78579. this.upperBound.z = u;
  78580. }
  78581. };
  78582. /**
  78583. * Returns true if the given AABB overlaps this AABB.
  78584. * @method overlaps
  78585. * @param {AABB} aabb
  78586. * @return {Boolean}
  78587. */
  78588. AABB.prototype.overlaps = function(aabb){
  78589. var l1 = this.lowerBound,
  78590. u1 = this.upperBound,
  78591. l2 = aabb.lowerBound,
  78592. u2 = aabb.upperBound;
  78593. // l2 u2
  78594. // |---------|
  78595. // |--------|
  78596. // l1 u1
  78597. return ((l2.x <= u1.x && u1.x <= u2.x) || (l1.x <= u2.x && u2.x <= u1.x)) &&
  78598. ((l2.y <= u1.y && u1.y <= u2.y) || (l1.y <= u2.y && u2.y <= u1.y)) &&
  78599. ((l2.z <= u1.z && u1.z <= u2.z) || (l1.z <= u2.z && u2.z <= u1.z));
  78600. };
  78601. /**
  78602. * Returns true if the given AABB is fully contained in this AABB.
  78603. * @method contains
  78604. * @param {AABB} aabb
  78605. * @return {Boolean}
  78606. */
  78607. AABB.prototype.contains = function(aabb){
  78608. var l1 = this.lowerBound,
  78609. u1 = this.upperBound,
  78610. l2 = aabb.lowerBound,
  78611. u2 = aabb.upperBound;
  78612. // l2 u2
  78613. // |---------|
  78614. // |---------------|
  78615. // l1 u1
  78616. return (
  78617. (l1.x <= l2.x && u1.x >= u2.x) &&
  78618. (l1.y <= l2.y && u1.y >= u2.y) &&
  78619. (l1.z <= l2.z && u1.z >= u2.z)
  78620. );
  78621. };
  78622. /**
  78623. * @method getCorners
  78624. * @param {Vec3} a
  78625. * @param {Vec3} b
  78626. * @param {Vec3} c
  78627. * @param {Vec3} d
  78628. * @param {Vec3} e
  78629. * @param {Vec3} f
  78630. * @param {Vec3} g
  78631. * @param {Vec3} h
  78632. */
  78633. AABB.prototype.getCorners = function(a, b, c, d, e, f, g, h){
  78634. var l = this.lowerBound,
  78635. u = this.upperBound;
  78636. a.copy(l);
  78637. b.set( u.x, l.y, l.z );
  78638. c.set( u.x, u.y, l.z );
  78639. d.set( l.x, u.y, u.z );
  78640. e.set( u.x, l.y, l.z );
  78641. f.set( l.x, u.y, l.z );
  78642. g.set( l.x, l.y, u.z );
  78643. h.copy(u);
  78644. };
  78645. var transformIntoFrame_corners = [
  78646. new Vec3(),
  78647. new Vec3(),
  78648. new Vec3(),
  78649. new Vec3(),
  78650. new Vec3(),
  78651. new Vec3(),
  78652. new Vec3(),
  78653. new Vec3()
  78654. ];
  78655. /**
  78656. * Get the representation of an AABB in another frame.
  78657. * @method toLocalFrame
  78658. * @param {Transform} frame
  78659. * @param {AABB} target
  78660. * @return {AABB} The "target" AABB object.
  78661. */
  78662. AABB.prototype.toLocalFrame = function(frame, target){
  78663. var corners = transformIntoFrame_corners;
  78664. var a = corners[0];
  78665. var b = corners[1];
  78666. var c = corners[2];
  78667. var d = corners[3];
  78668. var e = corners[4];
  78669. var f = corners[5];
  78670. var g = corners[6];
  78671. var h = corners[7];
  78672. // Get corners in current frame
  78673. this.getCorners(a, b, c, d, e, f, g, h);
  78674. // Transform them to new local frame
  78675. for(var i=0; i !== 8; i++){
  78676. var corner = corners[i];
  78677. frame.pointToLocal(corner, corner);
  78678. }
  78679. return target.setFromPoints(corners);
  78680. };
  78681. /**
  78682. * Get the representation of an AABB in the global frame.
  78683. * @method toWorldFrame
  78684. * @param {Transform} frame
  78685. * @param {AABB} target
  78686. * @return {AABB} The "target" AABB object.
  78687. */
  78688. AABB.prototype.toWorldFrame = function(frame, target){
  78689. var corners = transformIntoFrame_corners;
  78690. var a = corners[0];
  78691. var b = corners[1];
  78692. var c = corners[2];
  78693. var d = corners[3];
  78694. var e = corners[4];
  78695. var f = corners[5];
  78696. var g = corners[6];
  78697. var h = corners[7];
  78698. // Get corners in current frame
  78699. this.getCorners(a, b, c, d, e, f, g, h);
  78700. // Transform them to new local frame
  78701. for(var i=0; i !== 8; i++){
  78702. var corner = corners[i];
  78703. frame.pointToWorld(corner, corner);
  78704. }
  78705. return target.setFromPoints(corners);
  78706. };
  78707. },{"../math/Vec3":30,"../utils/Utils":53}],4:[function(_dereq_,module,exports){
  78708. module.exports = ArrayCollisionMatrix;
  78709. /**
  78710. * Collision "matrix". It's actually a triangular-shaped array of whether two bodies are touching this step, for reference next step
  78711. * @class ArrayCollisionMatrix
  78712. * @constructor
  78713. */
  78714. function ArrayCollisionMatrix() {
  78715. /**
  78716. * The matrix storage
  78717. * @property matrix
  78718. * @type {Array}
  78719. */
  78720. this.matrix = [];
  78721. }
  78722. /**
  78723. * Get an element
  78724. * @method get
  78725. * @param {Number} i
  78726. * @param {Number} j
  78727. * @return {Number}
  78728. */
  78729. ArrayCollisionMatrix.prototype.get = function(i, j) {
  78730. i = i.index;
  78731. j = j.index;
  78732. if (j > i) {
  78733. var temp = j;
  78734. j = i;
  78735. i = temp;
  78736. }
  78737. return this.matrix[(i*(i + 1)>>1) + j-1];
  78738. };
  78739. /**
  78740. * Set an element
  78741. * @method set
  78742. * @param {Number} i
  78743. * @param {Number} j
  78744. * @param {Number} value
  78745. */
  78746. ArrayCollisionMatrix.prototype.set = function(i, j, value) {
  78747. i = i.index;
  78748. j = j.index;
  78749. if (j > i) {
  78750. var temp = j;
  78751. j = i;
  78752. i = temp;
  78753. }
  78754. this.matrix[(i*(i + 1)>>1) + j-1] = value ? 1 : 0;
  78755. };
  78756. /**
  78757. * Sets all elements to zero
  78758. * @method reset
  78759. */
  78760. ArrayCollisionMatrix.prototype.reset = function() {
  78761. for (var i=0, l=this.matrix.length; i!==l; i++) {
  78762. this.matrix[i]=0;
  78763. }
  78764. };
  78765. /**
  78766. * Sets the max number of objects
  78767. * @method setNumObjects
  78768. * @param {Number} n
  78769. */
  78770. ArrayCollisionMatrix.prototype.setNumObjects = function(n) {
  78771. this.matrix.length = n*(n-1)>>1;
  78772. };
  78773. },{}],5:[function(_dereq_,module,exports){
  78774. var Body = _dereq_('../objects/Body');
  78775. var Vec3 = _dereq_('../math/Vec3');
  78776. var Quaternion = _dereq_('../math/Quaternion');
  78777. var Shape = _dereq_('../shapes/Shape');
  78778. var Plane = _dereq_('../shapes/Plane');
  78779. module.exports = Broadphase;
  78780. /**
  78781. * Base class for broadphase implementations
  78782. * @class Broadphase
  78783. * @constructor
  78784. * @author schteppe
  78785. */
  78786. function Broadphase(){
  78787. /**
  78788. * The world to search for collisions in.
  78789. * @property world
  78790. * @type {World}
  78791. */
  78792. this.world = null;
  78793. /**
  78794. * If set to true, the broadphase uses bounding boxes for intersection test, else it uses bounding spheres.
  78795. * @property useBoundingBoxes
  78796. * @type {Boolean}
  78797. */
  78798. this.useBoundingBoxes = false;
  78799. /**
  78800. * Set to true if the objects in the world moved.
  78801. * @property {Boolean} dirty
  78802. */
  78803. this.dirty = true;
  78804. }
  78805. /**
  78806. * Get the collision pairs from the world
  78807. * @method collisionPairs
  78808. * @param {World} world The world to search in
  78809. * @param {Array} p1 Empty array to be filled with body objects
  78810. * @param {Array} p2 Empty array to be filled with body objects
  78811. */
  78812. Broadphase.prototype.collisionPairs = function(world,p1,p2){
  78813. throw new Error("collisionPairs not implemented for this BroadPhase class!");
  78814. };
  78815. /**
  78816. * Check if a body pair needs to be intersection tested at all.
  78817. * @method needBroadphaseCollision
  78818. * @param {Body} bodyA
  78819. * @param {Body} bodyB
  78820. * @return {bool}
  78821. */
  78822. var Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC = Body.STATIC | Body.KINEMATIC;
  78823. Broadphase.prototype.needBroadphaseCollision = function(bodyA,bodyB){
  78824. // Check collision filter masks
  78825. if( (bodyA.collisionFilterGroup & bodyB.collisionFilterMask)===0 || (bodyB.collisionFilterGroup & bodyA.collisionFilterMask)===0){
  78826. return false;
  78827. }
  78828. // Check types
  78829. if(((bodyA.type & Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC)!==0 || bodyA.sleepState === Body.SLEEPING) &&
  78830. ((bodyB.type & Broadphase_needBroadphaseCollision_STATIC_OR_KINEMATIC)!==0 || bodyB.sleepState === Body.SLEEPING)) {
  78831. // Both bodies are static, kinematic or sleeping. Skip.
  78832. return false;
  78833. }
  78834. return true;
  78835. };
  78836. /**
  78837. * Check if the bounding volumes of two bodies intersect.
  78838. * @method intersectionTest
  78839. * @param {Body} bodyA
  78840. * @param {Body} bodyB
  78841. * @param {array} pairs1
  78842. * @param {array} pairs2
  78843. */
  78844. Broadphase.prototype.intersectionTest = function(bodyA, bodyB, pairs1, pairs2){
  78845. if(this.useBoundingBoxes){
  78846. this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2);
  78847. } else {
  78848. this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2);
  78849. }
  78850. };
  78851. /**
  78852. * Check if the bounding spheres of two bodies are intersecting.
  78853. * @method doBoundingSphereBroadphase
  78854. * @param {Body} bodyA
  78855. * @param {Body} bodyB
  78856. * @param {Array} pairs1 bodyA is appended to this array if intersection
  78857. * @param {Array} pairs2 bodyB is appended to this array if intersection
  78858. */
  78859. var Broadphase_collisionPairs_r = new Vec3(), // Temp objects
  78860. Broadphase_collisionPairs_normal = new Vec3(),
  78861. Broadphase_collisionPairs_quat = new Quaternion(),
  78862. Broadphase_collisionPairs_relpos = new Vec3();
  78863. Broadphase.prototype.doBoundingSphereBroadphase = function(bodyA,bodyB,pairs1,pairs2){
  78864. var r = Broadphase_collisionPairs_r;
  78865. bodyB.position.vsub(bodyA.position,r);
  78866. var boundingRadiusSum2 = Math.pow(bodyA.boundingRadius + bodyB.boundingRadius, 2);
  78867. var norm2 = r.norm2();
  78868. if(norm2 < boundingRadiusSum2){
  78869. pairs1.push(bodyA);
  78870. pairs2.push(bodyB);
  78871. }
  78872. };
  78873. /**
  78874. * Check if the bounding boxes of two bodies are intersecting.
  78875. * @method doBoundingBoxBroadphase
  78876. * @param {Body} bodyA
  78877. * @param {Body} bodyB
  78878. * @param {Array} pairs1
  78879. * @param {Array} pairs2
  78880. */
  78881. Broadphase.prototype.doBoundingBoxBroadphase = function(bodyA,bodyB,pairs1,pairs2){
  78882. if(bodyA.aabbNeedsUpdate){
  78883. bodyA.computeAABB();
  78884. }
  78885. if(bodyB.aabbNeedsUpdate){
  78886. bodyB.computeAABB();
  78887. }
  78888. // Check AABB / AABB
  78889. if(bodyA.aabb.overlaps(bodyB.aabb)){
  78890. pairs1.push(bodyA);
  78891. pairs2.push(bodyB);
  78892. }
  78893. };
  78894. /**
  78895. * Removes duplicate pairs from the pair arrays.
  78896. * @method makePairsUnique
  78897. * @param {Array} pairs1
  78898. * @param {Array} pairs2
  78899. */
  78900. var Broadphase_makePairsUnique_temp = { keys:[] },
  78901. Broadphase_makePairsUnique_p1 = [],
  78902. Broadphase_makePairsUnique_p2 = [];
  78903. Broadphase.prototype.makePairsUnique = function(pairs1,pairs2){
  78904. var t = Broadphase_makePairsUnique_temp,
  78905. p1 = Broadphase_makePairsUnique_p1,
  78906. p2 = Broadphase_makePairsUnique_p2,
  78907. N = pairs1.length;
  78908. for(var i=0; i!==N; i++){
  78909. p1[i] = pairs1[i];
  78910. p2[i] = pairs2[i];
  78911. }
  78912. pairs1.length = 0;
  78913. pairs2.length = 0;
  78914. for(var i=0; i!==N; i++){
  78915. var id1 = p1[i].id,
  78916. id2 = p2[i].id;
  78917. var key = id1 < id2 ? id1+","+id2 : id2+","+id1;
  78918. t[key] = i;
  78919. t.keys.push(key);
  78920. }
  78921. for(var i=0; i!==t.keys.length; i++){
  78922. var key = t.keys.pop(),
  78923. pairIndex = t[key];
  78924. pairs1.push(p1[pairIndex]);
  78925. pairs2.push(p2[pairIndex]);
  78926. delete t[key];
  78927. }
  78928. };
  78929. /**
  78930. * To be implemented by subcasses
  78931. * @method setWorld
  78932. * @param {World} world
  78933. */
  78934. Broadphase.prototype.setWorld = function(world){
  78935. };
  78936. /**
  78937. * Check if the bounding spheres of two bodies overlap.
  78938. * @method boundingSphereCheck
  78939. * @param {Body} bodyA
  78940. * @param {Body} bodyB
  78941. * @return {boolean}
  78942. */
  78943. var bsc_dist = new Vec3();
  78944. Broadphase.boundingSphereCheck = function(bodyA,bodyB){
  78945. var dist = bsc_dist;
  78946. bodyA.position.vsub(bodyB.position,dist);
  78947. return Math.pow(bodyA.shape.boundingSphereRadius + bodyB.shape.boundingSphereRadius,2) > dist.norm2();
  78948. };
  78949. /**
  78950. * Returns all the bodies within the AABB.
  78951. * @method aabbQuery
  78952. * @param {World} world
  78953. * @param {AABB} aabb
  78954. * @param {array} result An array to store resulting bodies in.
  78955. * @return {array}
  78956. */
  78957. Broadphase.prototype.aabbQuery = function(world, aabb, result){
  78958. console.warn('.aabbQuery is not implemented in this Broadphase subclass.');
  78959. return [];
  78960. };
  78961. },{"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Plane":42,"../shapes/Shape":43}],6:[function(_dereq_,module,exports){
  78962. module.exports = GridBroadphase;
  78963. var Broadphase = _dereq_('./Broadphase');
  78964. var Vec3 = _dereq_('../math/Vec3');
  78965. var Shape = _dereq_('../shapes/Shape');
  78966. /**
  78967. * Axis aligned uniform grid broadphase.
  78968. * @class GridBroadphase
  78969. * @constructor
  78970. * @extends Broadphase
  78971. * @todo Needs support for more than just planes and spheres.
  78972. * @param {Vec3} aabbMin
  78973. * @param {Vec3} aabbMax
  78974. * @param {Number} nx Number of boxes along x
  78975. * @param {Number} ny Number of boxes along y
  78976. * @param {Number} nz Number of boxes along z
  78977. */
  78978. function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){
  78979. Broadphase.apply(this);
  78980. this.nx = nx || 10;
  78981. this.ny = ny || 10;
  78982. this.nz = nz || 10;
  78983. this.aabbMin = aabbMin || new Vec3(100,100,100);
  78984. this.aabbMax = aabbMax || new Vec3(-100,-100,-100);
  78985. var nbins = this.nx * this.ny * this.nz;
  78986. if (nbins <= 0) {
  78987. throw "GridBroadphase: Each dimension's n must be >0";
  78988. }
  78989. this.bins = [];
  78990. this.binLengths = []; //Rather than continually resizing arrays (thrashing the memory), just record length and allow them to grow
  78991. this.bins.length = nbins;
  78992. this.binLengths.length = nbins;
  78993. for (var i=0;i<nbins;i++) {
  78994. this.bins[i]=[];
  78995. this.binLengths[i]=0;
  78996. }
  78997. }
  78998. GridBroadphase.prototype = new Broadphase();
  78999. GridBroadphase.prototype.constructor = GridBroadphase;
  79000. /**
  79001. * Get all the collision pairs in the physics world
  79002. * @method collisionPairs
  79003. * @param {World} world
  79004. * @param {Array} pairs1
  79005. * @param {Array} pairs2
  79006. */
  79007. var GridBroadphase_collisionPairs_d = new Vec3();
  79008. var GridBroadphase_collisionPairs_binPos = new Vec3();
  79009. GridBroadphase.prototype.collisionPairs = function(world,pairs1,pairs2){
  79010. var N = world.numObjects(),
  79011. bodies = world.bodies;
  79012. var max = this.aabbMax,
  79013. min = this.aabbMin,
  79014. nx = this.nx,
  79015. ny = this.ny,
  79016. nz = this.nz;
  79017. var xstep = ny*nz;
  79018. var ystep = nz;
  79019. var zstep = 1;
  79020. var xmax = max.x,
  79021. ymax = max.y,
  79022. zmax = max.z,
  79023. xmin = min.x,
  79024. ymin = min.y,
  79025. zmin = min.z;
  79026. var xmult = nx / (xmax-xmin),
  79027. ymult = ny / (ymax-ymin),
  79028. zmult = nz / (zmax-zmin);
  79029. var binsizeX = (xmax - xmin) / nx,
  79030. binsizeY = (ymax - ymin) / ny,
  79031. binsizeZ = (zmax - zmin) / nz;
  79032. var binRadius = Math.sqrt(binsizeX*binsizeX + binsizeY*binsizeY + binsizeZ*binsizeZ) * 0.5;
  79033. var types = Shape.types;
  79034. var SPHERE = types.SPHERE,
  79035. PLANE = types.PLANE,
  79036. BOX = types.BOX,
  79037. COMPOUND = types.COMPOUND,
  79038. CONVEXPOLYHEDRON = types.CONVEXPOLYHEDRON;
  79039. var bins=this.bins,
  79040. binLengths=this.binLengths,
  79041. Nbins=this.bins.length;
  79042. // Reset bins
  79043. for(var i=0; i!==Nbins; i++){
  79044. binLengths[i] = 0;
  79045. }
  79046. var ceil = Math.ceil;
  79047. var min = Math.min;
  79048. var max = Math.max;
  79049. function addBoxToBins(x0,y0,z0,x1,y1,z1,bi) {
  79050. var xoff0 = ((x0 - xmin) * xmult)|0,
  79051. yoff0 = ((y0 - ymin) * ymult)|0,
  79052. zoff0 = ((z0 - zmin) * zmult)|0,
  79053. xoff1 = ceil((x1 - xmin) * xmult),
  79054. yoff1 = ceil((y1 - ymin) * ymult),
  79055. zoff1 = ceil((z1 - zmin) * zmult);
  79056. if (xoff0 < 0) { xoff0 = 0; } else if (xoff0 >= nx) { xoff0 = nx - 1; }
  79057. if (yoff0 < 0) { yoff0 = 0; } else if (yoff0 >= ny) { yoff0 = ny - 1; }
  79058. if (zoff0 < 0) { zoff0 = 0; } else if (zoff0 >= nz) { zoff0 = nz - 1; }
  79059. if (xoff1 < 0) { xoff1 = 0; } else if (xoff1 >= nx) { xoff1 = nx - 1; }
  79060. if (yoff1 < 0) { yoff1 = 0; } else if (yoff1 >= ny) { yoff1 = ny - 1; }
  79061. if (zoff1 < 0) { zoff1 = 0; } else if (zoff1 >= nz) { zoff1 = nz - 1; }
  79062. xoff0 *= xstep;
  79063. yoff0 *= ystep;
  79064. zoff0 *= zstep;
  79065. xoff1 *= xstep;
  79066. yoff1 *= ystep;
  79067. zoff1 *= zstep;
  79068. for (var xoff = xoff0; xoff <= xoff1; xoff += xstep) {
  79069. for (var yoff = yoff0; yoff <= yoff1; yoff += ystep) {
  79070. for (var zoff = zoff0; zoff <= zoff1; zoff += zstep) {
  79071. var idx = xoff+yoff+zoff;
  79072. bins[idx][binLengths[idx]++] = bi;
  79073. }
  79074. }
  79075. }
  79076. }
  79077. // Put all bodies into the bins
  79078. for(var i=0; i!==N; i++){
  79079. var bi = bodies[i];
  79080. var si = bi.shape;
  79081. switch(si.type){
  79082. case SPHERE:
  79083. // Put in bin
  79084. // check if overlap with other bins
  79085. var x = bi.position.x,
  79086. y = bi.position.y,
  79087. z = bi.position.z;
  79088. var r = si.radius;
  79089. addBoxToBins(x-r, y-r, z-r, x+r, y+r, z+r, bi);
  79090. break;
  79091. case PLANE:
  79092. if(si.worldNormalNeedsUpdate){
  79093. si.computeWorldNormal(bi.quaternion);
  79094. }
  79095. var planeNormal = si.worldNormal;
  79096. //Relative position from origin of plane object to the first bin
  79097. //Incremented as we iterate through the bins
  79098. var xreset = xmin + binsizeX*0.5 - bi.position.x,
  79099. yreset = ymin + binsizeY*0.5 - bi.position.y,
  79100. zreset = zmin + binsizeZ*0.5 - bi.position.z;
  79101. var d = GridBroadphase_collisionPairs_d;
  79102. d.set(xreset, yreset, zreset);
  79103. for (var xi = 0, xoff = 0; xi !== nx; xi++, xoff += xstep, d.y = yreset, d.x += binsizeX) {
  79104. for (var yi = 0, yoff = 0; yi !== ny; yi++, yoff += ystep, d.z = zreset, d.y += binsizeY) {
  79105. for (var zi = 0, zoff = 0; zi !== nz; zi++, zoff += zstep, d.z += binsizeZ) {
  79106. if (d.dot(planeNormal) < binRadius) {
  79107. var idx = xoff + yoff + zoff;
  79108. bins[idx][binLengths[idx]++] = bi;
  79109. }
  79110. }
  79111. }
  79112. }
  79113. break;
  79114. default:
  79115. if (bi.aabbNeedsUpdate) {
  79116. bi.computeAABB();
  79117. }
  79118. addBoxToBins(
  79119. bi.aabb.lowerBound.x,
  79120. bi.aabb.lowerBound.y,
  79121. bi.aabb.lowerBound.z,
  79122. bi.aabb.upperBound.x,
  79123. bi.aabb.upperBound.y,
  79124. bi.aabb.upperBound.z,
  79125. bi);
  79126. break;
  79127. }
  79128. }
  79129. // Check each bin
  79130. for(var i=0; i!==Nbins; i++){
  79131. var binLength = binLengths[i];
  79132. //Skip bins with no potential collisions
  79133. if (binLength > 1) {
  79134. var bin = bins[i];
  79135. // Do N^2 broadphase inside
  79136. for(var xi=0; xi!==binLength; xi++){
  79137. var bi = bin[xi];
  79138. for(var yi=0; yi!==xi; yi++){
  79139. var bj = bin[yi];
  79140. if(this.needBroadphaseCollision(bi,bj)){
  79141. this.intersectionTest(bi,bj,pairs1,pairs2);
  79142. }
  79143. }
  79144. }
  79145. }
  79146. }
  79147. // for (var zi = 0, zoff=0; zi < nz; zi++, zoff+= zstep) {
  79148. // console.log("layer "+zi);
  79149. // for (var yi = 0, yoff=0; yi < ny; yi++, yoff += ystep) {
  79150. // var row = '';
  79151. // for (var xi = 0, xoff=0; xi < nx; xi++, xoff += xstep) {
  79152. // var idx = xoff + yoff + zoff;
  79153. // row += ' ' + binLengths[idx];
  79154. // }
  79155. // console.log(row);
  79156. // }
  79157. // }
  79158. this.makePairsUnique(pairs1,pairs2);
  79159. };
  79160. },{"../math/Vec3":30,"../shapes/Shape":43,"./Broadphase":5}],7:[function(_dereq_,module,exports){
  79161. module.exports = NaiveBroadphase;
  79162. var Broadphase = _dereq_('./Broadphase');
  79163. var AABB = _dereq_('./AABB');
  79164. /**
  79165. * Naive broadphase implementation, used in lack of better ones.
  79166. * @class NaiveBroadphase
  79167. * @constructor
  79168. * @description The naive broadphase looks at all possible pairs without restriction, therefore it has complexity N^2 (which is bad)
  79169. * @extends Broadphase
  79170. */
  79171. function NaiveBroadphase(){
  79172. Broadphase.apply(this);
  79173. }
  79174. NaiveBroadphase.prototype = new Broadphase();
  79175. NaiveBroadphase.prototype.constructor = NaiveBroadphase;
  79176. /**
  79177. * Get all the collision pairs in the physics world
  79178. * @method collisionPairs
  79179. * @param {World} world
  79180. * @param {Array} pairs1
  79181. * @param {Array} pairs2
  79182. */
  79183. NaiveBroadphase.prototype.collisionPairs = function(world,pairs1,pairs2){
  79184. var bodies = world.bodies,
  79185. n = bodies.length,
  79186. i,j,bi,bj;
  79187. // Naive N^2 ftw!
  79188. for(i=0; i!==n; i++){
  79189. for(j=0; j!==i; j++){
  79190. bi = bodies[i];
  79191. bj = bodies[j];
  79192. if(!this.needBroadphaseCollision(bi,bj)){
  79193. continue;
  79194. }
  79195. this.intersectionTest(bi,bj,pairs1,pairs2);
  79196. }
  79197. }
  79198. };
  79199. var tmpAABB = new AABB();
  79200. /**
  79201. * Returns all the bodies within an AABB.
  79202. * @method aabbQuery
  79203. * @param {World} world
  79204. * @param {AABB} aabb
  79205. * @param {array} result An array to store resulting bodies in.
  79206. * @return {array}
  79207. */
  79208. NaiveBroadphase.prototype.aabbQuery = function(world, aabb, result){
  79209. result = result || [];
  79210. for(var i = 0; i < world.bodies.length; i++){
  79211. var b = world.bodies[i];
  79212. if(b.aabbNeedsUpdate){
  79213. b.computeAABB();
  79214. }
  79215. // Ugly hack until Body gets aabb
  79216. if(b.aabb.overlaps(aabb)){
  79217. result.push(b);
  79218. }
  79219. }
  79220. return result;
  79221. };
  79222. },{"./AABB":3,"./Broadphase":5}],8:[function(_dereq_,module,exports){
  79223. module.exports = ObjectCollisionMatrix;
  79224. /**
  79225. * Records what objects are colliding with each other
  79226. * @class ObjectCollisionMatrix
  79227. * @constructor
  79228. */
  79229. function ObjectCollisionMatrix() {
  79230. /**
  79231. * The matrix storage
  79232. * @property matrix
  79233. * @type {Object}
  79234. */
  79235. this.matrix = {};
  79236. }
  79237. /**
  79238. * @method get
  79239. * @param {Number} i
  79240. * @param {Number} j
  79241. * @return {Number}
  79242. */
  79243. ObjectCollisionMatrix.prototype.get = function(i, j) {
  79244. i = i.id;
  79245. j = j.id;
  79246. if (j > i) {
  79247. var temp = j;
  79248. j = i;
  79249. i = temp;
  79250. }
  79251. return i+'-'+j in this.matrix;
  79252. };
  79253. /**
  79254. * @method set
  79255. * @param {Number} i
  79256. * @param {Number} j
  79257. * @param {Number} value
  79258. */
  79259. ObjectCollisionMatrix.prototype.set = function(i, j, value) {
  79260. i = i.id;
  79261. j = j.id;
  79262. if (j > i) {
  79263. var temp = j;
  79264. j = i;
  79265. i = temp;
  79266. }
  79267. if (value) {
  79268. this.matrix[i+'-'+j] = true;
  79269. }
  79270. else {
  79271. delete this.matrix[i+'-'+j];
  79272. }
  79273. };
  79274. /**
  79275. * Empty the matrix
  79276. * @method reset
  79277. */
  79278. ObjectCollisionMatrix.prototype.reset = function() {
  79279. this.matrix = {};
  79280. };
  79281. /**
  79282. * Set max number of objects
  79283. * @method setNumObjects
  79284. * @param {Number} n
  79285. */
  79286. ObjectCollisionMatrix.prototype.setNumObjects = function(n) {
  79287. };
  79288. },{}],9:[function(_dereq_,module,exports){
  79289. module.exports = Ray;
  79290. var Vec3 = _dereq_('../math/Vec3');
  79291. var Quaternion = _dereq_('../math/Quaternion');
  79292. var Transform = _dereq_('../math/Transform');
  79293. var ConvexPolyhedron = _dereq_('../shapes/ConvexPolyhedron');
  79294. var Box = _dereq_('../shapes/Box');
  79295. var RaycastResult = _dereq_('../collision/RaycastResult');
  79296. var Shape = _dereq_('../shapes/Shape');
  79297. var AABB = _dereq_('../collision/AABB');
  79298. /**
  79299. * A line in 3D space that intersects bodies and return points.
  79300. * @class Ray
  79301. * @constructor
  79302. * @param {Vec3} from
  79303. * @param {Vec3} to
  79304. */
  79305. function Ray(from, to){
  79306. /**
  79307. * @property {Vec3} from
  79308. */
  79309. this.from = from ? from.clone() : new Vec3();
  79310. /**
  79311. * @property {Vec3} to
  79312. */
  79313. this.to = to ? to.clone() : new Vec3();
  79314. /**
  79315. * @private
  79316. * @property {Vec3} _direction
  79317. */
  79318. this._direction = new Vec3();
  79319. /**
  79320. * The precision of the ray. Used when checking parallelity etc.
  79321. * @property {Number} precision
  79322. */
  79323. this.precision = 0.0001;
  79324. /**
  79325. * Set to true if you want the Ray to take .collisionResponse flags into account on bodies and shapes.
  79326. * @property {Boolean} checkCollisionResponse
  79327. */
  79328. this.checkCollisionResponse = true;
  79329. /**
  79330. * If set to true, the ray skips any hits with normal.dot(rayDirection) < 0.
  79331. * @property {Boolean} skipBackfaces
  79332. */
  79333. this.skipBackfaces = false;
  79334. /**
  79335. * @property {number} collisionFilterMask
  79336. * @default -1
  79337. */
  79338. this.collisionFilterMask = -1;
  79339. /**
  79340. * @property {number} collisionFilterGroup
  79341. * @default -1
  79342. */
  79343. this.collisionFilterGroup = -1;
  79344. /**
  79345. * The intersection mode. Should be Ray.ANY, Ray.ALL or Ray.CLOSEST.
  79346. * @property {number} mode
  79347. */
  79348. this.mode = Ray.ANY;
  79349. /**
  79350. * Current result object.
  79351. * @property {RaycastResult} result
  79352. */
  79353. this.result = new RaycastResult();
  79354. /**
  79355. * Will be set to true during intersectWorld() if the ray hit anything.
  79356. * @property {Boolean} hasHit
  79357. */
  79358. this.hasHit = false;
  79359. /**
  79360. * Current, user-provided result callback. Will be used if mode is Ray.ALL.
  79361. * @property {Function} callback
  79362. */
  79363. this.callback = function(result){};
  79364. }
  79365. Ray.prototype.constructor = Ray;
  79366. Ray.CLOSEST = 1;
  79367. Ray.ANY = 2;
  79368. Ray.ALL = 4;
  79369. var tmpAABB = new AABB();
  79370. var tmpArray = [];
  79371. /**
  79372. * Do itersection against all bodies in the given World.
  79373. * @method intersectWorld
  79374. * @param {World} world
  79375. * @param {object} options
  79376. * @return {Boolean} True if the ray hit anything, otherwise false.
  79377. */
  79378. Ray.prototype.intersectWorld = function (world, options) {
  79379. this.mode = options.mode || Ray.ANY;
  79380. this.result = options.result || new RaycastResult();
  79381. this.skipBackfaces = !!options.skipBackfaces;
  79382. this.collisionFilterMask = typeof(options.collisionFilterMask) !== 'undefined' ? options.collisionFilterMask : -1;
  79383. this.collisionFilterGroup = typeof(options.collisionFilterGroup) !== 'undefined' ? options.collisionFilterGroup : -1;
  79384. if(options.from){
  79385. this.from.copy(options.from);
  79386. }
  79387. if(options.to){
  79388. this.to.copy(options.to);
  79389. }
  79390. this.callback = options.callback || function(){};
  79391. this.hasHit = false;
  79392. this.result.reset();
  79393. this._updateDirection();
  79394. this.getAABB(tmpAABB);
  79395. tmpArray.length = 0;
  79396. world.broadphase.aabbQuery(world, tmpAABB, tmpArray);
  79397. this.intersectBodies(tmpArray);
  79398. return this.hasHit;
  79399. };
  79400. var v1 = new Vec3(),
  79401. v2 = new Vec3();
  79402. /*
  79403. * As per "Barycentric Technique" as named here http://www.blackpawn.com/texts/pointinpoly/default.html But without the division
  79404. */
  79405. Ray.pointInTriangle = pointInTriangle;
  79406. function pointInTriangle(p, a, b, c) {
  79407. c.vsub(a,v0);
  79408. b.vsub(a,v1);
  79409. p.vsub(a,v2);
  79410. var dot00 = v0.dot( v0 );
  79411. var dot01 = v0.dot( v1 );
  79412. var dot02 = v0.dot( v2 );
  79413. var dot11 = v1.dot( v1 );
  79414. var dot12 = v1.dot( v2 );
  79415. var u,v;
  79416. return ( (u = dot11 * dot02 - dot01 * dot12) >= 0 ) &&
  79417. ( (v = dot00 * dot12 - dot01 * dot02) >= 0 ) &&
  79418. ( u + v < ( dot00 * dot11 - dot01 * dot01 ) );
  79419. }
  79420. /**
  79421. * Shoot a ray at a body, get back information about the hit.
  79422. * @method intersectBody
  79423. * @private
  79424. * @param {Body} body
  79425. * @param {RaycastResult} [result] Deprecated - set the result property of the Ray instead.
  79426. */
  79427. var intersectBody_xi = new Vec3();
  79428. var intersectBody_qi = new Quaternion();
  79429. Ray.prototype.intersectBody = function (body, result) {
  79430. if(result){
  79431. this.result = result;
  79432. this._updateDirection();
  79433. }
  79434. var checkCollisionResponse = this.checkCollisionResponse;
  79435. if(checkCollisionResponse && !body.collisionResponse){
  79436. return;
  79437. }
  79438. if((this.collisionFilterGroup & body.collisionFilterMask)===0 || (body.collisionFilterGroup & this.collisionFilterMask)===0){
  79439. return;
  79440. }
  79441. var xi = intersectBody_xi;
  79442. var qi = intersectBody_qi;
  79443. for (var i = 0, N = body.shapes.length; i < N; i++) {
  79444. var shape = body.shapes[i];
  79445. if(checkCollisionResponse && !shape.collisionResponse){
  79446. continue; // Skip
  79447. }
  79448. body.quaternion.mult(body.shapeOrientations[i], qi);
  79449. body.quaternion.vmult(body.shapeOffsets[i], xi);
  79450. xi.vadd(body.position, xi);
  79451. this.intersectShape(
  79452. shape,
  79453. qi,
  79454. xi,
  79455. body
  79456. );
  79457. if(this.result._shouldStop){
  79458. break;
  79459. }
  79460. }
  79461. };
  79462. /**
  79463. * @method intersectBodies
  79464. * @param {Array} bodies An array of Body objects.
  79465. * @param {RaycastResult} [result] Deprecated
  79466. */
  79467. Ray.prototype.intersectBodies = function (bodies, result) {
  79468. if(result){
  79469. this.result = result;
  79470. this._updateDirection();
  79471. }
  79472. for ( var i = 0, l = bodies.length; !this.result._shouldStop && i < l; i ++ ) {
  79473. this.intersectBody(bodies[i]);
  79474. }
  79475. };
  79476. /**
  79477. * Updates the _direction vector.
  79478. * @private
  79479. * @method _updateDirection
  79480. */
  79481. Ray.prototype._updateDirection = function(){
  79482. this.to.vsub(this.from, this._direction);
  79483. this._direction.normalize();
  79484. };
  79485. /**
  79486. * @method intersectShape
  79487. * @private
  79488. * @param {Shape} shape
  79489. * @param {Quaternion} quat
  79490. * @param {Vec3} position
  79491. * @param {Body} body
  79492. */
  79493. Ray.prototype.intersectShape = function(shape, quat, position, body){
  79494. var from = this.from;
  79495. // Checking boundingSphere
  79496. var distance = distanceFromIntersection(from, this._direction, position);
  79497. if ( distance > shape.boundingSphereRadius ) {
  79498. return;
  79499. }
  79500. var intersectMethod = this[shape.type];
  79501. if(intersectMethod){
  79502. intersectMethod.call(this, shape, quat, position, body);
  79503. }
  79504. };
  79505. var vector = new Vec3();
  79506. var normal = new Vec3();
  79507. var intersectPoint = new Vec3();
  79508. var a = new Vec3();
  79509. var b = new Vec3();
  79510. var c = new Vec3();
  79511. var d = new Vec3();
  79512. var tmpRaycastResult = new RaycastResult();
  79513. /**
  79514. * @method intersectBox
  79515. * @private
  79516. * @param {Shape} shape
  79517. * @param {Quaternion} quat
  79518. * @param {Vec3} position
  79519. * @param {Body} body
  79520. */
  79521. Ray.prototype.intersectBox = function(shape, quat, position, body){
  79522. return this.intersectConvex(shape.convexPolyhedronRepresentation, quat, position, body);
  79523. };
  79524. Ray.prototype[Shape.types.BOX] = Ray.prototype.intersectBox;
  79525. /**
  79526. * @method intersectPlane
  79527. * @private
  79528. * @param {Shape} shape
  79529. * @param {Quaternion} quat
  79530. * @param {Vec3} position
  79531. * @param {Body} body
  79532. */
  79533. Ray.prototype.intersectPlane = function(shape, quat, position, body){
  79534. var from = this.from;
  79535. var to = this.to;
  79536. var direction = this._direction;
  79537. // Get plane normal
  79538. var worldNormal = new Vec3(0, 0, 1);
  79539. quat.vmult(worldNormal, worldNormal);
  79540. var len = new Vec3();
  79541. from.vsub(position, len);
  79542. var planeToFrom = len.dot(worldNormal);
  79543. to.vsub(position, len);
  79544. var planeToTo = len.dot(worldNormal);
  79545. if(planeToFrom * planeToTo > 0){
  79546. // "from" and "to" are on the same side of the plane... bail out
  79547. return;
  79548. }
  79549. if(from.distanceTo(to) < planeToFrom){
  79550. return;
  79551. }
  79552. var n_dot_dir = worldNormal.dot(direction);
  79553. if (Math.abs(n_dot_dir) < this.precision) {
  79554. // No intersection
  79555. return;
  79556. }
  79557. var planePointToFrom = new Vec3();
  79558. var dir_scaled_with_t = new Vec3();
  79559. var hitPointWorld = new Vec3();
  79560. from.vsub(position, planePointToFrom);
  79561. var t = -worldNormal.dot(planePointToFrom) / n_dot_dir;
  79562. direction.scale(t, dir_scaled_with_t);
  79563. from.vadd(dir_scaled_with_t, hitPointWorld);
  79564. this.reportIntersection(worldNormal, hitPointWorld, shape, body, -1);
  79565. };
  79566. Ray.prototype[Shape.types.PLANE] = Ray.prototype.intersectPlane;
  79567. /**
  79568. * Get the world AABB of the ray.
  79569. * @method getAABB
  79570. * @param {AABB} aabb
  79571. */
  79572. Ray.prototype.getAABB = function(result){
  79573. var to = this.to;
  79574. var from = this.from;
  79575. result.lowerBound.x = Math.min(to.x, from.x);
  79576. result.lowerBound.y = Math.min(to.y, from.y);
  79577. result.lowerBound.z = Math.min(to.z, from.z);
  79578. result.upperBound.x = Math.max(to.x, from.x);
  79579. result.upperBound.y = Math.max(to.y, from.y);
  79580. result.upperBound.z = Math.max(to.z, from.z);
  79581. };
  79582. var intersectConvexOptions = {
  79583. faceList: [0]
  79584. };
  79585. /**
  79586. * @method intersectHeightfield
  79587. * @private
  79588. * @param {Shape} shape
  79589. * @param {Quaternion} quat
  79590. * @param {Vec3} position
  79591. * @param {Body} body
  79592. */
  79593. Ray.prototype.intersectHeightfield = function(shape, quat, position, body){
  79594. var data = shape.data,
  79595. w = shape.elementSize,
  79596. worldPillarOffset = new Vec3();
  79597. // Convert the ray to local heightfield coordinates
  79598. var localRay = new Ray(this.from, this.to);
  79599. Transform.pointToLocalFrame(position, quat, localRay.from, localRay.from);
  79600. Transform.pointToLocalFrame(position, quat, localRay.to, localRay.to);
  79601. // Get the index of the data points to test against
  79602. var index = [];
  79603. var iMinX = null;
  79604. var iMinY = null;
  79605. var iMaxX = null;
  79606. var iMaxY = null;
  79607. var inside = shape.getIndexOfPosition(localRay.from.x, localRay.from.y, index, false);
  79608. if(inside){
  79609. iMinX = index[0];
  79610. iMinY = index[1];
  79611. iMaxX = index[0];
  79612. iMaxY = index[1];
  79613. }
  79614. inside = shape.getIndexOfPosition(localRay.to.x, localRay.to.y, index, false);
  79615. if(inside){
  79616. if (iMinX === null || index[0] < iMinX) { iMinX = index[0]; }
  79617. if (iMaxX === null || index[0] > iMaxX) { iMaxX = index[0]; }
  79618. if (iMinY === null || index[1] < iMinY) { iMinY = index[1]; }
  79619. if (iMaxY === null || index[1] > iMaxY) { iMaxY = index[1]; }
  79620. }
  79621. if(iMinX === null){
  79622. return;
  79623. }
  79624. var minMax = [];
  79625. shape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  79626. var min = minMax[0];
  79627. var max = minMax[1];
  79628. // // Bail out if the ray can't touch the bounding box
  79629. // // TODO
  79630. // var aabb = new AABB();
  79631. // this.getAABB(aabb);
  79632. // if(aabb.intersects()){
  79633. // return;
  79634. // }
  79635. for(var i = iMinX; i <= iMaxX; i++){
  79636. for(var j = iMinY; j <= iMaxY; j++){
  79637. if(this.result._shouldStop){
  79638. return;
  79639. }
  79640. // Lower triangle
  79641. shape.getConvexTrianglePillar(i, j, false);
  79642. Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
  79643. this.intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, intersectConvexOptions);
  79644. if(this.result._shouldStop){
  79645. return;
  79646. }
  79647. // Upper triangle
  79648. shape.getConvexTrianglePillar(i, j, true);
  79649. Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
  79650. this.intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, intersectConvexOptions);
  79651. }
  79652. }
  79653. };
  79654. Ray.prototype[Shape.types.HEIGHTFIELD] = Ray.prototype.intersectHeightfield;
  79655. var Ray_intersectSphere_intersectionPoint = new Vec3();
  79656. var Ray_intersectSphere_normal = new Vec3();
  79657. /**
  79658. * @method intersectSphere
  79659. * @private
  79660. * @param {Shape} shape
  79661. * @param {Quaternion} quat
  79662. * @param {Vec3} position
  79663. * @param {Body} body
  79664. */
  79665. Ray.prototype.intersectSphere = function(shape, quat, position, body){
  79666. var from = this.from,
  79667. to = this.to,
  79668. r = shape.radius;
  79669. var a = Math.pow(to.x - from.x, 2) + Math.pow(to.y - from.y, 2) + Math.pow(to.z - from.z, 2);
  79670. var b = 2 * ((to.x - from.x) * (from.x - position.x) + (to.y - from.y) * (from.y - position.y) + (to.z - from.z) * (from.z - position.z));
  79671. var c = Math.pow(from.x - position.x, 2) + Math.pow(from.y - position.y, 2) + Math.pow(from.z - position.z, 2) - Math.pow(r, 2);
  79672. var delta = Math.pow(b, 2) - 4 * a * c;
  79673. var intersectionPoint = Ray_intersectSphere_intersectionPoint;
  79674. var normal = Ray_intersectSphere_normal;
  79675. if(delta < 0){
  79676. // No intersection
  79677. return;
  79678. } else if(delta === 0){
  79679. // single intersection point
  79680. from.lerp(to, delta, intersectionPoint);
  79681. intersectionPoint.vsub(position, normal);
  79682. normal.normalize();
  79683. this.reportIntersection(normal, intersectionPoint, shape, body, -1);
  79684. } else {
  79685. var d1 = (- b - Math.sqrt(delta)) / (2 * a);
  79686. var d2 = (- b + Math.sqrt(delta)) / (2 * a);
  79687. if(d1 >= 0 && d1 <= 1){
  79688. from.lerp(to, d1, intersectionPoint);
  79689. intersectionPoint.vsub(position, normal);
  79690. normal.normalize();
  79691. this.reportIntersection(normal, intersectionPoint, shape, body, -1);
  79692. }
  79693. if(this.result._shouldStop){
  79694. return;
  79695. }
  79696. if(d2 >= 0 && d2 <= 1){
  79697. from.lerp(to, d2, intersectionPoint);
  79698. intersectionPoint.vsub(position, normal);
  79699. normal.normalize();
  79700. this.reportIntersection(normal, intersectionPoint, shape, body, -1);
  79701. }
  79702. }
  79703. };
  79704. Ray.prototype[Shape.types.SPHERE] = Ray.prototype.intersectSphere;
  79705. var intersectConvex_normal = new Vec3();
  79706. var intersectConvex_minDistNormal = new Vec3();
  79707. var intersectConvex_minDistIntersect = new Vec3();
  79708. var intersectConvex_vector = new Vec3();
  79709. /**
  79710. * @method intersectConvex
  79711. * @private
  79712. * @param {Shape} shape
  79713. * @param {Quaternion} quat
  79714. * @param {Vec3} position
  79715. * @param {Body} body
  79716. * @param {object} [options]
  79717. * @param {array} [options.faceList]
  79718. */
  79719. Ray.prototype.intersectConvex = function intersectConvex(
  79720. shape,
  79721. quat,
  79722. position,
  79723. body,
  79724. options
  79725. ){
  79726. var minDistNormal = intersectConvex_minDistNormal;
  79727. var normal = intersectConvex_normal;
  79728. var vector = intersectConvex_vector;
  79729. var minDistIntersect = intersectConvex_minDistIntersect;
  79730. var faceList = (options && options.faceList) || null;
  79731. // Checking faces
  79732. var faces = shape.faces,
  79733. vertices = shape.vertices,
  79734. normals = shape.faceNormals;
  79735. var direction = this._direction;
  79736. var from = this.from;
  79737. var to = this.to;
  79738. var fromToDistance = from.distanceTo(to);
  79739. var minDist = -1;
  79740. var Nfaces = faceList ? faceList.length : faces.length;
  79741. var result = this.result;
  79742. for (var j = 0; !result._shouldStop && j < Nfaces; j++) {
  79743. var fi = faceList ? faceList[j] : j;
  79744. var face = faces[fi];
  79745. var faceNormal = normals[fi];
  79746. var q = quat;
  79747. var x = position;
  79748. // determine if ray intersects the plane of the face
  79749. // note: this works regardless of the direction of the face normal
  79750. // Get plane point in world coordinates...
  79751. vector.copy(vertices[face[0]]);
  79752. q.vmult(vector,vector);
  79753. vector.vadd(x,vector);
  79754. // ...but make it relative to the ray from. We'll fix this later.
  79755. vector.vsub(from,vector);
  79756. // Get plane normal
  79757. q.vmult(faceNormal,normal);
  79758. // If this dot product is negative, we have something interesting
  79759. var dot = direction.dot(normal);
  79760. // Bail out if ray and plane are parallel
  79761. if ( Math.abs( dot ) < this.precision ){
  79762. continue;
  79763. }
  79764. // calc distance to plane
  79765. var scalar = normal.dot(vector) / dot;
  79766. // if negative distance, then plane is behind ray
  79767. if (scalar < 0){
  79768. continue;
  79769. }
  79770. // if (dot < 0) {
  79771. // Intersection point is from + direction * scalar
  79772. direction.mult(scalar,intersectPoint);
  79773. intersectPoint.vadd(from,intersectPoint);
  79774. // a is the point we compare points b and c with.
  79775. a.copy(vertices[face[0]]);
  79776. q.vmult(a,a);
  79777. x.vadd(a,a);
  79778. for(var i = 1; !result._shouldStop && i < face.length - 1; i++){
  79779. // Transform 3 vertices to world coords
  79780. b.copy(vertices[face[i]]);
  79781. c.copy(vertices[face[i+1]]);
  79782. q.vmult(b,b);
  79783. q.vmult(c,c);
  79784. x.vadd(b,b);
  79785. x.vadd(c,c);
  79786. var distance = intersectPoint.distanceTo(from);
  79787. if(!(pointInTriangle(intersectPoint, a, b, c) || pointInTriangle(intersectPoint, b, a, c)) || distance > fromToDistance){
  79788. continue;
  79789. }
  79790. this.reportIntersection(normal, intersectPoint, shape, body, fi);
  79791. }
  79792. // }
  79793. }
  79794. };
  79795. Ray.prototype[Shape.types.CONVEXPOLYHEDRON] = Ray.prototype.intersectConvex;
  79796. var intersectTrimesh_normal = new Vec3();
  79797. var intersectTrimesh_localDirection = new Vec3();
  79798. var intersectTrimesh_localFrom = new Vec3();
  79799. var intersectTrimesh_localTo = new Vec3();
  79800. var intersectTrimesh_worldNormal = new Vec3();
  79801. var intersectTrimesh_worldIntersectPoint = new Vec3();
  79802. var intersectTrimesh_localAABB = new AABB();
  79803. var intersectTrimesh_triangles = [];
  79804. var intersectTrimesh_treeTransform = new Transform();
  79805. /**
  79806. * @method intersectTrimesh
  79807. * @private
  79808. * @param {Shape} shape
  79809. * @param {Quaternion} quat
  79810. * @param {Vec3} position
  79811. * @param {Body} body
  79812. * @param {object} [options]
  79813. * @todo Optimize by transforming the world to local space first.
  79814. * @todo Use Octree lookup
  79815. */
  79816. Ray.prototype.intersectTrimesh = function intersectTrimesh(
  79817. mesh,
  79818. quat,
  79819. position,
  79820. body,
  79821. options
  79822. ){
  79823. var normal = intersectTrimesh_normal;
  79824. var triangles = intersectTrimesh_triangles;
  79825. var treeTransform = intersectTrimesh_treeTransform;
  79826. var minDistNormal = intersectConvex_minDistNormal;
  79827. var vector = intersectConvex_vector;
  79828. var minDistIntersect = intersectConvex_minDistIntersect;
  79829. var localAABB = intersectTrimesh_localAABB;
  79830. var localDirection = intersectTrimesh_localDirection;
  79831. var localFrom = intersectTrimesh_localFrom;
  79832. var localTo = intersectTrimesh_localTo;
  79833. var worldIntersectPoint = intersectTrimesh_worldIntersectPoint;
  79834. var worldNormal = intersectTrimesh_worldNormal;
  79835. var faceList = (options && options.faceList) || null;
  79836. // Checking faces
  79837. var indices = mesh.indices,
  79838. vertices = mesh.vertices,
  79839. normals = mesh.faceNormals;
  79840. var from = this.from;
  79841. var to = this.to;
  79842. var direction = this._direction;
  79843. var minDist = -1;
  79844. treeTransform.position.copy(position);
  79845. treeTransform.quaternion.copy(quat);
  79846. // Transform ray to local space!
  79847. Transform.vectorToLocalFrame(position, quat, direction, localDirection);
  79848. //body.vectorToLocalFrame(direction, localDirection);
  79849. Transform.pointToLocalFrame(position, quat, from, localFrom);
  79850. //body.pointToLocalFrame(from, localFrom);
  79851. Transform.pointToLocalFrame(position, quat, to, localTo);
  79852. //body.pointToLocalFrame(to, localTo);
  79853. var fromToDistanceSquared = localFrom.distanceSquared(localTo);
  79854. mesh.tree.rayQuery(this, treeTransform, triangles);
  79855. for (var i = 0, N = triangles.length; !this.result._shouldStop && i !== N; i++) {
  79856. var trianglesIndex = triangles[i];
  79857. mesh.getNormal(trianglesIndex, normal);
  79858. // determine if ray intersects the plane of the face
  79859. // note: this works regardless of the direction of the face normal
  79860. // Get plane point in world coordinates...
  79861. mesh.getVertex(indices[trianglesIndex * 3], a);
  79862. // ...but make it relative to the ray from. We'll fix this later.
  79863. a.vsub(localFrom,vector);
  79864. // Get plane normal
  79865. // quat.vmult(normal, normal);
  79866. // If this dot product is negative, we have something interesting
  79867. var dot = localDirection.dot(normal);
  79868. // Bail out if ray and plane are parallel
  79869. // if (Math.abs( dot ) < this.precision){
  79870. // continue;
  79871. // }
  79872. // calc distance to plane
  79873. var scalar = normal.dot(vector) / dot;
  79874. // if negative distance, then plane is behind ray
  79875. if (scalar < 0){
  79876. continue;
  79877. }
  79878. // Intersection point is from + direction * scalar
  79879. localDirection.scale(scalar,intersectPoint);
  79880. intersectPoint.vadd(localFrom,intersectPoint);
  79881. // Get triangle vertices
  79882. mesh.getVertex(indices[trianglesIndex * 3 + 1], b);
  79883. mesh.getVertex(indices[trianglesIndex * 3 + 2], c);
  79884. var squaredDistance = intersectPoint.distanceSquared(localFrom);
  79885. if(!(pointInTriangle(intersectPoint, b, a, c) || pointInTriangle(intersectPoint, a, b, c)) || squaredDistance > fromToDistanceSquared){
  79886. continue;
  79887. }
  79888. // transform intersectpoint and normal to world
  79889. Transform.vectorToWorldFrame(quat, normal, worldNormal);
  79890. //body.vectorToWorldFrame(normal, worldNormal);
  79891. Transform.pointToWorldFrame(position, quat, intersectPoint, worldIntersectPoint);
  79892. //body.pointToWorldFrame(intersectPoint, worldIntersectPoint);
  79893. this.reportIntersection(worldNormal, worldIntersectPoint, mesh, body, trianglesIndex);
  79894. }
  79895. triangles.length = 0;
  79896. };
  79897. Ray.prototype[Shape.types.TRIMESH] = Ray.prototype.intersectTrimesh;
  79898. /**
  79899. * @method reportIntersection
  79900. * @private
  79901. * @param {Vec3} normal
  79902. * @param {Vec3} hitPointWorld
  79903. * @param {Shape} shape
  79904. * @param {Body} body
  79905. * @return {boolean} True if the intersections should continue
  79906. */
  79907. Ray.prototype.reportIntersection = function(normal, hitPointWorld, shape, body, hitFaceIndex){
  79908. var from = this.from;
  79909. var to = this.to;
  79910. var distance = from.distanceTo(hitPointWorld);
  79911. var result = this.result;
  79912. // Skip back faces?
  79913. if(this.skipBackfaces && normal.dot(this._direction) > 0){
  79914. return;
  79915. }
  79916. result.hitFaceIndex = typeof(hitFaceIndex) !== 'undefined' ? hitFaceIndex : -1;
  79917. switch(this.mode){
  79918. case Ray.ALL:
  79919. this.hasHit = true;
  79920. result.set(
  79921. from,
  79922. to,
  79923. normal,
  79924. hitPointWorld,
  79925. shape,
  79926. body,
  79927. distance
  79928. );
  79929. result.hasHit = true;
  79930. this.callback(result);
  79931. break;
  79932. case Ray.CLOSEST:
  79933. // Store if closer than current closest
  79934. if(distance < result.distance || !result.hasHit){
  79935. this.hasHit = true;
  79936. result.hasHit = true;
  79937. result.set(
  79938. from,
  79939. to,
  79940. normal,
  79941. hitPointWorld,
  79942. shape,
  79943. body,
  79944. distance
  79945. );
  79946. }
  79947. break;
  79948. case Ray.ANY:
  79949. // Report and stop.
  79950. this.hasHit = true;
  79951. result.hasHit = true;
  79952. result.set(
  79953. from,
  79954. to,
  79955. normal,
  79956. hitPointWorld,
  79957. shape,
  79958. body,
  79959. distance
  79960. );
  79961. result._shouldStop = true;
  79962. break;
  79963. }
  79964. };
  79965. var v0 = new Vec3(),
  79966. intersect = new Vec3();
  79967. function distanceFromIntersection(from, direction, position) {
  79968. // v0 is vector from from to position
  79969. position.vsub(from,v0);
  79970. var dot = v0.dot(direction);
  79971. // intersect = direction*dot + from
  79972. direction.mult(dot,intersect);
  79973. intersect.vadd(from,intersect);
  79974. var distance = position.distanceTo(intersect);
  79975. return distance;
  79976. }
  79977. },{"../collision/AABB":3,"../collision/RaycastResult":10,"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"../shapes/Box":37,"../shapes/ConvexPolyhedron":38,"../shapes/Shape":43}],10:[function(_dereq_,module,exports){
  79978. var Vec3 = _dereq_('../math/Vec3');
  79979. module.exports = RaycastResult;
  79980. /**
  79981. * Storage for Ray casting data.
  79982. * @class RaycastResult
  79983. * @constructor
  79984. */
  79985. function RaycastResult(){
  79986. /**
  79987. * @property {Vec3} rayFromWorld
  79988. */
  79989. this.rayFromWorld = new Vec3();
  79990. /**
  79991. * @property {Vec3} rayToWorld
  79992. */
  79993. this.rayToWorld = new Vec3();
  79994. /**
  79995. * @property {Vec3} hitNormalWorld
  79996. */
  79997. this.hitNormalWorld = new Vec3();
  79998. /**
  79999. * @property {Vec3} hitPointWorld
  80000. */
  80001. this.hitPointWorld = new Vec3();
  80002. /**
  80003. * @property {boolean} hasHit
  80004. */
  80005. this.hasHit = false;
  80006. /**
  80007. * The hit shape, or null.
  80008. * @property {Shape} shape
  80009. */
  80010. this.shape = null;
  80011. /**
  80012. * The hit body, or null.
  80013. * @property {Body} body
  80014. */
  80015. this.body = null;
  80016. /**
  80017. * The index of the hit triangle, if the hit shape was a trimesh.
  80018. * @property {number} hitFaceIndex
  80019. * @default -1
  80020. */
  80021. this.hitFaceIndex = -1;
  80022. /**
  80023. * Distance to the hit. Will be set to -1 if there was no hit.
  80024. * @property {number} distance
  80025. * @default -1
  80026. */
  80027. this.distance = -1;
  80028. /**
  80029. * If the ray should stop traversing the bodies.
  80030. * @private
  80031. * @property {Boolean} _shouldStop
  80032. * @default false
  80033. */
  80034. this._shouldStop = false;
  80035. }
  80036. /**
  80037. * Reset all result data.
  80038. * @method reset
  80039. */
  80040. RaycastResult.prototype.reset = function () {
  80041. this.rayFromWorld.setZero();
  80042. this.rayToWorld.setZero();
  80043. this.hitNormalWorld.setZero();
  80044. this.hitPointWorld.setZero();
  80045. this.hasHit = false;
  80046. this.shape = null;
  80047. this.body = null;
  80048. this.hitFaceIndex = -1;
  80049. this.distance = -1;
  80050. this._shouldStop = false;
  80051. };
  80052. /**
  80053. * @method abort
  80054. */
  80055. RaycastResult.prototype.abort = function(){
  80056. this._shouldStop = true;
  80057. };
  80058. /**
  80059. * @method set
  80060. * @param {Vec3} rayFromWorld
  80061. * @param {Vec3} rayToWorld
  80062. * @param {Vec3} hitNormalWorld
  80063. * @param {Vec3} hitPointWorld
  80064. * @param {Shape} shape
  80065. * @param {Body} body
  80066. * @param {number} distance
  80067. */
  80068. RaycastResult.prototype.set = function(
  80069. rayFromWorld,
  80070. rayToWorld,
  80071. hitNormalWorld,
  80072. hitPointWorld,
  80073. shape,
  80074. body,
  80075. distance
  80076. ){
  80077. this.rayFromWorld.copy(rayFromWorld);
  80078. this.rayToWorld.copy(rayToWorld);
  80079. this.hitNormalWorld.copy(hitNormalWorld);
  80080. this.hitPointWorld.copy(hitPointWorld);
  80081. this.shape = shape;
  80082. this.body = body;
  80083. this.distance = distance;
  80084. };
  80085. },{"../math/Vec3":30}],11:[function(_dereq_,module,exports){
  80086. var Shape = _dereq_('../shapes/Shape');
  80087. var Broadphase = _dereq_('../collision/Broadphase');
  80088. module.exports = SAPBroadphase;
  80089. /**
  80090. * Sweep and prune broadphase along one axis.
  80091. *
  80092. * @class SAPBroadphase
  80093. * @constructor
  80094. * @param {World} [world]
  80095. * @extends Broadphase
  80096. */
  80097. function SAPBroadphase(world){
  80098. Broadphase.apply(this);
  80099. /**
  80100. * List of bodies currently in the broadphase.
  80101. * @property axisList
  80102. * @type {Array}
  80103. */
  80104. this.axisList = [];
  80105. /**
  80106. * The world to search in.
  80107. * @property world
  80108. * @type {World}
  80109. */
  80110. this.world = null;
  80111. /**
  80112. * Axis to sort the bodies along. Set to 0 for x axis, and 1 for y axis. For best performance, choose an axis that the bodies are spread out more on.
  80113. * @property axisIndex
  80114. * @type {Number}
  80115. */
  80116. this.axisIndex = 0;
  80117. var axisList = this.axisList;
  80118. this._addBodyHandler = function(e){
  80119. axisList.push(e.body);
  80120. };
  80121. this._removeBodyHandler = function(e){
  80122. var idx = axisList.indexOf(e.body);
  80123. if(idx !== -1){
  80124. axisList.splice(idx,1);
  80125. }
  80126. };
  80127. if(world){
  80128. this.setWorld(world);
  80129. }
  80130. }
  80131. SAPBroadphase.prototype = new Broadphase();
  80132. /**
  80133. * Change the world
  80134. * @method setWorld
  80135. * @param {World} world
  80136. */
  80137. SAPBroadphase.prototype.setWorld = function(world){
  80138. // Clear the old axis array
  80139. this.axisList.length = 0;
  80140. // Add all bodies from the new world
  80141. for(var i=0; i<world.bodies.length; i++){
  80142. this.axisList.push(world.bodies[i]);
  80143. }
  80144. // Remove old handlers, if any
  80145. world.removeEventListener("addBody", this._addBodyHandler);
  80146. world.removeEventListener("removeBody", this._removeBodyHandler);
  80147. // Add handlers to update the list of bodies.
  80148. world.addEventListener("addBody", this._addBodyHandler);
  80149. world.addEventListener("removeBody", this._removeBodyHandler);
  80150. this.world = world;
  80151. this.dirty = true;
  80152. };
  80153. /**
  80154. * @static
  80155. * @method insertionSortX
  80156. * @param {Array} a
  80157. * @return {Array}
  80158. */
  80159. SAPBroadphase.insertionSortX = function(a) {
  80160. for(var i=1,l=a.length;i<l;i++) {
  80161. var v = a[i];
  80162. for(var j=i - 1;j>=0;j--) {
  80163. if(a[j].aabb.lowerBound.x <= v.aabb.lowerBound.x){
  80164. break;
  80165. }
  80166. a[j+1] = a[j];
  80167. }
  80168. a[j+1] = v;
  80169. }
  80170. return a;
  80171. };
  80172. /**
  80173. * @static
  80174. * @method insertionSortY
  80175. * @param {Array} a
  80176. * @return {Array}
  80177. */
  80178. SAPBroadphase.insertionSortY = function(a) {
  80179. for(var i=1,l=a.length;i<l;i++) {
  80180. var v = a[i];
  80181. for(var j=i - 1;j>=0;j--) {
  80182. if(a[j].aabb.lowerBound.y <= v.aabb.lowerBound.y){
  80183. break;
  80184. }
  80185. a[j+1] = a[j];
  80186. }
  80187. a[j+1] = v;
  80188. }
  80189. return a;
  80190. };
  80191. /**
  80192. * @static
  80193. * @method insertionSortZ
  80194. * @param {Array} a
  80195. * @return {Array}
  80196. */
  80197. SAPBroadphase.insertionSortZ = function(a) {
  80198. for(var i=1,l=a.length;i<l;i++) {
  80199. var v = a[i];
  80200. for(var j=i - 1;j>=0;j--) {
  80201. if(a[j].aabb.lowerBound.z <= v.aabb.lowerBound.z){
  80202. break;
  80203. }
  80204. a[j+1] = a[j];
  80205. }
  80206. a[j+1] = v;
  80207. }
  80208. return a;
  80209. };
  80210. /**
  80211. * Collect all collision pairs
  80212. * @method collisionPairs
  80213. * @param {World} world
  80214. * @param {Array} p1
  80215. * @param {Array} p2
  80216. */
  80217. SAPBroadphase.prototype.collisionPairs = function(world,p1,p2){
  80218. var bodies = this.axisList,
  80219. N = bodies.length,
  80220. axisIndex = this.axisIndex,
  80221. i, j;
  80222. if(this.dirty){
  80223. this.sortList();
  80224. this.dirty = false;
  80225. }
  80226. // Look through the list
  80227. for(i=0; i !== N; i++){
  80228. var bi = bodies[i];
  80229. for(j=i+1; j < N; j++){
  80230. var bj = bodies[j];
  80231. if(!this.needBroadphaseCollision(bi,bj)){
  80232. continue;
  80233. }
  80234. if(!SAPBroadphase.checkBounds(bi,bj,axisIndex)){
  80235. break;
  80236. }
  80237. this.intersectionTest(bi,bj,p1,p2);
  80238. }
  80239. }
  80240. };
  80241. SAPBroadphase.prototype.sortList = function(){
  80242. var axisList = this.axisList;
  80243. var axisIndex = this.axisIndex;
  80244. var N = axisList.length;
  80245. // Update AABBs
  80246. for(var i = 0; i!==N; i++){
  80247. var bi = axisList[i];
  80248. if(bi.aabbNeedsUpdate){
  80249. bi.computeAABB();
  80250. }
  80251. }
  80252. // Sort the list
  80253. if(axisIndex === 0){
  80254. SAPBroadphase.insertionSortX(axisList);
  80255. } else if(axisIndex === 1){
  80256. SAPBroadphase.insertionSortY(axisList);
  80257. } else if(axisIndex === 2){
  80258. SAPBroadphase.insertionSortZ(axisList);
  80259. }
  80260. };
  80261. /**
  80262. * Check if the bounds of two bodies overlap, along the given SAP axis.
  80263. * @static
  80264. * @method checkBounds
  80265. * @param {Body} bi
  80266. * @param {Body} bj
  80267. * @param {Number} axisIndex
  80268. * @return {Boolean}
  80269. */
  80270. SAPBroadphase.checkBounds = function(bi, bj, axisIndex){
  80271. var biPos;
  80272. var bjPos;
  80273. if(axisIndex === 0){
  80274. biPos = bi.position.x;
  80275. bjPos = bj.position.x;
  80276. } else if(axisIndex === 1){
  80277. biPos = bi.position.y;
  80278. bjPos = bj.position.y;
  80279. } else if(axisIndex === 2){
  80280. biPos = bi.position.z;
  80281. bjPos = bj.position.z;
  80282. }
  80283. var ri = bi.boundingRadius,
  80284. rj = bj.boundingRadius,
  80285. boundA1 = biPos - ri,
  80286. boundA2 = biPos + ri,
  80287. boundB1 = bjPos - rj,
  80288. boundB2 = bjPos + rj;
  80289. return boundB1 < boundA2;
  80290. };
  80291. /**
  80292. * Computes the variance of the body positions and estimates the best
  80293. * axis to use. Will automatically set property .axisIndex.
  80294. * @method autoDetectAxis
  80295. */
  80296. SAPBroadphase.prototype.autoDetectAxis = function(){
  80297. var sumX=0,
  80298. sumX2=0,
  80299. sumY=0,
  80300. sumY2=0,
  80301. sumZ=0,
  80302. sumZ2=0,
  80303. bodies = this.axisList,
  80304. N = bodies.length,
  80305. invN=1/N;
  80306. for(var i=0; i!==N; i++){
  80307. var b = bodies[i];
  80308. var centerX = b.position.x;
  80309. sumX += centerX;
  80310. sumX2 += centerX*centerX;
  80311. var centerY = b.position.y;
  80312. sumY += centerY;
  80313. sumY2 += centerY*centerY;
  80314. var centerZ = b.position.z;
  80315. sumZ += centerZ;
  80316. sumZ2 += centerZ*centerZ;
  80317. }
  80318. var varianceX = sumX2 - sumX*sumX*invN,
  80319. varianceY = sumY2 - sumY*sumY*invN,
  80320. varianceZ = sumZ2 - sumZ*sumZ*invN;
  80321. if(varianceX > varianceY){
  80322. if(varianceX > varianceZ){
  80323. this.axisIndex = 0;
  80324. } else{
  80325. this.axisIndex = 2;
  80326. }
  80327. } else if(varianceY > varianceZ){
  80328. this.axisIndex = 1;
  80329. } else{
  80330. this.axisIndex = 2;
  80331. }
  80332. };
  80333. /**
  80334. * Returns all the bodies within an AABB.
  80335. * @method aabbQuery
  80336. * @param {World} world
  80337. * @param {AABB} aabb
  80338. * @param {array} result An array to store resulting bodies in.
  80339. * @return {array}
  80340. */
  80341. SAPBroadphase.prototype.aabbQuery = function(world, aabb, result){
  80342. result = result || [];
  80343. if(this.dirty){
  80344. this.sortList();
  80345. this.dirty = false;
  80346. }
  80347. var axisIndex = this.axisIndex, axis = 'x';
  80348. if(axisIndex === 1){ axis = 'y'; }
  80349. if(axisIndex === 2){ axis = 'z'; }
  80350. var axisList = this.axisList;
  80351. var lower = aabb.lowerBound[axis];
  80352. var upper = aabb.upperBound[axis];
  80353. for(var i = 0; i < axisList.length; i++){
  80354. var b = axisList[i];
  80355. if(b.aabbNeedsUpdate){
  80356. b.computeAABB();
  80357. }
  80358. if(b.aabb.overlaps(aabb)){
  80359. result.push(b);
  80360. }
  80361. }
  80362. return result;
  80363. };
  80364. },{"../collision/Broadphase":5,"../shapes/Shape":43}],12:[function(_dereq_,module,exports){
  80365. module.exports = ConeTwistConstraint;
  80366. var Constraint = _dereq_('./Constraint');
  80367. var PointToPointConstraint = _dereq_('./PointToPointConstraint');
  80368. var ConeEquation = _dereq_('../equations/ConeEquation');
  80369. var RotationalEquation = _dereq_('../equations/RotationalEquation');
  80370. var ContactEquation = _dereq_('../equations/ContactEquation');
  80371. var Vec3 = _dereq_('../math/Vec3');
  80372. /**
  80373. * @class ConeTwistConstraint
  80374. * @constructor
  80375. * @author schteppe
  80376. * @param {Body} bodyA
  80377. * @param {Body} bodyB
  80378. * @param {object} [options]
  80379. * @param {Vec3} [options.pivotA]
  80380. * @param {Vec3} [options.pivotB]
  80381. * @param {Vec3} [options.axisA]
  80382. * @param {Vec3} [options.axisB]
  80383. * @param {Number} [options.maxForce=1e6]
  80384. * @extends PointToPointConstraint
  80385. */
  80386. function ConeTwistConstraint(bodyA, bodyB, options){
  80387. options = options || {};
  80388. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  80389. // Set pivot point in between
  80390. var pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
  80391. var pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
  80392. this.axisA = options.axisA ? options.axisA.clone() : new Vec3();
  80393. this.axisB = options.axisB ? options.axisB.clone() : new Vec3();
  80394. PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);
  80395. this.collideConnected = !!options.collideConnected;
  80396. this.angle = typeof(options.angle) !== 'undefined' ? options.angle : 0;
  80397. /**
  80398. * @property {ConeEquation} coneEquation
  80399. */
  80400. var c = this.coneEquation = new ConeEquation(bodyA,bodyB,options);
  80401. /**
  80402. * @property {RotationalEquation} twistEquation
  80403. */
  80404. var t = this.twistEquation = new RotationalEquation(bodyA,bodyB,options);
  80405. this.twistAngle = typeof(options.twistAngle) !== 'undefined' ? options.twistAngle : 0;
  80406. // Make the cone equation push the bodies toward the cone axis, not outward
  80407. c.maxForce = 0;
  80408. c.minForce = -maxForce;
  80409. // Make the twist equation add torque toward the initial position
  80410. t.maxForce = 0;
  80411. t.minForce = -maxForce;
  80412. this.equations.push(c, t);
  80413. }
  80414. ConeTwistConstraint.prototype = new PointToPointConstraint();
  80415. ConeTwistConstraint.constructor = ConeTwistConstraint;
  80416. var ConeTwistConstraint_update_tmpVec1 = new Vec3();
  80417. var ConeTwistConstraint_update_tmpVec2 = new Vec3();
  80418. ConeTwistConstraint.prototype.update = function(){
  80419. var bodyA = this.bodyA,
  80420. bodyB = this.bodyB,
  80421. cone = this.coneEquation,
  80422. twist = this.twistEquation;
  80423. PointToPointConstraint.prototype.update.call(this);
  80424. // Update the axes to the cone constraint
  80425. bodyA.vectorToWorldFrame(this.axisA, cone.axisA);
  80426. bodyB.vectorToWorldFrame(this.axisB, cone.axisB);
  80427. // Update the world axes in the twist constraint
  80428. this.axisA.tangents(twist.axisA, twist.axisA);
  80429. bodyA.vectorToWorldFrame(twist.axisA, twist.axisA);
  80430. this.axisB.tangents(twist.axisB, twist.axisB);
  80431. bodyB.vectorToWorldFrame(twist.axisB, twist.axisB);
  80432. cone.angle = this.angle;
  80433. twist.maxAngle = this.twistAngle;
  80434. };
  80435. },{"../equations/ConeEquation":18,"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],13:[function(_dereq_,module,exports){
  80436. module.exports = Constraint;
  80437. var Utils = _dereq_('../utils/Utils');
  80438. /**
  80439. * Constraint base class
  80440. * @class Constraint
  80441. * @author schteppe
  80442. * @constructor
  80443. * @param {Body} bodyA
  80444. * @param {Body} bodyB
  80445. * @param {object} [options]
  80446. * @param {boolean} [options.collideConnected=true]
  80447. * @param {boolean} [options.wakeUpBodies=true]
  80448. */
  80449. function Constraint(bodyA, bodyB, options){
  80450. options = Utils.defaults(options,{
  80451. collideConnected : true,
  80452. wakeUpBodies : true,
  80453. });
  80454. /**
  80455. * Equations to be solved in this constraint
  80456. * @property equations
  80457. * @type {Array}
  80458. */
  80459. this.equations = [];
  80460. /**
  80461. * @property {Body} bodyA
  80462. */
  80463. this.bodyA = bodyA;
  80464. /**
  80465. * @property {Body} bodyB
  80466. */
  80467. this.bodyB = bodyB;
  80468. /**
  80469. * @property {Number} id
  80470. */
  80471. this.id = Constraint.idCounter++;
  80472. /**
  80473. * Set to true if you want the bodies to collide when they are connected.
  80474. * @property collideConnected
  80475. * @type {boolean}
  80476. */
  80477. this.collideConnected = options.collideConnected;
  80478. if(options.wakeUpBodies){
  80479. if(bodyA){
  80480. bodyA.wakeUp();
  80481. }
  80482. if(bodyB){
  80483. bodyB.wakeUp();
  80484. }
  80485. }
  80486. }
  80487. /**
  80488. * Update all the equations with data.
  80489. * @method update
  80490. */
  80491. Constraint.prototype.update = function(){
  80492. throw new Error("method update() not implmemented in this Constraint subclass!");
  80493. };
  80494. /**
  80495. * Enables all equations in the constraint.
  80496. * @method enable
  80497. */
  80498. Constraint.prototype.enable = function(){
  80499. var eqs = this.equations;
  80500. for(var i=0; i<eqs.length; i++){
  80501. eqs[i].enabled = true;
  80502. }
  80503. };
  80504. /**
  80505. * Disables all equations in the constraint.
  80506. * @method disable
  80507. */
  80508. Constraint.prototype.disable = function(){
  80509. var eqs = this.equations;
  80510. for(var i=0; i<eqs.length; i++){
  80511. eqs[i].enabled = false;
  80512. }
  80513. };
  80514. Constraint.idCounter = 0;
  80515. },{"../utils/Utils":53}],14:[function(_dereq_,module,exports){
  80516. module.exports = DistanceConstraint;
  80517. var Constraint = _dereq_('./Constraint');
  80518. var ContactEquation = _dereq_('../equations/ContactEquation');
  80519. /**
  80520. * Constrains two bodies to be at a constant distance from each others center of mass.
  80521. * @class DistanceConstraint
  80522. * @constructor
  80523. * @author schteppe
  80524. * @param {Body} bodyA
  80525. * @param {Body} bodyB
  80526. * @param {Number} [distance] The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB
  80527. * @param {Number} [maxForce=1e6]
  80528. * @extends Constraint
  80529. */
  80530. function DistanceConstraint(bodyA,bodyB,distance,maxForce){
  80531. Constraint.call(this,bodyA,bodyB);
  80532. if(typeof(distance)==="undefined") {
  80533. distance = bodyA.position.distanceTo(bodyB.position);
  80534. }
  80535. if(typeof(maxForce)==="undefined") {
  80536. maxForce = 1e6;
  80537. }
  80538. /**
  80539. * @property {number} distance
  80540. */
  80541. this.distance = distance;
  80542. /**
  80543. * @property {ContactEquation} distanceEquation
  80544. */
  80545. var eq = this.distanceEquation = new ContactEquation(bodyA, bodyB);
  80546. this.equations.push(eq);
  80547. // Make it bidirectional
  80548. eq.minForce = -maxForce;
  80549. eq.maxForce = maxForce;
  80550. }
  80551. DistanceConstraint.prototype = new Constraint();
  80552. DistanceConstraint.prototype.update = function(){
  80553. var bodyA = this.bodyA;
  80554. var bodyB = this.bodyB;
  80555. var eq = this.distanceEquation;
  80556. var halfDist = this.distance * 0.5;
  80557. var normal = eq.ni;
  80558. bodyB.position.vsub(bodyA.position, normal);
  80559. normal.normalize();
  80560. normal.mult(halfDist, eq.ri);
  80561. normal.mult(-halfDist, eq.rj);
  80562. };
  80563. },{"../equations/ContactEquation":19,"./Constraint":13}],15:[function(_dereq_,module,exports){
  80564. module.exports = HingeConstraint;
  80565. var Constraint = _dereq_('./Constraint');
  80566. var PointToPointConstraint = _dereq_('./PointToPointConstraint');
  80567. var RotationalEquation = _dereq_('../equations/RotationalEquation');
  80568. var RotationalMotorEquation = _dereq_('../equations/RotationalMotorEquation');
  80569. var ContactEquation = _dereq_('../equations/ContactEquation');
  80570. var Vec3 = _dereq_('../math/Vec3');
  80571. /**
  80572. * Hinge constraint. Think of it as a door hinge. It tries to keep the door in the correct place and with the correct orientation.
  80573. * @class HingeConstraint
  80574. * @constructor
  80575. * @author schteppe
  80576. * @param {Body} bodyA
  80577. * @param {Body} bodyB
  80578. * @param {object} [options]
  80579. * @param {Vec3} [options.pivotA] A point defined locally in bodyA. This defines the offset of axisA.
  80580. * @param {Vec3} [options.axisA] An axis that bodyA can rotate around, defined locally in bodyA.
  80581. * @param {Vec3} [options.pivotB]
  80582. * @param {Vec3} [options.axisB]
  80583. * @param {Number} [options.maxForce=1e6]
  80584. * @extends PointToPointConstraint
  80585. */
  80586. function HingeConstraint(bodyA, bodyB, options){
  80587. options = options || {};
  80588. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  80589. var pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
  80590. var pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
  80591. PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);
  80592. /**
  80593. * Rotation axis, defined locally in bodyA.
  80594. * @property {Vec3} axisA
  80595. */
  80596. var axisA = this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1,0,0);
  80597. axisA.normalize();
  80598. /**
  80599. * Rotation axis, defined locally in bodyB.
  80600. * @property {Vec3} axisB
  80601. */
  80602. var axisB = this.axisB = options.axisB ? options.axisB.clone() : new Vec3(1,0,0);
  80603. axisB.normalize();
  80604. /**
  80605. * @property {RotationalEquation} rotationalEquation1
  80606. */
  80607. var r1 = this.rotationalEquation1 = new RotationalEquation(bodyA,bodyB,options);
  80608. /**
  80609. * @property {RotationalEquation} rotationalEquation2
  80610. */
  80611. var r2 = this.rotationalEquation2 = new RotationalEquation(bodyA,bodyB,options);
  80612. /**
  80613. * @property {RotationalMotorEquation} motorEquation
  80614. */
  80615. var motor = this.motorEquation = new RotationalMotorEquation(bodyA,bodyB,maxForce);
  80616. motor.enabled = false; // Not enabled by default
  80617. // Equations to be fed to the solver
  80618. this.equations.push(
  80619. r1, // rotational1
  80620. r2, // rotational2
  80621. motor
  80622. );
  80623. }
  80624. HingeConstraint.prototype = new PointToPointConstraint();
  80625. HingeConstraint.constructor = HingeConstraint;
  80626. /**
  80627. * @method enableMotor
  80628. */
  80629. HingeConstraint.prototype.enableMotor = function(){
  80630. this.motorEquation.enabled = true;
  80631. };
  80632. /**
  80633. * @method disableMotor
  80634. */
  80635. HingeConstraint.prototype.disableMotor = function(){
  80636. this.motorEquation.enabled = false;
  80637. };
  80638. /**
  80639. * @method setMotorSpeed
  80640. * @param {number} speed
  80641. */
  80642. HingeConstraint.prototype.setMotorSpeed = function(speed){
  80643. this.motorEquation.targetVelocity = speed;
  80644. };
  80645. /**
  80646. * @method setMotorMaxForce
  80647. * @param {number} maxForce
  80648. */
  80649. HingeConstraint.prototype.setMotorMaxForce = function(maxForce){
  80650. this.motorEquation.maxForce = maxForce;
  80651. this.motorEquation.minForce = -maxForce;
  80652. };
  80653. var HingeConstraint_update_tmpVec1 = new Vec3();
  80654. var HingeConstraint_update_tmpVec2 = new Vec3();
  80655. HingeConstraint.prototype.update = function(){
  80656. var bodyA = this.bodyA,
  80657. bodyB = this.bodyB,
  80658. motor = this.motorEquation,
  80659. r1 = this.rotationalEquation1,
  80660. r2 = this.rotationalEquation2,
  80661. worldAxisA = HingeConstraint_update_tmpVec1,
  80662. worldAxisB = HingeConstraint_update_tmpVec2;
  80663. var axisA = this.axisA;
  80664. var axisB = this.axisB;
  80665. PointToPointConstraint.prototype.update.call(this);
  80666. // Get world axes
  80667. bodyA.quaternion.vmult(axisA, worldAxisA);
  80668. bodyB.quaternion.vmult(axisB, worldAxisB);
  80669. worldAxisA.tangents(r1.axisA, r2.axisA);
  80670. r1.axisB.copy(worldAxisB);
  80671. r2.axisB.copy(worldAxisB);
  80672. if(this.motorEquation.enabled){
  80673. bodyA.quaternion.vmult(this.axisA, motor.axisA);
  80674. bodyB.quaternion.vmult(this.axisB, motor.axisB);
  80675. }
  80676. };
  80677. },{"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../equations/RotationalMotorEquation":23,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],16:[function(_dereq_,module,exports){
  80678. module.exports = LockConstraint;
  80679. var Constraint = _dereq_('./Constraint');
  80680. var PointToPointConstraint = _dereq_('./PointToPointConstraint');
  80681. var RotationalEquation = _dereq_('../equations/RotationalEquation');
  80682. var RotationalMotorEquation = _dereq_('../equations/RotationalMotorEquation');
  80683. var ContactEquation = _dereq_('../equations/ContactEquation');
  80684. var Vec3 = _dereq_('../math/Vec3');
  80685. /**
  80686. * Lock constraint. Will remove all degrees of freedom between the bodies.
  80687. * @class LockConstraint
  80688. * @constructor
  80689. * @author schteppe
  80690. * @param {Body} bodyA
  80691. * @param {Body} bodyB
  80692. * @param {object} [options]
  80693. * @param {Number} [options.maxForce=1e6]
  80694. * @extends PointToPointConstraint
  80695. */
  80696. function LockConstraint(bodyA, bodyB, options){
  80697. options = options || {};
  80698. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  80699. // Set pivot point in between
  80700. var pivotA = new Vec3();
  80701. var pivotB = new Vec3();
  80702. var halfWay = new Vec3();
  80703. bodyA.position.vadd(bodyB.position, halfWay);
  80704. halfWay.scale(0.5, halfWay);
  80705. bodyB.pointToLocalFrame(halfWay, pivotB);
  80706. bodyA.pointToLocalFrame(halfWay, pivotA);
  80707. PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);
  80708. /**
  80709. * @property {RotationalEquation} rotationalEquation1
  80710. */
  80711. var r1 = this.rotationalEquation1 = new RotationalEquation(bodyA,bodyB,options);
  80712. /**
  80713. * @property {RotationalEquation} rotationalEquation2
  80714. */
  80715. var r2 = this.rotationalEquation2 = new RotationalEquation(bodyA,bodyB,options);
  80716. /**
  80717. * @property {RotationalEquation} rotationalEquation3
  80718. */
  80719. var r3 = this.rotationalEquation3 = new RotationalEquation(bodyA,bodyB,options);
  80720. this.equations.push(r1, r2, r3);
  80721. }
  80722. LockConstraint.prototype = new PointToPointConstraint();
  80723. LockConstraint.constructor = LockConstraint;
  80724. var LockConstraint_update_tmpVec1 = new Vec3();
  80725. var LockConstraint_update_tmpVec2 = new Vec3();
  80726. LockConstraint.prototype.update = function(){
  80727. var bodyA = this.bodyA,
  80728. bodyB = this.bodyB,
  80729. motor = this.motorEquation,
  80730. r1 = this.rotationalEquation1,
  80731. r2 = this.rotationalEquation2,
  80732. r3 = this.rotationalEquation3,
  80733. worldAxisA = LockConstraint_update_tmpVec1,
  80734. worldAxisB = LockConstraint_update_tmpVec2;
  80735. PointToPointConstraint.prototype.update.call(this);
  80736. bodyA.vectorToWorldFrame(Vec3.UNIT_X, r1.axisA);
  80737. bodyB.vectorToWorldFrame(Vec3.UNIT_Y, r1.axisB);
  80738. bodyA.vectorToWorldFrame(Vec3.UNIT_Y, r2.axisA);
  80739. bodyB.vectorToWorldFrame(Vec3.UNIT_Z, r2.axisB);
  80740. bodyA.vectorToWorldFrame(Vec3.UNIT_Z, r3.axisA);
  80741. bodyB.vectorToWorldFrame(Vec3.UNIT_X, r3.axisB);
  80742. };
  80743. },{"../equations/ContactEquation":19,"../equations/RotationalEquation":22,"../equations/RotationalMotorEquation":23,"../math/Vec3":30,"./Constraint":13,"./PointToPointConstraint":17}],17:[function(_dereq_,module,exports){
  80744. module.exports = PointToPointConstraint;
  80745. var Constraint = _dereq_('./Constraint');
  80746. var ContactEquation = _dereq_('../equations/ContactEquation');
  80747. var Vec3 = _dereq_('../math/Vec3');
  80748. /**
  80749. * Connects two bodies at given offset points.
  80750. * @class PointToPointConstraint
  80751. * @extends Constraint
  80752. * @constructor
  80753. * @param {Body} bodyA
  80754. * @param {Vec3} pivotA The point relative to the center of mass of bodyA which bodyA is constrained to.
  80755. * @param {Body} bodyB Body that will be constrained in a similar way to the same point as bodyA. We will therefore get a link between bodyA and bodyB. If not specified, bodyA will be constrained to a static point.
  80756. * @param {Vec3} pivotB See pivotA.
  80757. * @param {Number} maxForce The maximum force that should be applied to constrain the bodies.
  80758. *
  80759. * @example
  80760. * var bodyA = new Body({ mass: 1 });
  80761. * var bodyB = new Body({ mass: 1 });
  80762. * bodyA.position.set(-1, 0, 0);
  80763. * bodyB.position.set(1, 0, 0);
  80764. * bodyA.addShape(shapeA);
  80765. * bodyB.addShape(shapeB);
  80766. * world.addBody(bodyA);
  80767. * world.addBody(bodyB);
  80768. * var localPivotA = new Vec3(1, 0, 0);
  80769. * var localPivotB = new Vec3(-1, 0, 0);
  80770. * var constraint = new PointToPointConstraint(bodyA, localPivotA, bodyB, localPivotB);
  80771. * world.addConstraint(constraint);
  80772. */
  80773. function PointToPointConstraint(bodyA,pivotA,bodyB,pivotB,maxForce){
  80774. Constraint.call(this,bodyA,bodyB);
  80775. maxForce = typeof(maxForce) !== 'undefined' ? maxForce : 1e6;
  80776. /**
  80777. * Pivot, defined locally in bodyA.
  80778. * @property {Vec3} pivotA
  80779. */
  80780. this.pivotA = pivotA ? pivotA.clone() : new Vec3();
  80781. /**
  80782. * Pivot, defined locally in bodyB.
  80783. * @property {Vec3} pivotB
  80784. */
  80785. this.pivotB = pivotB ? pivotB.clone() : new Vec3();
  80786. /**
  80787. * @property {ContactEquation} equationX
  80788. */
  80789. var x = this.equationX = new ContactEquation(bodyA,bodyB);
  80790. /**
  80791. * @property {ContactEquation} equationY
  80792. */
  80793. var y = this.equationY = new ContactEquation(bodyA,bodyB);
  80794. /**
  80795. * @property {ContactEquation} equationZ
  80796. */
  80797. var z = this.equationZ = new ContactEquation(bodyA,bodyB);
  80798. // Equations to be fed to the solver
  80799. this.equations.push(x, y, z);
  80800. // Make the equations bidirectional
  80801. x.minForce = y.minForce = z.minForce = -maxForce;
  80802. x.maxForce = y.maxForce = z.maxForce = maxForce;
  80803. x.ni.set(1, 0, 0);
  80804. y.ni.set(0, 1, 0);
  80805. z.ni.set(0, 0, 1);
  80806. }
  80807. PointToPointConstraint.prototype = new Constraint();
  80808. PointToPointConstraint.prototype.update = function(){
  80809. var bodyA = this.bodyA;
  80810. var bodyB = this.bodyB;
  80811. var x = this.equationX;
  80812. var y = this.equationY;
  80813. var z = this.equationZ;
  80814. // Rotate the pivots to world space
  80815. bodyA.quaternion.vmult(this.pivotA,x.ri);
  80816. bodyB.quaternion.vmult(this.pivotB,x.rj);
  80817. y.ri.copy(x.ri);
  80818. y.rj.copy(x.rj);
  80819. z.ri.copy(x.ri);
  80820. z.rj.copy(x.rj);
  80821. };
  80822. },{"../equations/ContactEquation":19,"../math/Vec3":30,"./Constraint":13}],18:[function(_dereq_,module,exports){
  80823. module.exports = ConeEquation;
  80824. var Vec3 = _dereq_('../math/Vec3');
  80825. var Mat3 = _dereq_('../math/Mat3');
  80826. var Equation = _dereq_('./Equation');
  80827. /**
  80828. * Cone equation. Works to keep the given body world vectors aligned, or tilted within a given angle from each other.
  80829. * @class ConeEquation
  80830. * @constructor
  80831. * @author schteppe
  80832. * @param {Body} bodyA
  80833. * @param {Body} bodyB
  80834. * @param {Vec3} [options.axisA] Local axis in A
  80835. * @param {Vec3} [options.axisB] Local axis in B
  80836. * @param {Vec3} [options.angle] The "cone angle" to keep
  80837. * @param {number} [options.maxForce=1e6]
  80838. * @extends Equation
  80839. */
  80840. function ConeEquation(bodyA, bodyB, options){
  80841. options = options || {};
  80842. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  80843. Equation.call(this,bodyA,bodyB,-maxForce, maxForce);
  80844. this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  80845. this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
  80846. /**
  80847. * The cone angle to keep
  80848. * @property {number} angle
  80849. */
  80850. this.angle = typeof(options.angle) !== 'undefined' ? options.angle : 0;
  80851. }
  80852. ConeEquation.prototype = new Equation();
  80853. ConeEquation.prototype.constructor = ConeEquation;
  80854. var tmpVec1 = new Vec3();
  80855. var tmpVec2 = new Vec3();
  80856. ConeEquation.prototype.computeB = function(h){
  80857. var a = this.a,
  80858. b = this.b,
  80859. ni = this.axisA,
  80860. nj = this.axisB,
  80861. nixnj = tmpVec1,
  80862. njxni = tmpVec2,
  80863. GA = this.jacobianElementA,
  80864. GB = this.jacobianElementB;
  80865. // Caluclate cross products
  80866. ni.cross(nj, nixnj);
  80867. nj.cross(ni, njxni);
  80868. // The angle between two vector is:
  80869. // cos(theta) = a * b / (length(a) * length(b) = { len(a) = len(b) = 1 } = a * b
  80870. // g = a * b
  80871. // gdot = (b x a) * wi + (a x b) * wj
  80872. // G = [0 bxa 0 axb]
  80873. // W = [vi wi vj wj]
  80874. GA.rotational.copy(njxni);
  80875. GB.rotational.copy(nixnj);
  80876. var g = Math.cos(this.angle) - ni.dot(nj),
  80877. GW = this.computeGW(),
  80878. GiMf = this.computeGiMf();
  80879. var B = - g * a - GW * b - h * GiMf;
  80880. return B;
  80881. };
  80882. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],19:[function(_dereq_,module,exports){
  80883. module.exports = ContactEquation;
  80884. var Equation = _dereq_('./Equation');
  80885. var Vec3 = _dereq_('../math/Vec3');
  80886. var Mat3 = _dereq_('../math/Mat3');
  80887. /**
  80888. * Contact/non-penetration constraint equation
  80889. * @class ContactEquation
  80890. * @constructor
  80891. * @author schteppe
  80892. * @param {Body} bodyA
  80893. * @param {Body} bodyB
  80894. * @extends Equation
  80895. */
  80896. function ContactEquation(bodyA, bodyB, maxForce){
  80897. maxForce = typeof(maxForce) !== 'undefined' ? maxForce : 1e6;
  80898. Equation.call(this, bodyA, bodyB, 0, maxForce);
  80899. /**
  80900. * @property restitution
  80901. * @type {Number}
  80902. */
  80903. this.restitution = 0.0; // "bounciness": u1 = -e*u0
  80904. /**
  80905. * World-oriented vector that goes from the center of bi to the contact point.
  80906. * @property {Vec3} ri
  80907. */
  80908. this.ri = new Vec3();
  80909. /**
  80910. * World-oriented vector that starts in body j position and goes to the contact point.
  80911. * @property {Vec3} rj
  80912. */
  80913. this.rj = new Vec3();
  80914. /**
  80915. * Contact normal, pointing out of body i.
  80916. * @property {Vec3} ni
  80917. */
  80918. this.ni = new Vec3();
  80919. }
  80920. ContactEquation.prototype = new Equation();
  80921. ContactEquation.prototype.constructor = ContactEquation;
  80922. var ContactEquation_computeB_temp1 = new Vec3(); // Temp vectors
  80923. var ContactEquation_computeB_temp2 = new Vec3();
  80924. var ContactEquation_computeB_temp3 = new Vec3();
  80925. ContactEquation.prototype.computeB = function(h){
  80926. var a = this.a,
  80927. b = this.b,
  80928. bi = this.bi,
  80929. bj = this.bj,
  80930. ri = this.ri,
  80931. rj = this.rj,
  80932. rixn = ContactEquation_computeB_temp1,
  80933. rjxn = ContactEquation_computeB_temp2,
  80934. vi = bi.velocity,
  80935. wi = bi.angularVelocity,
  80936. fi = bi.force,
  80937. taui = bi.torque,
  80938. vj = bj.velocity,
  80939. wj = bj.angularVelocity,
  80940. fj = bj.force,
  80941. tauj = bj.torque,
  80942. penetrationVec = ContactEquation_computeB_temp3,
  80943. GA = this.jacobianElementA,
  80944. GB = this.jacobianElementB,
  80945. n = this.ni;
  80946. // Caluclate cross products
  80947. ri.cross(n,rixn);
  80948. rj.cross(n,rjxn);
  80949. // g = xj+rj -(xi+ri)
  80950. // G = [ -ni -rixn ni rjxn ]
  80951. n.negate(GA.spatial);
  80952. rixn.negate(GA.rotational);
  80953. GB.spatial.copy(n);
  80954. GB.rotational.copy(rjxn);
  80955. // Calculate the penetration vector
  80956. penetrationVec.copy(bj.position);
  80957. penetrationVec.vadd(rj,penetrationVec);
  80958. penetrationVec.vsub(bi.position,penetrationVec);
  80959. penetrationVec.vsub(ri,penetrationVec);
  80960. var g = n.dot(penetrationVec);
  80961. // Compute iteration
  80962. var ePlusOne = this.restitution + 1;
  80963. var GW = ePlusOne * vj.dot(n) - ePlusOne * vi.dot(n) + wj.dot(rjxn) - wi.dot(rixn);
  80964. var GiMf = this.computeGiMf();
  80965. var B = - g * a - GW * b - h*GiMf;
  80966. return B;
  80967. };
  80968. var ContactEquation_getImpactVelocityAlongNormal_vi = new Vec3();
  80969. var ContactEquation_getImpactVelocityAlongNormal_vj = new Vec3();
  80970. var ContactEquation_getImpactVelocityAlongNormal_xi = new Vec3();
  80971. var ContactEquation_getImpactVelocityAlongNormal_xj = new Vec3();
  80972. var ContactEquation_getImpactVelocityAlongNormal_relVel = new Vec3();
  80973. /**
  80974. * Get the current relative velocity in the contact point.
  80975. * @method getImpactVelocityAlongNormal
  80976. * @return {number}
  80977. */
  80978. ContactEquation.prototype.getImpactVelocityAlongNormal = function(){
  80979. var vi = ContactEquation_getImpactVelocityAlongNormal_vi;
  80980. var vj = ContactEquation_getImpactVelocityAlongNormal_vj;
  80981. var xi = ContactEquation_getImpactVelocityAlongNormal_xi;
  80982. var xj = ContactEquation_getImpactVelocityAlongNormal_xj;
  80983. var relVel = ContactEquation_getImpactVelocityAlongNormal_relVel;
  80984. this.bi.position.vadd(this.ri, xi);
  80985. this.bj.position.vadd(this.rj, xj);
  80986. this.bi.getVelocityAtWorldPoint(xi, vi);
  80987. this.bj.getVelocityAtWorldPoint(xj, vj);
  80988. vi.vsub(vj, relVel);
  80989. return this.ni.dot(relVel);
  80990. };
  80991. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],20:[function(_dereq_,module,exports){
  80992. module.exports = Equation;
  80993. var JacobianElement = _dereq_('../math/JacobianElement'),
  80994. Vec3 = _dereq_('../math/Vec3');
  80995. /**
  80996. * Equation base class
  80997. * @class Equation
  80998. * @constructor
  80999. * @author schteppe
  81000. * @param {Body} bi
  81001. * @param {Body} bj
  81002. * @param {Number} minForce Minimum (read: negative max) force to be applied by the constraint.
  81003. * @param {Number} maxForce Maximum (read: positive max) force to be applied by the constraint.
  81004. */
  81005. function Equation(bi,bj,minForce,maxForce){
  81006. this.id = Equation.id++;
  81007. /**
  81008. * @property {number} minForce
  81009. */
  81010. this.minForce = typeof(minForce)==="undefined" ? -1e6 : minForce;
  81011. /**
  81012. * @property {number} maxForce
  81013. */
  81014. this.maxForce = typeof(maxForce)==="undefined" ? 1e6 : maxForce;
  81015. /**
  81016. * @property bi
  81017. * @type {Body}
  81018. */
  81019. this.bi = bi;
  81020. /**
  81021. * @property bj
  81022. * @type {Body}
  81023. */
  81024. this.bj = bj;
  81025. /**
  81026. * SPOOK parameter
  81027. * @property {number} a
  81028. */
  81029. this.a = 0.0;
  81030. /**
  81031. * SPOOK parameter
  81032. * @property {number} b
  81033. */
  81034. this.b = 0.0;
  81035. /**
  81036. * SPOOK parameter
  81037. * @property {number} eps
  81038. */
  81039. this.eps = 0.0;
  81040. /**
  81041. * @property {JacobianElement} jacobianElementA
  81042. */
  81043. this.jacobianElementA = new JacobianElement();
  81044. /**
  81045. * @property {JacobianElement} jacobianElementB
  81046. */
  81047. this.jacobianElementB = new JacobianElement();
  81048. /**
  81049. * @property {boolean} enabled
  81050. * @default true
  81051. */
  81052. this.enabled = true;
  81053. // Set typical spook params
  81054. this.setSpookParams(1e7,4,1/60);
  81055. }
  81056. Equation.prototype.constructor = Equation;
  81057. Equation.id = 0;
  81058. /**
  81059. * Recalculates a,b,eps.
  81060. * @method setSpookParams
  81061. */
  81062. Equation.prototype.setSpookParams = function(stiffness,relaxation,timeStep){
  81063. var d = relaxation,
  81064. k = stiffness,
  81065. h = timeStep;
  81066. this.a = 4.0 / (h * (1 + 4 * d));
  81067. this.b = (4.0 * d) / (1 + 4 * d);
  81068. this.eps = 4.0 / (h * h * k * (1 + 4 * d));
  81069. };
  81070. /**
  81071. * Computes the RHS of the SPOOK equation
  81072. * @method computeB
  81073. * @return {Number}
  81074. */
  81075. Equation.prototype.computeB = function(a,b,h){
  81076. var GW = this.computeGW(),
  81077. Gq = this.computeGq(),
  81078. GiMf = this.computeGiMf();
  81079. return - Gq * a - GW * b - GiMf*h;
  81080. };
  81081. /**
  81082. * Computes G*q, where q are the generalized body coordinates
  81083. * @method computeGq
  81084. * @return {Number}
  81085. */
  81086. Equation.prototype.computeGq = function(){
  81087. var GA = this.jacobianElementA,
  81088. GB = this.jacobianElementB,
  81089. bi = this.bi,
  81090. bj = this.bj,
  81091. xi = bi.position,
  81092. xj = bj.position;
  81093. return GA.spatial.dot(xi) + GB.spatial.dot(xj);
  81094. };
  81095. var zero = new Vec3();
  81096. /**
  81097. * Computes G*W, where W are the body velocities
  81098. * @method computeGW
  81099. * @return {Number}
  81100. */
  81101. Equation.prototype.computeGW = function(){
  81102. var GA = this.jacobianElementA,
  81103. GB = this.jacobianElementB,
  81104. bi = this.bi,
  81105. bj = this.bj,
  81106. vi = bi.velocity,
  81107. vj = bj.velocity,
  81108. wi = bi.angularVelocity || zero,
  81109. wj = bj.angularVelocity || zero;
  81110. return GA.multiplyVectors(vi,wi) + GB.multiplyVectors(vj,wj);
  81111. };
  81112. /**
  81113. * Computes G*Wlambda, where W are the body velocities
  81114. * @method computeGWlambda
  81115. * @return {Number}
  81116. */
  81117. Equation.prototype.computeGWlambda = function(){
  81118. var GA = this.jacobianElementA,
  81119. GB = this.jacobianElementB,
  81120. bi = this.bi,
  81121. bj = this.bj,
  81122. vi = bi.vlambda,
  81123. vj = bj.vlambda,
  81124. wi = bi.wlambda || zero,
  81125. wj = bj.wlambda || zero;
  81126. return GA.multiplyVectors(vi,wi) + GB.multiplyVectors(vj,wj);
  81127. };
  81128. /**
  81129. * Computes G*inv(M)*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies.
  81130. * @method computeGiMf
  81131. * @return {Number}
  81132. */
  81133. var iMfi = new Vec3(),
  81134. iMfj = new Vec3(),
  81135. invIi_vmult_taui = new Vec3(),
  81136. invIj_vmult_tauj = new Vec3();
  81137. Equation.prototype.computeGiMf = function(){
  81138. var GA = this.jacobianElementA,
  81139. GB = this.jacobianElementB,
  81140. bi = this.bi,
  81141. bj = this.bj,
  81142. fi = bi.force,
  81143. ti = bi.torque,
  81144. fj = bj.force,
  81145. tj = bj.torque,
  81146. invMassi = bi.invMassSolve,
  81147. invMassj = bj.invMassSolve;
  81148. if(bi.invInertiaWorldSolve){ bi.invInertiaWorldSolve.vmult(ti,invIi_vmult_taui); }
  81149. else { invIi_vmult_taui.set(0,0,0); }
  81150. if(bj.invInertiaWorldSolve){ bj.invInertiaWorldSolve.vmult(tj,invIj_vmult_tauj); }
  81151. else { invIj_vmult_tauj.set(0,0,0); }
  81152. fi.mult(invMassi,iMfi);
  81153. fj.mult(invMassj,iMfj);
  81154. return GA.multiplyVectors(iMfi,invIi_vmult_taui) + GB.multiplyVectors(iMfj,invIj_vmult_tauj);
  81155. };
  81156. /**
  81157. * Computes G*inv(M)*G'
  81158. * @method computeGiMGt
  81159. * @return {Number}
  81160. */
  81161. var tmp = new Vec3();
  81162. Equation.prototype.computeGiMGt = function(){
  81163. var GA = this.jacobianElementA,
  81164. GB = this.jacobianElementB,
  81165. bi = this.bi,
  81166. bj = this.bj,
  81167. invMassi = bi.invMassSolve,
  81168. invMassj = bj.invMassSolve,
  81169. invIi = bi.invInertiaWorldSolve,
  81170. invIj = bj.invInertiaWorldSolve,
  81171. result = invMassi + invMassj;
  81172. if(invIi){
  81173. invIi.vmult(GA.rotational,tmp);
  81174. result += tmp.dot(GA.rotational);
  81175. }
  81176. if(invIj){
  81177. invIj.vmult(GB.rotational,tmp);
  81178. result += tmp.dot(GB.rotational);
  81179. }
  81180. return result;
  81181. };
  81182. var addToWlambda_temp = new Vec3(),
  81183. addToWlambda_Gi = new Vec3(),
  81184. addToWlambda_Gj = new Vec3(),
  81185. addToWlambda_ri = new Vec3(),
  81186. addToWlambda_rj = new Vec3(),
  81187. addToWlambda_Mdiag = new Vec3();
  81188. /**
  81189. * Add constraint velocity to the bodies.
  81190. * @method addToWlambda
  81191. * @param {Number} deltalambda
  81192. */
  81193. Equation.prototype.addToWlambda = function(deltalambda){
  81194. var GA = this.jacobianElementA,
  81195. GB = this.jacobianElementB,
  81196. bi = this.bi,
  81197. bj = this.bj,
  81198. temp = addToWlambda_temp;
  81199. // Add to linear velocity
  81200. // v_lambda += inv(M) * delta_lamba * G
  81201. GA.spatial.mult(bi.invMassSolve * deltalambda,temp);
  81202. bi.vlambda.vadd(temp, bi.vlambda);
  81203. GB.spatial.mult(bj.invMassSolve * deltalambda,temp);
  81204. bj.vlambda.vadd(temp, bj.vlambda);
  81205. // Add to angular velocity
  81206. if(bi.invInertiaWorldSolve){
  81207. bi.invInertiaWorldSolve.vmult(GA.rotational,temp);
  81208. temp.mult(deltalambda,temp);
  81209. bi.wlambda.vadd(temp,bi.wlambda);
  81210. }
  81211. if(bj.invInertiaWorldSolve){
  81212. bj.invInertiaWorldSolve.vmult(GB.rotational,temp);
  81213. temp.mult(deltalambda,temp);
  81214. bj.wlambda.vadd(temp,bj.wlambda);
  81215. }
  81216. };
  81217. /**
  81218. * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps
  81219. * @method computeInvC
  81220. * @param {Number} eps
  81221. * @return {Number}
  81222. */
  81223. Equation.prototype.computeC = function(){
  81224. return this.computeGiMGt() + this.eps;
  81225. };
  81226. },{"../math/JacobianElement":26,"../math/Vec3":30}],21:[function(_dereq_,module,exports){
  81227. module.exports = FrictionEquation;
  81228. var Equation = _dereq_('./Equation');
  81229. var Vec3 = _dereq_('../math/Vec3');
  81230. var Mat3 = _dereq_('../math/Mat3');
  81231. /**
  81232. * Constrains the slipping in a contact along a tangent
  81233. * @class FrictionEquation
  81234. * @constructor
  81235. * @author schteppe
  81236. * @param {Body} bodyA
  81237. * @param {Body} bodyB
  81238. * @param {Number} slipForce should be +-F_friction = +-mu * F_normal = +-mu * m * g
  81239. * @extends Equation
  81240. */
  81241. function FrictionEquation(bodyA, bodyB, slipForce){
  81242. Equation.call(this,bodyA, bodyB, -slipForce, slipForce);
  81243. this.ri = new Vec3();
  81244. this.rj = new Vec3();
  81245. this.t = new Vec3(); // tangent
  81246. }
  81247. FrictionEquation.prototype = new Equation();
  81248. FrictionEquation.prototype.constructor = FrictionEquation;
  81249. var FrictionEquation_computeB_temp1 = new Vec3();
  81250. var FrictionEquation_computeB_temp2 = new Vec3();
  81251. FrictionEquation.prototype.computeB = function(h){
  81252. var a = this.a,
  81253. b = this.b,
  81254. bi = this.bi,
  81255. bj = this.bj,
  81256. ri = this.ri,
  81257. rj = this.rj,
  81258. rixt = FrictionEquation_computeB_temp1,
  81259. rjxt = FrictionEquation_computeB_temp2,
  81260. t = this.t;
  81261. // Caluclate cross products
  81262. ri.cross(t,rixt);
  81263. rj.cross(t,rjxt);
  81264. // G = [-t -rixt t rjxt]
  81265. // And remember, this is a pure velocity constraint, g is always zero!
  81266. var GA = this.jacobianElementA,
  81267. GB = this.jacobianElementB;
  81268. t.negate(GA.spatial);
  81269. rixt.negate(GA.rotational);
  81270. GB.spatial.copy(t);
  81271. GB.rotational.copy(rjxt);
  81272. var GW = this.computeGW();
  81273. var GiMf = this.computeGiMf();
  81274. var B = - GW * b - h * GiMf;
  81275. return B;
  81276. };
  81277. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],22:[function(_dereq_,module,exports){
  81278. module.exports = RotationalEquation;
  81279. var Vec3 = _dereq_('../math/Vec3');
  81280. var Mat3 = _dereq_('../math/Mat3');
  81281. var Equation = _dereq_('./Equation');
  81282. /**
  81283. * Rotational constraint. Works to keep the local vectors orthogonal to each other in world space.
  81284. * @class RotationalEquation
  81285. * @constructor
  81286. * @author schteppe
  81287. * @param {Body} bodyA
  81288. * @param {Body} bodyB
  81289. * @param {Vec3} [options.axisA]
  81290. * @param {Vec3} [options.axisB]
  81291. * @param {number} [options.maxForce]
  81292. * @extends Equation
  81293. */
  81294. function RotationalEquation(bodyA, bodyB, options){
  81295. options = options || {};
  81296. var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
  81297. Equation.call(this,bodyA,bodyB,-maxForce, maxForce);
  81298. this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
  81299. this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);
  81300. this.maxAngle = Math.PI / 2;
  81301. }
  81302. RotationalEquation.prototype = new Equation();
  81303. RotationalEquation.prototype.constructor = RotationalEquation;
  81304. var tmpVec1 = new Vec3();
  81305. var tmpVec2 = new Vec3();
  81306. RotationalEquation.prototype.computeB = function(h){
  81307. var a = this.a,
  81308. b = this.b,
  81309. ni = this.axisA,
  81310. nj = this.axisB,
  81311. nixnj = tmpVec1,
  81312. njxni = tmpVec2,
  81313. GA = this.jacobianElementA,
  81314. GB = this.jacobianElementB;
  81315. // Caluclate cross products
  81316. ni.cross(nj, nixnj);
  81317. nj.cross(ni, njxni);
  81318. // g = ni * nj
  81319. // gdot = (nj x ni) * wi + (ni x nj) * wj
  81320. // G = [0 njxni 0 nixnj]
  81321. // W = [vi wi vj wj]
  81322. GA.rotational.copy(njxni);
  81323. GB.rotational.copy(nixnj);
  81324. var g = Math.cos(this.maxAngle) - ni.dot(nj),
  81325. GW = this.computeGW(),
  81326. GiMf = this.computeGiMf();
  81327. var B = - g * a - GW * b - h * GiMf;
  81328. return B;
  81329. };
  81330. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],23:[function(_dereq_,module,exports){
  81331. module.exports = RotationalMotorEquation;
  81332. var Vec3 = _dereq_('../math/Vec3');
  81333. var Mat3 = _dereq_('../math/Mat3');
  81334. var Equation = _dereq_('./Equation');
  81335. /**
  81336. * Rotational motor constraint. Tries to keep the relative angular velocity of the bodies to a given value.
  81337. * @class RotationalMotorEquation
  81338. * @constructor
  81339. * @author schteppe
  81340. * @param {Body} bodyA
  81341. * @param {Body} bodyB
  81342. * @param {Number} maxForce
  81343. * @extends Equation
  81344. */
  81345. function RotationalMotorEquation(bodyA, bodyB, maxForce){
  81346. maxForce = typeof(maxForce)!=='undefined' ? maxForce : 1e6;
  81347. Equation.call(this,bodyA,bodyB,-maxForce,maxForce);
  81348. /**
  81349. * World oriented rotational axis
  81350. * @property {Vec3} axisA
  81351. */
  81352. this.axisA = new Vec3();
  81353. /**
  81354. * World oriented rotational axis
  81355. * @property {Vec3} axisB
  81356. */
  81357. this.axisB = new Vec3(); // World oriented rotational axis
  81358. /**
  81359. * Motor velocity
  81360. * @property {Number} targetVelocity
  81361. */
  81362. this.targetVelocity = 0;
  81363. }
  81364. RotationalMotorEquation.prototype = new Equation();
  81365. RotationalMotorEquation.prototype.constructor = RotationalMotorEquation;
  81366. RotationalMotorEquation.prototype.computeB = function(h){
  81367. var a = this.a,
  81368. b = this.b,
  81369. bi = this.bi,
  81370. bj = this.bj,
  81371. axisA = this.axisA,
  81372. axisB = this.axisB,
  81373. GA = this.jacobianElementA,
  81374. GB = this.jacobianElementB;
  81375. // g = 0
  81376. // gdot = axisA * wi - axisB * wj
  81377. // gdot = G * W = G * [vi wi vj wj]
  81378. // =>
  81379. // G = [0 axisA 0 -axisB]
  81380. GA.rotational.copy(axisA);
  81381. axisB.negate(GB.rotational);
  81382. var GW = this.computeGW() - this.targetVelocity,
  81383. GiMf = this.computeGiMf();
  81384. var B = - GW * b - h * GiMf;
  81385. return B;
  81386. };
  81387. },{"../math/Mat3":27,"../math/Vec3":30,"./Equation":20}],24:[function(_dereq_,module,exports){
  81388. var Utils = _dereq_('../utils/Utils');
  81389. module.exports = ContactMaterial;
  81390. /**
  81391. * Defines what happens when two materials meet.
  81392. * @class ContactMaterial
  81393. * @constructor
  81394. * @param {Material} m1
  81395. * @param {Material} m2
  81396. * @param {object} [options]
  81397. * @param {Number} [options.friction=0.3]
  81398. * @param {Number} [options.restitution=0.3]
  81399. * @param {number} [options.contactEquationStiffness=1e7]
  81400. * @param {number} [options.contactEquationRelaxation=3]
  81401. * @param {number} [options.frictionEquationStiffness=1e7]
  81402. * @param {Number} [options.frictionEquationRelaxation=3]
  81403. */
  81404. function ContactMaterial(m1, m2, options){
  81405. options = Utils.defaults(options, {
  81406. friction: 0.3,
  81407. restitution: 0.3,
  81408. contactEquationStiffness: 1e7,
  81409. contactEquationRelaxation: 3,
  81410. frictionEquationStiffness: 1e7,
  81411. frictionEquationRelaxation: 3
  81412. });
  81413. /**
  81414. * Identifier of this material
  81415. * @property {Number} id
  81416. */
  81417. this.id = ContactMaterial.idCounter++;
  81418. /**
  81419. * Participating materials
  81420. * @property {Array} materials
  81421. * @todo Should be .materialA and .materialB instead
  81422. */
  81423. this.materials = [m1, m2];
  81424. /**
  81425. * Friction coefficient
  81426. * @property {Number} friction
  81427. */
  81428. this.friction = options.friction;
  81429. /**
  81430. * Restitution coefficient
  81431. * @property {Number} restitution
  81432. */
  81433. this.restitution = options.restitution;
  81434. /**
  81435. * Stiffness of the produced contact equations
  81436. * @property {Number} contactEquationStiffness
  81437. */
  81438. this.contactEquationStiffness = options.contactEquationStiffness;
  81439. /**
  81440. * Relaxation time of the produced contact equations
  81441. * @property {Number} contactEquationRelaxation
  81442. */
  81443. this.contactEquationRelaxation = options.contactEquationRelaxation;
  81444. /**
  81445. * Stiffness of the produced friction equations
  81446. * @property {Number} frictionEquationStiffness
  81447. */
  81448. this.frictionEquationStiffness = options.frictionEquationStiffness;
  81449. /**
  81450. * Relaxation time of the produced friction equations
  81451. * @property {Number} frictionEquationRelaxation
  81452. */
  81453. this.frictionEquationRelaxation = options.frictionEquationRelaxation;
  81454. }
  81455. ContactMaterial.idCounter = 0;
  81456. },{"../utils/Utils":53}],25:[function(_dereq_,module,exports){
  81457. module.exports = Material;
  81458. /**
  81459. * Defines a physics material.
  81460. * @class Material
  81461. * @constructor
  81462. * @param {object} [options]
  81463. * @author schteppe
  81464. */
  81465. function Material(options){
  81466. var name = '';
  81467. options = options || {};
  81468. // Backwards compatibility fix
  81469. if(typeof(options) === 'string'){
  81470. name = options;
  81471. options = {};
  81472. } else if(typeof(options) === 'object') {
  81473. name = '';
  81474. }
  81475. /**
  81476. * @property name
  81477. * @type {String}
  81478. */
  81479. this.name = name;
  81480. /**
  81481. * material id.
  81482. * @property id
  81483. * @type {number}
  81484. */
  81485. this.id = Material.idCounter++;
  81486. /**
  81487. * Friction for this material. If non-negative, it will be used instead of the friction given by ContactMaterials. If there's no matching ContactMaterial, the value from .defaultContactMaterial in the World will be used.
  81488. * @property {number} friction
  81489. */
  81490. this.friction = typeof(options.friction) !== 'undefined' ? options.friction : -1;
  81491. /**
  81492. * Restitution for this material. If non-negative, it will be used instead of the restitution given by ContactMaterials. If there's no matching ContactMaterial, the value from .defaultContactMaterial in the World will be used.
  81493. * @property {number} restitution
  81494. */
  81495. this.restitution = typeof(options.restitution) !== 'undefined' ? options.restitution : -1;
  81496. }
  81497. Material.idCounter = 0;
  81498. },{}],26:[function(_dereq_,module,exports){
  81499. module.exports = JacobianElement;
  81500. var Vec3 = _dereq_('./Vec3');
  81501. /**
  81502. * An element containing 6 entries, 3 spatial and 3 rotational degrees of freedom.
  81503. * @class JacobianElement
  81504. * @constructor
  81505. */
  81506. function JacobianElement(){
  81507. /**
  81508. * @property {Vec3} spatial
  81509. */
  81510. this.spatial = new Vec3();
  81511. /**
  81512. * @property {Vec3} rotational
  81513. */
  81514. this.rotational = new Vec3();
  81515. }
  81516. /**
  81517. * Multiply with other JacobianElement
  81518. * @method multiplyElement
  81519. * @param {JacobianElement} element
  81520. * @return {Number}
  81521. */
  81522. JacobianElement.prototype.multiplyElement = function(element){
  81523. return element.spatial.dot(this.spatial) + element.rotational.dot(this.rotational);
  81524. };
  81525. /**
  81526. * Multiply with two vectors
  81527. * @method multiplyVectors
  81528. * @param {Vec3} spatial
  81529. * @param {Vec3} rotational
  81530. * @return {Number}
  81531. */
  81532. JacobianElement.prototype.multiplyVectors = function(spatial,rotational){
  81533. return spatial.dot(this.spatial) + rotational.dot(this.rotational);
  81534. };
  81535. },{"./Vec3":30}],27:[function(_dereq_,module,exports){
  81536. module.exports = Mat3;
  81537. var Vec3 = _dereq_('./Vec3');
  81538. /**
  81539. * A 3x3 matrix.
  81540. * @class Mat3
  81541. * @constructor
  81542. * @param array elements Array of nine elements. Optional.
  81543. * @author schteppe / http://github.com/schteppe
  81544. */
  81545. function Mat3(elements){
  81546. /**
  81547. * A vector of length 9, containing all matrix elements
  81548. * @property {Array} elements
  81549. */
  81550. if(elements){
  81551. this.elements = elements;
  81552. } else {
  81553. this.elements = [0,0,0,0,0,0,0,0,0];
  81554. }
  81555. }
  81556. /**
  81557. * Sets the matrix to identity
  81558. * @method identity
  81559. * @todo Should perhaps be renamed to setIdentity() to be more clear.
  81560. * @todo Create another function that immediately creates an identity matrix eg. eye()
  81561. */
  81562. Mat3.prototype.identity = function(){
  81563. var e = this.elements;
  81564. e[0] = 1;
  81565. e[1] = 0;
  81566. e[2] = 0;
  81567. e[3] = 0;
  81568. e[4] = 1;
  81569. e[5] = 0;
  81570. e[6] = 0;
  81571. e[7] = 0;
  81572. e[8] = 1;
  81573. };
  81574. /**
  81575. * Set all elements to zero
  81576. * @method setZero
  81577. */
  81578. Mat3.prototype.setZero = function(){
  81579. var e = this.elements;
  81580. e[0] = 0;
  81581. e[1] = 0;
  81582. e[2] = 0;
  81583. e[3] = 0;
  81584. e[4] = 0;
  81585. e[5] = 0;
  81586. e[6] = 0;
  81587. e[7] = 0;
  81588. e[8] = 0;
  81589. };
  81590. /**
  81591. * Sets the matrix diagonal elements from a Vec3
  81592. * @method setTrace
  81593. * @param {Vec3} vec3
  81594. */
  81595. Mat3.prototype.setTrace = function(vec3){
  81596. var e = this.elements;
  81597. e[0] = vec3.x;
  81598. e[4] = vec3.y;
  81599. e[8] = vec3.z;
  81600. };
  81601. /**
  81602. * Gets the matrix diagonal elements
  81603. * @method getTrace
  81604. * @return {Vec3}
  81605. */
  81606. Mat3.prototype.getTrace = function(target){
  81607. var target = target || new Vec3();
  81608. var e = this.elements;
  81609. target.x = e[0];
  81610. target.y = e[4];
  81611. target.z = e[8];
  81612. };
  81613. /**
  81614. * Matrix-Vector multiplication
  81615. * @method vmult
  81616. * @param {Vec3} v The vector to multiply with
  81617. * @param {Vec3} target Optional, target to save the result in.
  81618. */
  81619. Mat3.prototype.vmult = function(v,target){
  81620. target = target || new Vec3();
  81621. var e = this.elements,
  81622. x = v.x,
  81623. y = v.y,
  81624. z = v.z;
  81625. target.x = e[0]*x + e[1]*y + e[2]*z;
  81626. target.y = e[3]*x + e[4]*y + e[5]*z;
  81627. target.z = e[6]*x + e[7]*y + e[8]*z;
  81628. return target;
  81629. };
  81630. /**
  81631. * Matrix-scalar multiplication
  81632. * @method smult
  81633. * @param {Number} s
  81634. */
  81635. Mat3.prototype.smult = function(s){
  81636. for(var i=0; i<this.elements.length; i++){
  81637. this.elements[i] *= s;
  81638. }
  81639. };
  81640. /**
  81641. * Matrix multiplication
  81642. * @method mmult
  81643. * @param {Mat3} m Matrix to multiply with from left side.
  81644. * @return {Mat3} The result.
  81645. */
  81646. Mat3.prototype.mmult = function(m,target){
  81647. var r = target || new Mat3();
  81648. for(var i=0; i<3; i++){
  81649. for(var j=0; j<3; j++){
  81650. var sum = 0.0;
  81651. for(var k=0; k<3; k++){
  81652. sum += m.elements[i+k*3] * this.elements[k+j*3];
  81653. }
  81654. r.elements[i+j*3] = sum;
  81655. }
  81656. }
  81657. return r;
  81658. };
  81659. /**
  81660. * Scale each column of the matrix
  81661. * @method scale
  81662. * @param {Vec3} v
  81663. * @return {Mat3} The result.
  81664. */
  81665. Mat3.prototype.scale = function(v,target){
  81666. target = target || new Mat3();
  81667. var e = this.elements,
  81668. t = target.elements;
  81669. for(var i=0; i!==3; i++){
  81670. t[3*i + 0] = v.x * e[3*i + 0];
  81671. t[3*i + 1] = v.y * e[3*i + 1];
  81672. t[3*i + 2] = v.z * e[3*i + 2];
  81673. }
  81674. return target;
  81675. };
  81676. /**
  81677. * Solve Ax=b
  81678. * @method solve
  81679. * @param {Vec3} b The right hand side
  81680. * @param {Vec3} target Optional. Target vector to save in.
  81681. * @return {Vec3} The solution x
  81682. * @todo should reuse arrays
  81683. */
  81684. Mat3.prototype.solve = function(b,target){
  81685. target = target || new Vec3();
  81686. // Construct equations
  81687. var nr = 3; // num rows
  81688. var nc = 4; // num cols
  81689. var eqns = [];
  81690. for(var i=0; i<nr*nc; i++){
  81691. eqns.push(0);
  81692. }
  81693. var i,j;
  81694. for(i=0; i<3; i++){
  81695. for(j=0; j<3; j++){
  81696. eqns[i+nc*j] = this.elements[i+3*j];
  81697. }
  81698. }
  81699. eqns[3+4*0] = b.x;
  81700. eqns[3+4*1] = b.y;
  81701. eqns[3+4*2] = b.z;
  81702. // Compute right upper triangular version of the matrix - Gauss elimination
  81703. var n = 3, k = n, np;
  81704. var kp = 4; // num rows
  81705. var p, els;
  81706. do {
  81707. i = k - n;
  81708. if (eqns[i+nc*i] === 0) {
  81709. // the pivot is null, swap lines
  81710. for (j = i + 1; j < k; j++) {
  81711. if (eqns[i+nc*j] !== 0) {
  81712. np = kp;
  81713. do { // do ligne( i ) = ligne( i ) + ligne( k )
  81714. p = kp - np;
  81715. eqns[p+nc*i] += eqns[p+nc*j];
  81716. } while (--np);
  81717. break;
  81718. }
  81719. }
  81720. }
  81721. if (eqns[i+nc*i] !== 0) {
  81722. for (j = i + 1; j < k; j++) {
  81723. var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
  81724. np = kp;
  81725. do { // do ligne( k ) = ligne( k ) - multiplier * ligne( i )
  81726. p = kp - np;
  81727. eqns[p+nc*j] = p <= i ? 0 : eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
  81728. } while (--np);
  81729. }
  81730. }
  81731. } while (--n);
  81732. // Get the solution
  81733. target.z = eqns[2*nc+3] / eqns[2*nc+2];
  81734. target.y = (eqns[1*nc+3] - eqns[1*nc+2]*target.z) / eqns[1*nc+1];
  81735. target.x = (eqns[0*nc+3] - eqns[0*nc+2]*target.z - eqns[0*nc+1]*target.y) / eqns[0*nc+0];
  81736. if(isNaN(target.x) || isNaN(target.y) || isNaN(target.z) || target.x===Infinity || target.y===Infinity || target.z===Infinity){
  81737. throw "Could not solve equation! Got x=["+target.toString()+"], b=["+b.toString()+"], A=["+this.toString()+"]";
  81738. }
  81739. return target;
  81740. };
  81741. /**
  81742. * Get an element in the matrix by index. Index starts at 0, not 1!!!
  81743. * @method e
  81744. * @param {Number} row
  81745. * @param {Number} column
  81746. * @param {Number} value Optional. If provided, the matrix element will be set to this value.
  81747. * @return {Number}
  81748. */
  81749. Mat3.prototype.e = function( row , column ,value){
  81750. if(value===undefined){
  81751. return this.elements[column+3*row];
  81752. } else {
  81753. // Set value
  81754. this.elements[column+3*row] = value;
  81755. }
  81756. };
  81757. /**
  81758. * Copy another matrix into this matrix object.
  81759. * @method copy
  81760. * @param {Mat3} source
  81761. * @return {Mat3} this
  81762. */
  81763. Mat3.prototype.copy = function(source){
  81764. for(var i=0; i < source.elements.length; i++){
  81765. this.elements[i] = source.elements[i];
  81766. }
  81767. return this;
  81768. };
  81769. /**
  81770. * Returns a string representation of the matrix.
  81771. * @method toString
  81772. * @return string
  81773. */
  81774. Mat3.prototype.toString = function(){
  81775. var r = "";
  81776. var sep = ",";
  81777. for(var i=0; i<9; i++){
  81778. r += this.elements[i] + sep;
  81779. }
  81780. return r;
  81781. };
  81782. /**
  81783. * reverse the matrix
  81784. * @method reverse
  81785. * @param {Mat3} target Optional. Target matrix to save in.
  81786. * @return {Mat3} The solution x
  81787. */
  81788. Mat3.prototype.reverse = function(target){
  81789. target = target || new Mat3();
  81790. // Construct equations
  81791. var nr = 3; // num rows
  81792. var nc = 6; // num cols
  81793. var eqns = [];
  81794. for(var i=0; i<nr*nc; i++){
  81795. eqns.push(0);
  81796. }
  81797. var i,j;
  81798. for(i=0; i<3; i++){
  81799. for(j=0; j<3; j++){
  81800. eqns[i+nc*j] = this.elements[i+3*j];
  81801. }
  81802. }
  81803. eqns[3+6*0] = 1;
  81804. eqns[3+6*1] = 0;
  81805. eqns[3+6*2] = 0;
  81806. eqns[4+6*0] = 0;
  81807. eqns[4+6*1] = 1;
  81808. eqns[4+6*2] = 0;
  81809. eqns[5+6*0] = 0;
  81810. eqns[5+6*1] = 0;
  81811. eqns[5+6*2] = 1;
  81812. // Compute right upper triangular version of the matrix - Gauss elimination
  81813. var n = 3, k = n, np;
  81814. var kp = nc; // num rows
  81815. var p;
  81816. do {
  81817. i = k - n;
  81818. if (eqns[i+nc*i] === 0) {
  81819. // the pivot is null, swap lines
  81820. for (j = i + 1; j < k; j++) {
  81821. if (eqns[i+nc*j] !== 0) {
  81822. np = kp;
  81823. do { // do line( i ) = line( i ) + line( k )
  81824. p = kp - np;
  81825. eqns[p+nc*i] += eqns[p+nc*j];
  81826. } while (--np);
  81827. break;
  81828. }
  81829. }
  81830. }
  81831. if (eqns[i+nc*i] !== 0) {
  81832. for (j = i + 1; j < k; j++) {
  81833. var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
  81834. np = kp;
  81835. do { // do line( k ) = line( k ) - multiplier * line( i )
  81836. p = kp - np;
  81837. eqns[p+nc*j] = p <= i ? 0 : eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
  81838. } while (--np);
  81839. }
  81840. }
  81841. } while (--n);
  81842. // eliminate the upper left triangle of the matrix
  81843. i = 2;
  81844. do {
  81845. j = i-1;
  81846. do {
  81847. var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
  81848. np = nc;
  81849. do {
  81850. p = nc - np;
  81851. eqns[p+nc*j] = eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
  81852. } while (--np);
  81853. } while (j--);
  81854. } while (--i);
  81855. // operations on the diagonal
  81856. i = 2;
  81857. do {
  81858. var multiplier = 1 / eqns[i+nc*i];
  81859. np = nc;
  81860. do {
  81861. p = nc - np;
  81862. eqns[p+nc*i] = eqns[p+nc*i] * multiplier ;
  81863. } while (--np);
  81864. } while (i--);
  81865. i = 2;
  81866. do {
  81867. j = 2;
  81868. do {
  81869. p = eqns[nr+j+nc*i];
  81870. if( isNaN( p ) || p ===Infinity ){
  81871. throw "Could not reverse! A=["+this.toString()+"]";
  81872. }
  81873. target.e( i , j , p );
  81874. } while (j--);
  81875. } while (i--);
  81876. return target;
  81877. };
  81878. /**
  81879. * Set the matrix from a quaterion
  81880. * @method setRotationFromQuaternion
  81881. * @param {Quaternion} q
  81882. */
  81883. Mat3.prototype.setRotationFromQuaternion = function( q ) {
  81884. var x = q.x, y = q.y, z = q.z, w = q.w,
  81885. x2 = x + x, y2 = y + y, z2 = z + z,
  81886. xx = x * x2, xy = x * y2, xz = x * z2,
  81887. yy = y * y2, yz = y * z2, zz = z * z2,
  81888. wx = w * x2, wy = w * y2, wz = w * z2,
  81889. e = this.elements;
  81890. e[3*0 + 0] = 1 - ( yy + zz );
  81891. e[3*0 + 1] = xy - wz;
  81892. e[3*0 + 2] = xz + wy;
  81893. e[3*1 + 0] = xy + wz;
  81894. e[3*1 + 1] = 1 - ( xx + zz );
  81895. e[3*1 + 2] = yz - wx;
  81896. e[3*2 + 0] = xz - wy;
  81897. e[3*2 + 1] = yz + wx;
  81898. e[3*2 + 2] = 1 - ( xx + yy );
  81899. return this;
  81900. };
  81901. /**
  81902. * Transpose the matrix
  81903. * @method transpose
  81904. * @param {Mat3} target Where to store the result.
  81905. * @return {Mat3} The target Mat3, or a new Mat3 if target was omitted.
  81906. */
  81907. Mat3.prototype.transpose = function( target ) {
  81908. target = target || new Mat3();
  81909. var Mt = target.elements,
  81910. M = this.elements;
  81911. for(var i=0; i!==3; i++){
  81912. for(var j=0; j!==3; j++){
  81913. Mt[3*i + j] = M[3*j + i];
  81914. }
  81915. }
  81916. return target;
  81917. };
  81918. },{"./Vec3":30}],28:[function(_dereq_,module,exports){
  81919. module.exports = Quaternion;
  81920. var Vec3 = _dereq_('./Vec3');
  81921. /**
  81922. * A Quaternion describes a rotation in 3D space. The Quaternion is mathematically defined as Q = x*i + y*j + z*k + w, where (i,j,k) are imaginary basis vectors. (x,y,z) can be seen as a vector related to the axis of rotation, while the real multiplier, w, is related to the amount of rotation.
  81923. * @class Quaternion
  81924. * @constructor
  81925. * @param {Number} x Multiplier of the imaginary basis vector i.
  81926. * @param {Number} y Multiplier of the imaginary basis vector j.
  81927. * @param {Number} z Multiplier of the imaginary basis vector k.
  81928. * @param {Number} w Multiplier of the real part.
  81929. * @see http://en.wikipedia.org/wiki/Quaternion
  81930. */
  81931. function Quaternion(x,y,z,w){
  81932. /**
  81933. * @property {Number} x
  81934. */
  81935. this.x = x!==undefined ? x : 0;
  81936. /**
  81937. * @property {Number} y
  81938. */
  81939. this.y = y!==undefined ? y : 0;
  81940. /**
  81941. * @property {Number} z
  81942. */
  81943. this.z = z!==undefined ? z : 0;
  81944. /**
  81945. * The multiplier of the real quaternion basis vector.
  81946. * @property {Number} w
  81947. */
  81948. this.w = w!==undefined ? w : 1;
  81949. }
  81950. /**
  81951. * Set the value of the quaternion.
  81952. * @method set
  81953. * @param {Number} x
  81954. * @param {Number} y
  81955. * @param {Number} z
  81956. * @param {Number} w
  81957. */
  81958. Quaternion.prototype.set = function(x,y,z,w){
  81959. this.x = x;
  81960. this.y = y;
  81961. this.z = z;
  81962. this.w = w;
  81963. };
  81964. /**
  81965. * Convert to a readable format
  81966. * @method toString
  81967. * @return string
  81968. */
  81969. Quaternion.prototype.toString = function(){
  81970. return this.x+","+this.y+","+this.z+","+this.w;
  81971. };
  81972. /**
  81973. * Convert to an Array
  81974. * @method toArray
  81975. * @return Array
  81976. */
  81977. Quaternion.prototype.toArray = function(){
  81978. return [this.x, this.y, this.z, this.w];
  81979. };
  81980. /**
  81981. * Set the quaternion components given an axis and an angle.
  81982. * @method setFromAxisAngle
  81983. * @param {Vec3} axis
  81984. * @param {Number} angle in radians
  81985. */
  81986. Quaternion.prototype.setFromAxisAngle = function(axis,angle){
  81987. var s = Math.sin(angle*0.5);
  81988. this.x = axis.x * s;
  81989. this.y = axis.y * s;
  81990. this.z = axis.z * s;
  81991. this.w = Math.cos(angle*0.5);
  81992. };
  81993. /**
  81994. * Converts the quaternion to axis/angle representation.
  81995. * @method toAxisAngle
  81996. * @param {Vec3} targetAxis Optional. A vector object to reuse for storing the axis.
  81997. * @return Array An array, first elemnt is the axis and the second is the angle in radians.
  81998. */
  81999. Quaternion.prototype.toAxisAngle = function(targetAxis){
  82000. targetAxis = targetAxis || new Vec3();
  82001. this.normalize(); // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised
  82002. var angle = 2 * Math.acos(this.w);
  82003. var s = Math.sqrt(1-this.w*this.w); // assuming quaternion normalised then w is less than 1, so term always positive.
  82004. if (s < 0.001) { // test to avoid divide by zero, s is always positive due to sqrt
  82005. // if s close to zero then direction of axis not important
  82006. targetAxis.x = this.x; // if it is important that axis is normalised then replace with x=1; y=z=0;
  82007. targetAxis.y = this.y;
  82008. targetAxis.z = this.z;
  82009. } else {
  82010. targetAxis.x = this.x / s; // normalise axis
  82011. targetAxis.y = this.y / s;
  82012. targetAxis.z = this.z / s;
  82013. }
  82014. return [targetAxis,angle];
  82015. };
  82016. var sfv_t1 = new Vec3(),
  82017. sfv_t2 = new Vec3();
  82018. /**
  82019. * Set the quaternion value given two vectors. The resulting rotation will be the needed rotation to rotate u to v.
  82020. * @method setFromVectors
  82021. * @param {Vec3} u
  82022. * @param {Vec3} v
  82023. */
  82024. Quaternion.prototype.setFromVectors = function(u,v){
  82025. if(u.isAntiparallelTo(v)){
  82026. var t1 = sfv_t1;
  82027. var t2 = sfv_t2;
  82028. u.tangents(t1,t2);
  82029. this.setFromAxisAngle(t1,Math.PI);
  82030. } else {
  82031. var a = u.cross(v);
  82032. this.x = a.x;
  82033. this.y = a.y;
  82034. this.z = a.z;
  82035. this.w = Math.sqrt(Math.pow(u.norm(),2) * Math.pow(v.norm(),2)) + u.dot(v);
  82036. this.normalize();
  82037. }
  82038. };
  82039. /**
  82040. * Quaternion multiplication
  82041. * @method mult
  82042. * @param {Quaternion} q
  82043. * @param {Quaternion} target Optional.
  82044. * @return {Quaternion}
  82045. */
  82046. var Quaternion_mult_va = new Vec3();
  82047. var Quaternion_mult_vb = new Vec3();
  82048. var Quaternion_mult_vaxvb = new Vec3();
  82049. Quaternion.prototype.mult = function(q,target){
  82050. target = target || new Quaternion();
  82051. var w = this.w,
  82052. va = Quaternion_mult_va,
  82053. vb = Quaternion_mult_vb,
  82054. vaxvb = Quaternion_mult_vaxvb;
  82055. va.set(this.x,this.y,this.z);
  82056. vb.set(q.x,q.y,q.z);
  82057. target.w = w*q.w - va.dot(vb);
  82058. va.cross(vb,vaxvb);
  82059. target.x = w * vb.x + q.w*va.x + vaxvb.x;
  82060. target.y = w * vb.y + q.w*va.y + vaxvb.y;
  82061. target.z = w * vb.z + q.w*va.z + vaxvb.z;
  82062. return target;
  82063. };
  82064. /**
  82065. * Get the inverse quaternion rotation.
  82066. * @method inverse
  82067. * @param {Quaternion} target
  82068. * @return {Quaternion}
  82069. */
  82070. Quaternion.prototype.inverse = function(target){
  82071. var x = this.x, y = this.y, z = this.z, w = this.w;
  82072. target = target || new Quaternion();
  82073. this.conjugate(target);
  82074. var inorm2 = 1/(x*x + y*y + z*z + w*w);
  82075. target.x *= inorm2;
  82076. target.y *= inorm2;
  82077. target.z *= inorm2;
  82078. target.w *= inorm2;
  82079. return target;
  82080. };
  82081. /**
  82082. * Get the quaternion conjugate
  82083. * @method conjugate
  82084. * @param {Quaternion} target
  82085. * @return {Quaternion}
  82086. */
  82087. Quaternion.prototype.conjugate = function(target){
  82088. target = target || new Quaternion();
  82089. target.x = -this.x;
  82090. target.y = -this.y;
  82091. target.z = -this.z;
  82092. target.w = this.w;
  82093. return target;
  82094. };
  82095. /**
  82096. * Normalize the quaternion. Note that this changes the values of the quaternion.
  82097. * @method normalize
  82098. */
  82099. Quaternion.prototype.normalize = function(){
  82100. var l = Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w);
  82101. if ( l === 0 ) {
  82102. this.x = 0;
  82103. this.y = 0;
  82104. this.z = 0;
  82105. this.w = 0;
  82106. } else {
  82107. l = 1 / l;
  82108. this.x *= l;
  82109. this.y *= l;
  82110. this.z *= l;
  82111. this.w *= l;
  82112. }
  82113. };
  82114. /**
  82115. * Approximation of quaternion normalization. Works best when quat is already almost-normalized.
  82116. * @method normalizeFast
  82117. * @see http://jsperf.com/fast-quaternion-normalization
  82118. * @author unphased, https://github.com/unphased
  82119. */
  82120. Quaternion.prototype.normalizeFast = function () {
  82121. var f = (3.0-(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w))/2.0;
  82122. if ( f === 0 ) {
  82123. this.x = 0;
  82124. this.y = 0;
  82125. this.z = 0;
  82126. this.w = 0;
  82127. } else {
  82128. this.x *= f;
  82129. this.y *= f;
  82130. this.z *= f;
  82131. this.w *= f;
  82132. }
  82133. };
  82134. /**
  82135. * Multiply the quaternion by a vector
  82136. * @method vmult
  82137. * @param {Vec3} v
  82138. * @param {Vec3} target Optional
  82139. * @return {Vec3}
  82140. */
  82141. Quaternion.prototype.vmult = function(v,target){
  82142. target = target || new Vec3();
  82143. var x = v.x,
  82144. y = v.y,
  82145. z = v.z;
  82146. var qx = this.x,
  82147. qy = this.y,
  82148. qz = this.z,
  82149. qw = this.w;
  82150. // q*v
  82151. var ix = qw * x + qy * z - qz * y,
  82152. iy = qw * y + qz * x - qx * z,
  82153. iz = qw * z + qx * y - qy * x,
  82154. iw = -qx * x - qy * y - qz * z;
  82155. target.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  82156. target.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  82157. target.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  82158. return target;
  82159. };
  82160. /**
  82161. * Copies value of source to this quaternion.
  82162. * @method copy
  82163. * @param {Quaternion} source
  82164. * @return {Quaternion} this
  82165. */
  82166. Quaternion.prototype.copy = function(source){
  82167. this.x = source.x;
  82168. this.y = source.y;
  82169. this.z = source.z;
  82170. this.w = source.w;
  82171. return this;
  82172. };
  82173. /**
  82174. * Convert the quaternion to euler angle representation. Order: YZX, as this page describes: http://www.euclideanspace.com/maths/standards/index.htm
  82175. * @method toEuler
  82176. * @param {Vec3} target
  82177. * @param string order Three-character string e.g. "YZX", which also is default.
  82178. */
  82179. Quaternion.prototype.toEuler = function(target,order){
  82180. order = order || "YZX";
  82181. var heading, attitude, bank;
  82182. var x = this.x, y = this.y, z = this.z, w = this.w;
  82183. switch(order){
  82184. case "YZX":
  82185. var test = x*y + z*w;
  82186. if (test > 0.499) { // singularity at north pole
  82187. heading = 2 * Math.atan2(x,w);
  82188. attitude = Math.PI/2;
  82189. bank = 0;
  82190. }
  82191. if (test < -0.499) { // singularity at south pole
  82192. heading = -2 * Math.atan2(x,w);
  82193. attitude = - Math.PI/2;
  82194. bank = 0;
  82195. }
  82196. if(isNaN(heading)){
  82197. var sqx = x*x;
  82198. var sqy = y*y;
  82199. var sqz = z*z;
  82200. heading = Math.atan2(2*y*w - 2*x*z , 1 - 2*sqy - 2*sqz); // Heading
  82201. attitude = Math.asin(2*test); // attitude
  82202. bank = Math.atan2(2*x*w - 2*y*z , 1 - 2*sqx - 2*sqz); // bank
  82203. }
  82204. break;
  82205. default:
  82206. throw new Error("Euler order "+order+" not supported yet.");
  82207. }
  82208. target.y = heading;
  82209. target.z = attitude;
  82210. target.x = bank;
  82211. };
  82212. /**
  82213. * See http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  82214. * @method setFromEuler
  82215. * @param {Number} x
  82216. * @param {Number} y
  82217. * @param {Number} z
  82218. * @param {String} order The order to apply angles: 'XYZ' or 'YXZ' or any other combination
  82219. */
  82220. Quaternion.prototype.setFromEuler = function ( x, y, z, order ) {
  82221. order = order || "XYZ";
  82222. var c1 = Math.cos( x / 2 );
  82223. var c2 = Math.cos( y / 2 );
  82224. var c3 = Math.cos( z / 2 );
  82225. var s1 = Math.sin( x / 2 );
  82226. var s2 = Math.sin( y / 2 );
  82227. var s3 = Math.sin( z / 2 );
  82228. if ( order === 'XYZ' ) {
  82229. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  82230. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  82231. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  82232. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  82233. } else if ( order === 'YXZ' ) {
  82234. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  82235. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  82236. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  82237. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  82238. } else if ( order === 'ZXY' ) {
  82239. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  82240. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  82241. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  82242. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  82243. } else if ( order === 'ZYX' ) {
  82244. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  82245. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  82246. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  82247. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  82248. } else if ( order === 'YZX' ) {
  82249. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  82250. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  82251. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  82252. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  82253. } else if ( order === 'XZY' ) {
  82254. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  82255. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  82256. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  82257. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  82258. }
  82259. return this;
  82260. };
  82261. Quaternion.prototype.clone = function(){
  82262. return new Quaternion(this.x, this.y, this.z, this.w);
  82263. };
  82264. },{"./Vec3":30}],29:[function(_dereq_,module,exports){
  82265. var Vec3 = _dereq_('./Vec3');
  82266. var Quaternion = _dereq_('./Quaternion');
  82267. module.exports = Transform;
  82268. /**
  82269. * @class Transform
  82270. * @constructor
  82271. */
  82272. function Transform(options) {
  82273. options = options || {};
  82274. /**
  82275. * @property {Vec3} position
  82276. */
  82277. this.position = new Vec3();
  82278. if(options.position){
  82279. this.position.copy(options.position);
  82280. }
  82281. /**
  82282. * @property {Quaternion} quaternion
  82283. */
  82284. this.quaternion = new Quaternion();
  82285. if(options.quaternion){
  82286. this.quaternion.copy(options.quaternion);
  82287. }
  82288. }
  82289. var tmpQuat = new Quaternion();
  82290. /**
  82291. * @static
  82292. * @method pointToLocaFrame
  82293. * @param {Vec3} position
  82294. * @param {Quaternion} quaternion
  82295. * @param {Vec3} worldPoint
  82296. * @param {Vec3} result
  82297. */
  82298. Transform.pointToLocalFrame = function(position, quaternion, worldPoint, result){
  82299. var result = result || new Vec3();
  82300. worldPoint.vsub(position, result);
  82301. quaternion.conjugate(tmpQuat);
  82302. tmpQuat.vmult(result, result);
  82303. return result;
  82304. };
  82305. /**
  82306. * Get a global point in local transform coordinates.
  82307. * @method pointToLocal
  82308. * @param {Vec3} point
  82309. * @param {Vec3} result
  82310. * @return {Vec3} The "result" vector object
  82311. */
  82312. Transform.prototype.pointToLocal = function(worldPoint, result){
  82313. return Transform.pointToLocalFrame(this.position, this.quaternion, worldPoint, result);
  82314. };
  82315. /**
  82316. * @static
  82317. * @method pointToWorldFrame
  82318. * @param {Vec3} position
  82319. * @param {Vec3} quaternion
  82320. * @param {Vec3} localPoint
  82321. * @param {Vec3} result
  82322. */
  82323. Transform.pointToWorldFrame = function(position, quaternion, localPoint, result){
  82324. var result = result || new Vec3();
  82325. quaternion.vmult(localPoint, result);
  82326. result.vadd(position, result);
  82327. return result;
  82328. };
  82329. /**
  82330. * Get a local point in global transform coordinates.
  82331. * @method pointToWorld
  82332. * @param {Vec3} point
  82333. * @param {Vec3} result
  82334. * @return {Vec3} The "result" vector object
  82335. */
  82336. Transform.prototype.pointToWorld = function(localPoint, result){
  82337. return Transform.pointToWorldFrame(this.position, this.quaternion, localPoint, result);
  82338. };
  82339. Transform.prototype.vectorToWorldFrame = function(localVector, result){
  82340. var result = result || new Vec3();
  82341. this.quaternion.vmult(localVector, result);
  82342. return result;
  82343. };
  82344. Transform.vectorToWorldFrame = function(quaternion, localVector, result){
  82345. quaternion.vmult(localVector, result);
  82346. return result;
  82347. };
  82348. Transform.vectorToLocalFrame = function(position, quaternion, worldVector, result){
  82349. var result = result || new Vec3();
  82350. quaternion.w *= -1;
  82351. quaternion.vmult(worldVector, result);
  82352. quaternion.w *= -1;
  82353. return result;
  82354. };
  82355. },{"./Quaternion":28,"./Vec3":30}],30:[function(_dereq_,module,exports){
  82356. module.exports = Vec3;
  82357. var Mat3 = _dereq_('./Mat3');
  82358. /**
  82359. * 3-dimensional vector
  82360. * @class Vec3
  82361. * @constructor
  82362. * @param {Number} x
  82363. * @param {Number} y
  82364. * @param {Number} z
  82365. * @author schteppe
  82366. * @example
  82367. * var v = new Vec3(1, 2, 3);
  82368. * console.log('x=' + v.x); // x=1
  82369. */
  82370. function Vec3(x,y,z){
  82371. /**
  82372. * @property x
  82373. * @type {Number}
  82374. */
  82375. this.x = x||0.0;
  82376. /**
  82377. * @property y
  82378. * @type {Number}
  82379. */
  82380. this.y = y||0.0;
  82381. /**
  82382. * @property z
  82383. * @type {Number}
  82384. */
  82385. this.z = z||0.0;
  82386. }
  82387. /**
  82388. * @static
  82389. * @property {Vec3} ZERO
  82390. */
  82391. Vec3.ZERO = new Vec3(0, 0, 0);
  82392. /**
  82393. * @static
  82394. * @property {Vec3} UNIT_X
  82395. */
  82396. Vec3.UNIT_X = new Vec3(1, 0, 0);
  82397. /**
  82398. * @static
  82399. * @property {Vec3} UNIT_Y
  82400. */
  82401. Vec3.UNIT_Y = new Vec3(0, 1, 0);
  82402. /**
  82403. * @static
  82404. * @property {Vec3} UNIT_Z
  82405. */
  82406. Vec3.UNIT_Z = new Vec3(0, 0, 1);
  82407. /**
  82408. * Vector cross product
  82409. * @method cross
  82410. * @param {Vec3} v
  82411. * @param {Vec3} target Optional. Target to save in.
  82412. * @return {Vec3}
  82413. */
  82414. Vec3.prototype.cross = function(v,target){
  82415. var vx=v.x, vy=v.y, vz=v.z, x=this.x, y=this.y, z=this.z;
  82416. target = target || new Vec3();
  82417. target.x = (y * vz) - (z * vy);
  82418. target.y = (z * vx) - (x * vz);
  82419. target.z = (x * vy) - (y * vx);
  82420. return target;
  82421. };
  82422. /**
  82423. * Set the vectors' 3 elements
  82424. * @method set
  82425. * @param {Number} x
  82426. * @param {Number} y
  82427. * @param {Number} z
  82428. * @return Vec3
  82429. */
  82430. Vec3.prototype.set = function(x,y,z){
  82431. this.x = x;
  82432. this.y = y;
  82433. this.z = z;
  82434. return this;
  82435. };
  82436. /**
  82437. * Set all components of the vector to zero.
  82438. * @method setZero
  82439. */
  82440. Vec3.prototype.setZero = function(){
  82441. this.x = this.y = this.z = 0;
  82442. };
  82443. /**
  82444. * Vector addition
  82445. * @method vadd
  82446. * @param {Vec3} v
  82447. * @param {Vec3} target Optional.
  82448. * @return {Vec3}
  82449. */
  82450. Vec3.prototype.vadd = function(v,target){
  82451. if(target){
  82452. target.x = v.x + this.x;
  82453. target.y = v.y + this.y;
  82454. target.z = v.z + this.z;
  82455. } else {
  82456. return new Vec3(this.x + v.x,
  82457. this.y + v.y,
  82458. this.z + v.z);
  82459. }
  82460. };
  82461. /**
  82462. * Vector subtraction
  82463. * @method vsub
  82464. * @param {Vec3} v
  82465. * @param {Vec3} target Optional. Target to save in.
  82466. * @return {Vec3}
  82467. */
  82468. Vec3.prototype.vsub = function(v,target){
  82469. if(target){
  82470. target.x = this.x - v.x;
  82471. target.y = this.y - v.y;
  82472. target.z = this.z - v.z;
  82473. } else {
  82474. return new Vec3(this.x-v.x,
  82475. this.y-v.y,
  82476. this.z-v.z);
  82477. }
  82478. };
  82479. /**
  82480. * Get the cross product matrix a_cross from a vector, such that a x b = a_cross * b = c
  82481. * @method crossmat
  82482. * @see http://www8.cs.umu.se/kurser/TDBD24/VT06/lectures/Lecture6.pdf
  82483. * @return {Mat3}
  82484. */
  82485. Vec3.prototype.crossmat = function(){
  82486. return new Mat3([ 0, -this.z, this.y,
  82487. this.z, 0, -this.x,
  82488. -this.y, this.x, 0]);
  82489. };
  82490. /**
  82491. * Normalize the vector. Note that this changes the values in the vector.
  82492. * @method normalize
  82493. * @return {Number} Returns the norm of the vector
  82494. */
  82495. Vec3.prototype.normalize = function(){
  82496. var x=this.x, y=this.y, z=this.z;
  82497. var n = Math.sqrt(x*x + y*y + z*z);
  82498. if(n>0.0){
  82499. var invN = 1/n;
  82500. this.x *= invN;
  82501. this.y *= invN;
  82502. this.z *= invN;
  82503. } else {
  82504. // Make something up
  82505. this.x = 0;
  82506. this.y = 0;
  82507. this.z = 0;
  82508. }
  82509. return n;
  82510. };
  82511. /**
  82512. * Get the version of this vector that is of length 1.
  82513. * @method unit
  82514. * @param {Vec3} target Optional target to save in
  82515. * @return {Vec3} Returns the unit vector
  82516. */
  82517. Vec3.prototype.unit = function(target){
  82518. target = target || new Vec3();
  82519. var x=this.x, y=this.y, z=this.z;
  82520. var ninv = Math.sqrt(x*x + y*y + z*z);
  82521. if(ninv>0.0){
  82522. ninv = 1.0/ninv;
  82523. target.x = x * ninv;
  82524. target.y = y * ninv;
  82525. target.z = z * ninv;
  82526. } else {
  82527. target.x = 1;
  82528. target.y = 0;
  82529. target.z = 0;
  82530. }
  82531. return target;
  82532. };
  82533. /**
  82534. * Get the length of the vector
  82535. * @method norm
  82536. * @return {Number}
  82537. * @deprecated Use .length() instead
  82538. */
  82539. Vec3.prototype.norm = function(){
  82540. var x=this.x, y=this.y, z=this.z;
  82541. return Math.sqrt(x*x + y*y + z*z);
  82542. };
  82543. /**
  82544. * Get the length of the vector
  82545. * @method length
  82546. * @return {Number}
  82547. */
  82548. Vec3.prototype.length = Vec3.prototype.norm;
  82549. /**
  82550. * Get the squared length of the vector
  82551. * @method norm2
  82552. * @return {Number}
  82553. * @deprecated Use .lengthSquared() instead.
  82554. */
  82555. Vec3.prototype.norm2 = function(){
  82556. return this.dot(this);
  82557. };
  82558. /**
  82559. * Get the squared length of the vector.
  82560. * @method lengthSquared
  82561. * @return {Number}
  82562. */
  82563. Vec3.prototype.lengthSquared = Vec3.prototype.norm2;
  82564. /**
  82565. * Get distance from this point to another point
  82566. * @method distanceTo
  82567. * @param {Vec3} p
  82568. * @return {Number}
  82569. */
  82570. Vec3.prototype.distanceTo = function(p){
  82571. var x=this.x, y=this.y, z=this.z;
  82572. var px=p.x, py=p.y, pz=p.z;
  82573. return Math.sqrt((px-x)*(px-x)+
  82574. (py-y)*(py-y)+
  82575. (pz-z)*(pz-z));
  82576. };
  82577. /**
  82578. * Get squared distance from this point to another point
  82579. * @method distanceSquared
  82580. * @param {Vec3} p
  82581. * @return {Number}
  82582. */
  82583. Vec3.prototype.distanceSquared = function(p){
  82584. var x=this.x, y=this.y, z=this.z;
  82585. var px=p.x, py=p.y, pz=p.z;
  82586. return (px-x)*(px-x) + (py-y)*(py-y) + (pz-z)*(pz-z);
  82587. };
  82588. /**
  82589. * Multiply all the components of the vector with a scalar.
  82590. * @deprecated Use .scale instead
  82591. * @method mult
  82592. * @param {Number} scalar
  82593. * @param {Vec3} target The vector to save the result in.
  82594. * @return {Vec3}
  82595. * @deprecated Use .scale() instead
  82596. */
  82597. Vec3.prototype.mult = function(scalar,target){
  82598. target = target || new Vec3();
  82599. var x = this.x,
  82600. y = this.y,
  82601. z = this.z;
  82602. target.x = scalar * x;
  82603. target.y = scalar * y;
  82604. target.z = scalar * z;
  82605. return target;
  82606. };
  82607. /**
  82608. * Multiply the vector with a scalar.
  82609. * @method scale
  82610. * @param {Number} scalar
  82611. * @param {Vec3} target
  82612. * @return {Vec3}
  82613. */
  82614. Vec3.prototype.scale = Vec3.prototype.mult;
  82615. /**
  82616. * Calculate dot product
  82617. * @method dot
  82618. * @param {Vec3} v
  82619. * @return {Number}
  82620. */
  82621. Vec3.prototype.dot = function(v){
  82622. return this.x * v.x + this.y * v.y + this.z * v.z;
  82623. };
  82624. /**
  82625. * @method isZero
  82626. * @return bool
  82627. */
  82628. Vec3.prototype.isZero = function(){
  82629. return this.x===0 && this.y===0 && this.z===0;
  82630. };
  82631. /**
  82632. * Make the vector point in the opposite direction.
  82633. * @method negate
  82634. * @param {Vec3} target Optional target to save in
  82635. * @return {Vec3}
  82636. */
  82637. Vec3.prototype.negate = function(target){
  82638. target = target || new Vec3();
  82639. target.x = -this.x;
  82640. target.y = -this.y;
  82641. target.z = -this.z;
  82642. return target;
  82643. };
  82644. /**
  82645. * Compute two artificial tangents to the vector
  82646. * @method tangents
  82647. * @param {Vec3} t1 Vector object to save the first tangent in
  82648. * @param {Vec3} t2 Vector object to save the second tangent in
  82649. */
  82650. var Vec3_tangents_n = new Vec3();
  82651. var Vec3_tangents_randVec = new Vec3();
  82652. Vec3.prototype.tangents = function(t1,t2){
  82653. var norm = this.norm();
  82654. if(norm>0.0){
  82655. var n = Vec3_tangents_n;
  82656. var inorm = 1/norm;
  82657. n.set(this.x*inorm,this.y*inorm,this.z*inorm);
  82658. var randVec = Vec3_tangents_randVec;
  82659. if(Math.abs(n.x) < 0.9){
  82660. randVec.set(1,0,0);
  82661. n.cross(randVec,t1);
  82662. } else {
  82663. randVec.set(0,1,0);
  82664. n.cross(randVec,t1);
  82665. }
  82666. n.cross(t1,t2);
  82667. } else {
  82668. // The normal length is zero, make something up
  82669. t1.set(1, 0, 0);
  82670. t2.set(0, 1, 0);
  82671. }
  82672. };
  82673. /**
  82674. * Converts to a more readable format
  82675. * @method toString
  82676. * @return string
  82677. */
  82678. Vec3.prototype.toString = function(){
  82679. return this.x+","+this.y+","+this.z;
  82680. };
  82681. /**
  82682. * Converts to an array
  82683. * @method toArray
  82684. * @return Array
  82685. */
  82686. Vec3.prototype.toArray = function(){
  82687. return [this.x, this.y, this.z];
  82688. };
  82689. /**
  82690. * Copies value of source to this vector.
  82691. * @method copy
  82692. * @param {Vec3} source
  82693. * @return {Vec3} this
  82694. */
  82695. Vec3.prototype.copy = function(source){
  82696. this.x = source.x;
  82697. this.y = source.y;
  82698. this.z = source.z;
  82699. return this;
  82700. };
  82701. /**
  82702. * Do a linear interpolation between two vectors
  82703. * @method lerp
  82704. * @param {Vec3} v
  82705. * @param {Number} t A number between 0 and 1. 0 will make this function return u, and 1 will make it return v. Numbers in between will generate a vector in between them.
  82706. * @param {Vec3} target
  82707. */
  82708. Vec3.prototype.lerp = function(v,t,target){
  82709. var x=this.x, y=this.y, z=this.z;
  82710. target.x = x + (v.x-x)*t;
  82711. target.y = y + (v.y-y)*t;
  82712. target.z = z + (v.z-z)*t;
  82713. };
  82714. /**
  82715. * Check if a vector equals is almost equal to another one.
  82716. * @method almostEquals
  82717. * @param {Vec3} v
  82718. * @param {Number} precision
  82719. * @return bool
  82720. */
  82721. Vec3.prototype.almostEquals = function(v,precision){
  82722. if(precision===undefined){
  82723. precision = 1e-6;
  82724. }
  82725. if( Math.abs(this.x-v.x)>precision ||
  82726. Math.abs(this.y-v.y)>precision ||
  82727. Math.abs(this.z-v.z)>precision){
  82728. return false;
  82729. }
  82730. return true;
  82731. };
  82732. /**
  82733. * Check if a vector is almost zero
  82734. * @method almostZero
  82735. * @param {Number} precision
  82736. */
  82737. Vec3.prototype.almostZero = function(precision){
  82738. if(precision===undefined){
  82739. precision = 1e-6;
  82740. }
  82741. if( Math.abs(this.x)>precision ||
  82742. Math.abs(this.y)>precision ||
  82743. Math.abs(this.z)>precision){
  82744. return false;
  82745. }
  82746. return true;
  82747. };
  82748. var antip_neg = new Vec3();
  82749. /**
  82750. * Check if the vector is anti-parallel to another vector.
  82751. * @method isAntiparallelTo
  82752. * @param {Vec3} v
  82753. * @param {Number} precision Set to zero for exact comparisons
  82754. * @return {Boolean}
  82755. */
  82756. Vec3.prototype.isAntiparallelTo = function(v,precision){
  82757. this.negate(antip_neg);
  82758. return antip_neg.almostEquals(v,precision);
  82759. };
  82760. /**
  82761. * Clone the vector
  82762. * @method clone
  82763. * @return {Vec3}
  82764. */
  82765. Vec3.prototype.clone = function(){
  82766. return new Vec3(this.x, this.y, this.z);
  82767. };
  82768. },{"./Mat3":27}],31:[function(_dereq_,module,exports){
  82769. module.exports = Body;
  82770. var EventTarget = _dereq_('../utils/EventTarget');
  82771. var Shape = _dereq_('../shapes/Shape');
  82772. var Vec3 = _dereq_('../math/Vec3');
  82773. var Mat3 = _dereq_('../math/Mat3');
  82774. var Quaternion = _dereq_('../math/Quaternion');
  82775. var Material = _dereq_('../material/Material');
  82776. var AABB = _dereq_('../collision/AABB');
  82777. var Box = _dereq_('../shapes/Box');
  82778. /**
  82779. * Base class for all body types.
  82780. * @class Body
  82781. * @constructor
  82782. * @extends EventTarget
  82783. * @param {object} [options]
  82784. * @param {Vec3} [options.position]
  82785. * @param {Vec3} [options.velocity]
  82786. * @param {Vec3} [options.angularVelocity]
  82787. * @param {Quaternion} [options.quaternion]
  82788. * @param {number} [options.mass]
  82789. * @param {Material} [options.material]
  82790. * @param {number} [options.type]
  82791. * @param {number} [options.linearDamping=0.01]
  82792. * @param {number} [options.angularDamping=0.01]
  82793. * @param {boolean} [options.allowSleep=true]
  82794. * @param {number} [options.sleepSpeedLimit=0.1]
  82795. * @param {number} [options.sleepTimeLimit=1]
  82796. * @param {number} [options.collisionFilterGroup=1]
  82797. * @param {number} [options.collisionFilterMask=1]
  82798. * @param {boolean} [options.fixedRotation=false]
  82799. * @param {Body} [options.shape]
  82800. * @example
  82801. * var body = new Body({
  82802. * mass: 1
  82803. * });
  82804. * var shape = new Sphere(1);
  82805. * body.addShape(shape);
  82806. * world.add(body);
  82807. */
  82808. function Body(options){
  82809. options = options || {};
  82810. EventTarget.apply(this);
  82811. this.id = Body.idCounter++;
  82812. /**
  82813. * Reference to the world the body is living in
  82814. * @property world
  82815. * @type {World}
  82816. */
  82817. this.world = null;
  82818. /**
  82819. * Callback function that is used BEFORE stepping the system. Use it to apply forces, for example. Inside the function, "this" will refer to this Body object.
  82820. * @property preStep
  82821. * @type {Function}
  82822. * @deprecated Use World events instead
  82823. */
  82824. this.preStep = null;
  82825. /**
  82826. * Callback function that is used AFTER stepping the system. Inside the function, "this" will refer to this Body object.
  82827. * @property postStep
  82828. * @type {Function}
  82829. * @deprecated Use World events instead
  82830. */
  82831. this.postStep = null;
  82832. this.vlambda = new Vec3();
  82833. /**
  82834. * @property {Number} collisionFilterGroup
  82835. */
  82836. this.collisionFilterGroup = typeof(options.collisionFilterGroup) === 'number' ? options.collisionFilterGroup : 1;
  82837. /**
  82838. * @property {Number} collisionFilterMask
  82839. */
  82840. this.collisionFilterMask = typeof(options.collisionFilterMask) === 'number' ? options.collisionFilterMask : 1;
  82841. /**
  82842. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
  82843. * @property {Number} collisionResponse
  82844. */
  82845. this.collisionResponse = true;
  82846. /**
  82847. * @property position
  82848. * @type {Vec3}
  82849. */
  82850. this.position = new Vec3();
  82851. if(options.position){
  82852. this.position.copy(options.position);
  82853. }
  82854. /**
  82855. * @property {Vec3} previousPosition
  82856. */
  82857. this.previousPosition = new Vec3();
  82858. /**
  82859. * Initial position of the body
  82860. * @property initPosition
  82861. * @type {Vec3}
  82862. */
  82863. this.initPosition = new Vec3();
  82864. /**
  82865. * @property velocity
  82866. * @type {Vec3}
  82867. */
  82868. this.velocity = new Vec3();
  82869. if(options.velocity){
  82870. this.velocity.copy(options.velocity);
  82871. }
  82872. /**
  82873. * @property initVelocity
  82874. * @type {Vec3}
  82875. */
  82876. this.initVelocity = new Vec3();
  82877. /**
  82878. * Linear force on the body
  82879. * @property force
  82880. * @type {Vec3}
  82881. */
  82882. this.force = new Vec3();
  82883. var mass = typeof(options.mass) === 'number' ? options.mass : 0;
  82884. /**
  82885. * @property mass
  82886. * @type {Number}
  82887. * @default 0
  82888. */
  82889. this.mass = mass;
  82890. /**
  82891. * @property invMass
  82892. * @type {Number}
  82893. */
  82894. this.invMass = mass > 0 ? 1.0 / mass : 0;
  82895. /**
  82896. * @property material
  82897. * @type {Material}
  82898. */
  82899. this.material = options.material || null;
  82900. /**
  82901. * @property linearDamping
  82902. * @type {Number}
  82903. */
  82904. this.linearDamping = typeof(options.linearDamping) === 'number' ? options.linearDamping : 0.01;
  82905. /**
  82906. * One of: Body.DYNAMIC, Body.STATIC and Body.KINEMATIC.
  82907. * @property type
  82908. * @type {Number}
  82909. */
  82910. this.type = (mass <= 0.0 ? Body.STATIC : Body.DYNAMIC);
  82911. if(typeof(options.type) === typeof(Body.STATIC)){
  82912. this.type = options.type;
  82913. }
  82914. /**
  82915. * If true, the body will automatically fall to sleep.
  82916. * @property allowSleep
  82917. * @type {Boolean}
  82918. * @default true
  82919. */
  82920. this.allowSleep = typeof(options.allowSleep) !== 'undefined' ? options.allowSleep : true;
  82921. /**
  82922. * Current sleep state.
  82923. * @property sleepState
  82924. * @type {Number}
  82925. */
  82926. this.sleepState = 0;
  82927. /**
  82928. * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
  82929. * @property sleepSpeedLimit
  82930. * @type {Number}
  82931. * @default 0.1
  82932. */
  82933. this.sleepSpeedLimit = typeof(options.sleepSpeedLimit) !== 'undefined' ? options.sleepSpeedLimit : 0.1;
  82934. /**
  82935. * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
  82936. * @property sleepTimeLimit
  82937. * @type {Number}
  82938. * @default 1
  82939. */
  82940. this.sleepTimeLimit = typeof(options.sleepTimeLimit) !== 'undefined' ? options.sleepTimeLimit : 1;
  82941. this.timeLastSleepy = 0;
  82942. this._wakeUpAfterNarrowphase = false;
  82943. /**
  82944. * Rotational force on the body, around center of mass
  82945. * @property {Vec3} torque
  82946. */
  82947. this.torque = new Vec3();
  82948. /**
  82949. * Orientation of the body
  82950. * @property quaternion
  82951. * @type {Quaternion}
  82952. */
  82953. this.quaternion = new Quaternion();
  82954. if(options.quaternion){
  82955. this.quaternion.copy(options.quaternion);
  82956. }
  82957. /**
  82958. * @property initQuaternion
  82959. * @type {Quaternion}
  82960. */
  82961. this.initQuaternion = new Quaternion();
  82962. /**
  82963. * @property angularVelocity
  82964. * @type {Vec3}
  82965. */
  82966. this.angularVelocity = new Vec3();
  82967. if(options.angularVelocity){
  82968. this.angularVelocity.copy(options.angularVelocity);
  82969. }
  82970. /**
  82971. * @property initAngularVelocity
  82972. * @type {Vec3}
  82973. */
  82974. this.initAngularVelocity = new Vec3();
  82975. this.interpolatedPosition = new Vec3();
  82976. this.interpolatedQuaternion = new Quaternion();
  82977. /**
  82978. * @property shapes
  82979. * @type {array}
  82980. */
  82981. this.shapes = [];
  82982. /**
  82983. * @property shapeOffsets
  82984. * @type {array}
  82985. */
  82986. this.shapeOffsets = [];
  82987. /**
  82988. * @property shapeOrientations
  82989. * @type {array}
  82990. */
  82991. this.shapeOrientations = [];
  82992. /**
  82993. * @property inertia
  82994. * @type {Vec3}
  82995. */
  82996. this.inertia = new Vec3();
  82997. /**
  82998. * @property {Vec3} invInertia
  82999. */
  83000. this.invInertia = new Vec3();
  83001. /**
  83002. * @property {Mat3} invInertiaWorld
  83003. */
  83004. this.invInertiaWorld = new Mat3();
  83005. this.invMassSolve = 0;
  83006. /**
  83007. * @property {Vec3} invInertiaSolve
  83008. */
  83009. this.invInertiaSolve = new Vec3();
  83010. /**
  83011. * @property {Mat3} invInertiaWorldSolve
  83012. */
  83013. this.invInertiaWorldSolve = new Mat3();
  83014. /**
  83015. * Set to true if you don't want the body to rotate. Make sure to run .updateMassProperties() after changing this.
  83016. * @property {Boolean} fixedRotation
  83017. * @default false
  83018. */
  83019. this.fixedRotation = typeof(options.fixedRotation) !== "undefined" ? options.fixedRotation : false;
  83020. /**
  83021. * @property {Number} angularDamping
  83022. */
  83023. this.angularDamping = typeof(options.angularDamping) !== 'undefined' ? options.angularDamping : 0.01;
  83024. /**
  83025. * @property aabb
  83026. * @type {AABB}
  83027. */
  83028. this.aabb = new AABB();
  83029. /**
  83030. * Indicates if the AABB needs to be updated before use.
  83031. * @property aabbNeedsUpdate
  83032. * @type {Boolean}
  83033. */
  83034. this.aabbNeedsUpdate = true;
  83035. this.wlambda = new Vec3();
  83036. if(options.shape){
  83037. this.addShape(options.shape);
  83038. }
  83039. this.updateMassProperties();
  83040. }
  83041. Body.prototype = new EventTarget();
  83042. Body.prototype.constructor = Body;
  83043. /**
  83044. * A dynamic body is fully simulated. Can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass.
  83045. * @static
  83046. * @property DYNAMIC
  83047. * @type {Number}
  83048. */
  83049. Body.DYNAMIC = 1;
  83050. /**
  83051. * A static body does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting the position of the body. The velocity of a static body is always zero. Static bodies do not collide with other static or kinematic bodies.
  83052. * @static
  83053. * @property STATIC
  83054. * @type {Number}
  83055. */
  83056. Body.STATIC = 2;
  83057. /**
  83058. * A kinematic body moves under simulation according to its velocity. They do not respond to forces. They can be moved manually, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass. Kinematic bodies do not collide with other static or kinematic bodies.
  83059. * @static
  83060. * @property KINEMATIC
  83061. * @type {Number}
  83062. */
  83063. Body.KINEMATIC = 4;
  83064. /**
  83065. * @static
  83066. * @property AWAKE
  83067. * @type {number}
  83068. */
  83069. Body.AWAKE = 0;
  83070. /**
  83071. * @static
  83072. * @property SLEEPY
  83073. * @type {number}
  83074. */
  83075. Body.SLEEPY = 1;
  83076. /**
  83077. * @static
  83078. * @property SLEEPING
  83079. * @type {number}
  83080. */
  83081. Body.SLEEPING = 2;
  83082. Body.idCounter = 0;
  83083. /**
  83084. * Wake the body up.
  83085. * @method wakeUp
  83086. */
  83087. Body.prototype.wakeUp = function(){
  83088. var s = this.sleepState;
  83089. this.sleepState = 0;
  83090. if(s === Body.SLEEPING){
  83091. this.dispatchEvent({type:"wakeup"});
  83092. }
  83093. };
  83094. /**
  83095. * Force body sleep
  83096. * @method sleep
  83097. */
  83098. Body.prototype.sleep = function(){
  83099. this.sleepState = Body.SLEEPING;
  83100. this.velocity.set(0,0,0);
  83101. this.angularVelocity.set(0,0,0);
  83102. };
  83103. Body.sleepyEvent = {
  83104. type: "sleepy"
  83105. };
  83106. Body.sleepEvent = {
  83107. type: "sleep"
  83108. };
  83109. /**
  83110. * Called every timestep to update internal sleep timer and change sleep state if needed.
  83111. * @method sleepTick
  83112. * @param {Number} time The world time in seconds
  83113. */
  83114. Body.prototype.sleepTick = function(time){
  83115. if(this.allowSleep){
  83116. var sleepState = this.sleepState;
  83117. var speedSquared = this.velocity.norm2() + this.angularVelocity.norm2();
  83118. var speedLimitSquared = Math.pow(this.sleepSpeedLimit,2);
  83119. if(sleepState===Body.AWAKE && speedSquared < speedLimitSquared){
  83120. this.sleepState = Body.SLEEPY; // Sleepy
  83121. this.timeLastSleepy = time;
  83122. this.dispatchEvent(Body.sleepyEvent);
  83123. } else if(sleepState===Body.SLEEPY && speedSquared > speedLimitSquared){
  83124. this.wakeUp(); // Wake up
  83125. } else if(sleepState===Body.SLEEPY && (time - this.timeLastSleepy ) > this.sleepTimeLimit){
  83126. this.sleep(); // Sleeping
  83127. this.dispatchEvent(Body.sleepEvent);
  83128. }
  83129. }
  83130. };
  83131. /**
  83132. * If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate "solve mass".
  83133. * @method updateSolveMassProperties
  83134. */
  83135. Body.prototype.updateSolveMassProperties = function(){
  83136. if(this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC){
  83137. this.invMassSolve = 0;
  83138. this.invInertiaSolve.setZero();
  83139. this.invInertiaWorldSolve.setZero();
  83140. } else {
  83141. this.invMassSolve = this.invMass;
  83142. this.invInertiaSolve.copy(this.invInertia);
  83143. this.invInertiaWorldSolve.copy(this.invInertiaWorld);
  83144. }
  83145. };
  83146. /**
  83147. * Convert a world point to local body frame.
  83148. * @method pointToLocalFrame
  83149. * @param {Vec3} worldPoint
  83150. * @param {Vec3} result
  83151. * @return {Vec3}
  83152. */
  83153. Body.prototype.pointToLocalFrame = function(worldPoint,result){
  83154. var result = result || new Vec3();
  83155. worldPoint.vsub(this.position,result);
  83156. this.quaternion.conjugate().vmult(result,result);
  83157. return result;
  83158. };
  83159. /**
  83160. * Convert a world vector to local body frame.
  83161. * @method vectorToLocalFrame
  83162. * @param {Vec3} worldPoint
  83163. * @param {Vec3} result
  83164. * @return {Vec3}
  83165. */
  83166. Body.prototype.vectorToLocalFrame = function(worldVector, result){
  83167. var result = result || new Vec3();
  83168. this.quaternion.conjugate().vmult(worldVector,result);
  83169. return result;
  83170. };
  83171. /**
  83172. * Convert a local body point to world frame.
  83173. * @method pointToWorldFrame
  83174. * @param {Vec3} localPoint
  83175. * @param {Vec3} result
  83176. * @return {Vec3}
  83177. */
  83178. Body.prototype.pointToWorldFrame = function(localPoint,result){
  83179. var result = result || new Vec3();
  83180. this.quaternion.vmult(localPoint,result);
  83181. result.vadd(this.position,result);
  83182. return result;
  83183. };
  83184. /**
  83185. * Convert a local body point to world frame.
  83186. * @method vectorToWorldFrame
  83187. * @param {Vec3} localVector
  83188. * @param {Vec3} result
  83189. * @return {Vec3}
  83190. */
  83191. Body.prototype.vectorToWorldFrame = function(localVector, result){
  83192. var result = result || new Vec3();
  83193. this.quaternion.vmult(localVector, result);
  83194. return result;
  83195. };
  83196. var tmpVec = new Vec3();
  83197. var tmpQuat = new Quaternion();
  83198. /**
  83199. * Add a shape to the body with a local offset and orientation.
  83200. * @method addShape
  83201. * @param {Shape} shape
  83202. * @param {Vec3} offset
  83203. * @param {Quaternion} quaternion
  83204. * @return {Body} The body object, for chainability.
  83205. */
  83206. Body.prototype.addShape = function(shape, _offset, _orientation){
  83207. var offset = new Vec3();
  83208. var orientation = new Quaternion();
  83209. if(_offset){
  83210. offset.copy(_offset);
  83211. }
  83212. if(_orientation){
  83213. orientation.copy(_orientation);
  83214. }
  83215. this.shapes.push(shape);
  83216. this.shapeOffsets.push(offset);
  83217. this.shapeOrientations.push(orientation);
  83218. this.updateMassProperties();
  83219. this.updateBoundingRadius();
  83220. this.aabbNeedsUpdate = true;
  83221. return this;
  83222. };
  83223. /**
  83224. * Update the bounding radius of the body. Should be done if any of the shapes are changed.
  83225. * @method updateBoundingRadius
  83226. */
  83227. Body.prototype.updateBoundingRadius = function(){
  83228. var shapes = this.shapes,
  83229. shapeOffsets = this.shapeOffsets,
  83230. N = shapes.length,
  83231. radius = 0;
  83232. for(var i=0; i!==N; i++){
  83233. var shape = shapes[i];
  83234. shape.updateBoundingSphereRadius();
  83235. var offset = shapeOffsets[i].norm(),
  83236. r = shape.boundingSphereRadius;
  83237. if(offset + r > radius){
  83238. radius = offset + r;
  83239. }
  83240. }
  83241. this.boundingRadius = radius;
  83242. };
  83243. var computeAABB_shapeAABB = new AABB();
  83244. /**
  83245. * Updates the .aabb
  83246. * @method computeAABB
  83247. * @todo rename to updateAABB()
  83248. */
  83249. Body.prototype.computeAABB = function(){
  83250. var shapes = this.shapes,
  83251. shapeOffsets = this.shapeOffsets,
  83252. shapeOrientations = this.shapeOrientations,
  83253. N = shapes.length,
  83254. offset = tmpVec,
  83255. orientation = tmpQuat,
  83256. bodyQuat = this.quaternion,
  83257. aabb = this.aabb,
  83258. shapeAABB = computeAABB_shapeAABB;
  83259. for(var i=0; i!==N; i++){
  83260. var shape = shapes[i];
  83261. // Get shape world quaternion
  83262. shapeOrientations[i].mult(bodyQuat, orientation);
  83263. // Get shape world position
  83264. orientation.vmult(shapeOffsets[i], offset);
  83265. offset.vadd(this.position, offset);
  83266. // vec2.rotate(offset, shapeOffsets[i], bodyAngle);
  83267. // vec2.add(offset, offset, this.position);
  83268. // Get shape AABB
  83269. shape.calculateWorldAABB(offset, orientation, shapeAABB.lowerBound, shapeAABB.upperBound);
  83270. if(i === 0){
  83271. aabb.copy(shapeAABB);
  83272. } else {
  83273. aabb.extend(shapeAABB);
  83274. }
  83275. }
  83276. this.aabbNeedsUpdate = false;
  83277. };
  83278. var uiw_m1 = new Mat3(),
  83279. uiw_m2 = new Mat3(),
  83280. uiw_m3 = new Mat3();
  83281. /**
  83282. * Update .inertiaWorld and .invInertiaWorld
  83283. * @method updateInertiaWorld
  83284. */
  83285. Body.prototype.updateInertiaWorld = function(force){
  83286. var I = this.invInertia;
  83287. if (I.x === I.y && I.y === I.z && !force) {
  83288. // If inertia M = s*I, where I is identity and s a scalar, then
  83289. // R*M*R' = R*(s*I)*R' = s*R*I*R' = s*R*R' = s*I = M
  83290. // where R is the rotation matrix.
  83291. // In other words, we don't have to transform the inertia if all
  83292. // inertia diagonal entries are equal.
  83293. } else {
  83294. var m1 = uiw_m1,
  83295. m2 = uiw_m2,
  83296. m3 = uiw_m3;
  83297. m1.setRotationFromQuaternion(this.quaternion);
  83298. m1.transpose(m2);
  83299. m1.scale(I,m1);
  83300. m1.mmult(m2,this.invInertiaWorld);
  83301. //m3.getTrace(this.invInertiaWorld);
  83302. }
  83303. /*
  83304. this.quaternion.vmult(this.inertia,this.inertiaWorld);
  83305. this.quaternion.vmult(this.invInertia,this.invInertiaWorld);
  83306. */
  83307. };
  83308. /**
  83309. * Apply force to a world point. This could for example be a point on the Body surface. Applying force this way will add to Body.force and Body.torque.
  83310. * @method applyForce
  83311. * @param {Vec3} force The amount of force to add.
  83312. * @param {Vec3} worldPoint A world point to apply the force on.
  83313. */
  83314. var Body_applyForce_r = new Vec3();
  83315. var Body_applyForce_rotForce = new Vec3();
  83316. Body.prototype.applyForce = function(force,worldPoint){
  83317. if(this.type !== Body.DYNAMIC){
  83318. return;
  83319. }
  83320. // Compute point position relative to the body center
  83321. var r = Body_applyForce_r;
  83322. worldPoint.vsub(this.position,r);
  83323. // Compute produced rotational force
  83324. var rotForce = Body_applyForce_rotForce;
  83325. r.cross(force,rotForce);
  83326. // Add linear force
  83327. this.force.vadd(force,this.force);
  83328. // Add rotational force
  83329. this.torque.vadd(rotForce,this.torque);
  83330. };
  83331. /**
  83332. * Apply force to a local point in the body.
  83333. * @method applyLocalForce
  83334. * @param {Vec3} force The force vector to apply, defined locally in the body frame.
  83335. * @param {Vec3} localPoint A local point in the body to apply the force on.
  83336. */
  83337. var Body_applyLocalForce_worldForce = new Vec3();
  83338. var Body_applyLocalForce_worldPoint = new Vec3();
  83339. Body.prototype.applyLocalForce = function(localForce, localPoint){
  83340. if(this.type !== Body.DYNAMIC){
  83341. return;
  83342. }
  83343. var worldForce = Body_applyLocalForce_worldForce;
  83344. var worldPoint = Body_applyLocalForce_worldPoint;
  83345. // Transform the force vector to world space
  83346. this.vectorToWorldFrame(localForce, worldForce);
  83347. this.pointToWorldFrame(localPoint, worldPoint);
  83348. this.applyForce(worldForce, worldPoint);
  83349. };
  83350. /**
  83351. * Apply impulse to a world point. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
  83352. * @method applyImpulse
  83353. * @param {Vec3} impulse The amount of impulse to add.
  83354. * @param {Vec3} worldPoint A world point to apply the force on.
  83355. */
  83356. var Body_applyImpulse_r = new Vec3();
  83357. var Body_applyImpulse_velo = new Vec3();
  83358. var Body_applyImpulse_rotVelo = new Vec3();
  83359. Body.prototype.applyImpulse = function(impulse, worldPoint){
  83360. if(this.type !== Body.DYNAMIC){
  83361. return;
  83362. }
  83363. // Compute point position relative to the body center
  83364. var r = Body_applyImpulse_r;
  83365. worldPoint.vsub(this.position,r);
  83366. // Compute produced central impulse velocity
  83367. var velo = Body_applyImpulse_velo;
  83368. velo.copy(impulse);
  83369. velo.mult(this.invMass,velo);
  83370. // Add linear impulse
  83371. this.velocity.vadd(velo, this.velocity);
  83372. // Compute produced rotational impulse velocity
  83373. var rotVelo = Body_applyImpulse_rotVelo;
  83374. r.cross(impulse,rotVelo);
  83375. /*
  83376. rotVelo.x *= this.invInertia.x;
  83377. rotVelo.y *= this.invInertia.y;
  83378. rotVelo.z *= this.invInertia.z;
  83379. */
  83380. this.invInertiaWorld.vmult(rotVelo,rotVelo);
  83381. // Add rotational Impulse
  83382. this.angularVelocity.vadd(rotVelo, this.angularVelocity);
  83383. };
  83384. /**
  83385. * Apply locally-defined impulse to a local point in the body.
  83386. * @method applyLocalImpulse
  83387. * @param {Vec3} force The force vector to apply, defined locally in the body frame.
  83388. * @param {Vec3} localPoint A local point in the body to apply the force on.
  83389. */
  83390. var Body_applyLocalImpulse_worldImpulse = new Vec3();
  83391. var Body_applyLocalImpulse_worldPoint = new Vec3();
  83392. Body.prototype.applyLocalImpulse = function(localImpulse, localPoint){
  83393. if(this.type !== Body.DYNAMIC){
  83394. return;
  83395. }
  83396. var worldImpulse = Body_applyLocalImpulse_worldImpulse;
  83397. var worldPoint = Body_applyLocalImpulse_worldPoint;
  83398. // Transform the force vector to world space
  83399. this.vectorToWorldFrame(localImpulse, worldImpulse);
  83400. this.pointToWorldFrame(localPoint, worldPoint);
  83401. this.applyImpulse(worldImpulse, worldPoint);
  83402. };
  83403. var Body_updateMassProperties_halfExtents = new Vec3();
  83404. /**
  83405. * Should be called whenever you change the body shape or mass.
  83406. * @method updateMassProperties
  83407. */
  83408. Body.prototype.updateMassProperties = function(){
  83409. var halfExtents = Body_updateMassProperties_halfExtents;
  83410. this.invMass = this.mass > 0 ? 1.0 / this.mass : 0;
  83411. var I = this.inertia;
  83412. var fixed = this.fixedRotation;
  83413. // Approximate with AABB box
  83414. this.computeAABB();
  83415. halfExtents.set(
  83416. (this.aabb.upperBound.x-this.aabb.lowerBound.x) / 2,
  83417. (this.aabb.upperBound.y-this.aabb.lowerBound.y) / 2,
  83418. (this.aabb.upperBound.z-this.aabb.lowerBound.z) / 2
  83419. );
  83420. Box.calculateInertia(halfExtents, this.mass, I);
  83421. this.invInertia.set(
  83422. I.x > 0 && !fixed ? 1.0 / I.x : 0,
  83423. I.y > 0 && !fixed ? 1.0 / I.y : 0,
  83424. I.z > 0 && !fixed ? 1.0 / I.z : 0
  83425. );
  83426. this.updateInertiaWorld(true);
  83427. };
  83428. /**
  83429. * Get world velocity of a point in the body.
  83430. * @method getVelocityAtWorldPoint
  83431. * @param {Vec3} worldPoint
  83432. * @param {Vec3} result
  83433. * @return {Vec3} The result vector.
  83434. */
  83435. Body.prototype.getVelocityAtWorldPoint = function(worldPoint, result){
  83436. var r = new Vec3();
  83437. worldPoint.vsub(this.position, r);
  83438. this.angularVelocity.cross(r, result);
  83439. this.velocity.vadd(result, result);
  83440. return result;
  83441. };
  83442. },{"../collision/AABB":3,"../material/Material":25,"../math/Mat3":27,"../math/Quaternion":28,"../math/Vec3":30,"../shapes/Box":37,"../shapes/Shape":43,"../utils/EventTarget":49}],32:[function(_dereq_,module,exports){
  83443. var Body = _dereq_('./Body');
  83444. var Vec3 = _dereq_('../math/Vec3');
  83445. var Quaternion = _dereq_('../math/Quaternion');
  83446. var RaycastResult = _dereq_('../collision/RaycastResult');
  83447. var Ray = _dereq_('../collision/Ray');
  83448. var WheelInfo = _dereq_('../objects/WheelInfo');
  83449. module.exports = RaycastVehicle;
  83450. /**
  83451. * Vehicle helper class that casts rays from the wheel positions towards the ground and applies forces.
  83452. * @class RaycastVehicle
  83453. * @constructor
  83454. * @param {object} [options]
  83455. * @param {Body} [options.chassisBody] The car chassis body.
  83456. * @param {integer} [options.indexRightAxis] Axis to use for right. x=0, y=1, z=2
  83457. * @param {integer} [options.indexLeftAxis]
  83458. * @param {integer} [options.indexUpAxis]
  83459. */
  83460. function RaycastVehicle(options){
  83461. /**
  83462. * @property {Body} chassisBody
  83463. */
  83464. this.chassisBody = options.chassisBody;
  83465. /**
  83466. * An array of WheelInfo objects.
  83467. * @property {array} wheelInfos
  83468. */
  83469. this.wheelInfos = [];
  83470. /**
  83471. * Will be set to true if the car is sliding.
  83472. * @property {boolean} sliding
  83473. */
  83474. this.sliding = false;
  83475. /**
  83476. * @property {World} world
  83477. */
  83478. this.world = null;
  83479. /**
  83480. * Index of the right axis, 0=x, 1=y, 2=z
  83481. * @property {integer} indexRightAxis
  83482. * @default 1
  83483. */
  83484. this.indexRightAxis = typeof(options.indexRightAxis) !== 'undefined' ? options.indexRightAxis : 1;
  83485. /**
  83486. * Index of the forward axis, 0=x, 1=y, 2=z
  83487. * @property {integer} indexForwardAxis
  83488. * @default 0
  83489. */
  83490. this.indexForwardAxis = typeof(options.indexForwardAxis) !== 'undefined' ? options.indexForwardAxis : 0;
  83491. /**
  83492. * Index of the up axis, 0=x, 1=y, 2=z
  83493. * @property {integer} indexUpAxis
  83494. * @default 2
  83495. */
  83496. this.indexUpAxis = typeof(options.indexUpAxis) !== 'undefined' ? options.indexUpAxis : 2;
  83497. }
  83498. var tmpVec1 = new Vec3();
  83499. var tmpVec2 = new Vec3();
  83500. var tmpVec3 = new Vec3();
  83501. var tmpVec4 = new Vec3();
  83502. var tmpVec5 = new Vec3();
  83503. var tmpVec6 = new Vec3();
  83504. var tmpRay = new Ray();
  83505. /**
  83506. * Add a wheel. For information about the options, see WheelInfo.
  83507. * @method addWheel
  83508. * @param {object} [options]
  83509. */
  83510. RaycastVehicle.prototype.addWheel = function(options){
  83511. options = options || {};
  83512. var info = new WheelInfo(options);
  83513. var index = this.wheelInfos.length;
  83514. this.wheelInfos.push(info);
  83515. return index;
  83516. };
  83517. /**
  83518. * Set the steering value of a wheel.
  83519. * @method setSteeringValue
  83520. * @param {number} value
  83521. * @param {integer} wheelIndex
  83522. */
  83523. RaycastVehicle.prototype.setSteeringValue = function(value, wheelIndex){
  83524. var wheel = this.wheelInfos[wheelIndex];
  83525. wheel.steering = value;
  83526. };
  83527. var torque = new Vec3();
  83528. /**
  83529. * Set the wheel force to apply on one of the wheels each time step
  83530. * @method applyEngineForce
  83531. * @param {number} value
  83532. * @param {integer} wheelIndex
  83533. */
  83534. RaycastVehicle.prototype.applyEngineForce = function(value, wheelIndex){
  83535. this.wheelInfos[wheelIndex].engineForce = value;
  83536. };
  83537. /**
  83538. * Set the braking force of a wheel
  83539. * @method setBrake
  83540. * @param {number} brake
  83541. * @param {integer} wheelIndex
  83542. */
  83543. RaycastVehicle.prototype.setBrake = function(brake, wheelIndex){
  83544. this.wheelInfos[wheelIndex].brake = brake;
  83545. };
  83546. /**
  83547. * Add the vehicle including its constraints to the world.
  83548. * @method addToWorld
  83549. * @param {World} world
  83550. */
  83551. RaycastVehicle.prototype.addToWorld = function(world){
  83552. var constraints = this.constraints;
  83553. world.add(this.chassisBody);
  83554. var that = this;
  83555. this.preStepCallback = function(){
  83556. that.updateVehicle(world.dt);
  83557. };
  83558. world.addEventListener('preStep', this.preStepCallback);
  83559. this.world = world;
  83560. };
  83561. /**
  83562. * Get one of the wheel axles, world-oriented.
  83563. * @private
  83564. * @method getVehicleAxisWorld
  83565. * @param {integer} axisIndex
  83566. * @param {Vec3} result
  83567. */
  83568. RaycastVehicle.prototype.getVehicleAxisWorld = function(axisIndex, result){
  83569. result.set(
  83570. axisIndex === 0 ? 1 : 0,
  83571. axisIndex === 1 ? 1 : 0,
  83572. axisIndex === 2 ? 1 : 0
  83573. );
  83574. this.chassisBody.vectorToWorldFrame(result, result);
  83575. };
  83576. RaycastVehicle.prototype.updateVehicle = function(timeStep){
  83577. var wheelInfos = this.wheelInfos;
  83578. var numWheels = wheelInfos.length;
  83579. var chassisBody = this.chassisBody;
  83580. for (var i = 0; i < numWheels; i++) {
  83581. this.updateWheelTransform(i);
  83582. }
  83583. this.currentVehicleSpeedKmHour = 3.6 * chassisBody.velocity.norm();
  83584. var forwardWorld = new Vec3();
  83585. this.getVehicleAxisWorld(this.indexForwardAxis, forwardWorld);
  83586. if (forwardWorld.dot(chassisBody.velocity) < 0){
  83587. this.currentVehicleSpeedKmHour *= -1;
  83588. }
  83589. // simulate suspension
  83590. for (var i = 0; i < numWheels; i++) {
  83591. this.castRay(wheelInfos[i]);
  83592. }
  83593. this.updateSuspension(timeStep);
  83594. var impulse = new Vec3();
  83595. var relpos = new Vec3();
  83596. for (var i = 0; i < numWheels; i++) {
  83597. //apply suspension force
  83598. var wheel = wheelInfos[i];
  83599. var suspensionForce = wheel.suspensionForce;
  83600. if (suspensionForce > wheel.maxSuspensionForce) {
  83601. suspensionForce = wheel.maxSuspensionForce;
  83602. }
  83603. wheel.raycastResult.hitNormalWorld.scale(suspensionForce * timeStep, impulse);
  83604. wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, relpos);
  83605. chassisBody.applyImpulse(impulse, wheel.raycastResult.hitPointWorld/*relpos*/);
  83606. }
  83607. this.updateFriction(timeStep);
  83608. var hitNormalWorldScaledWithProj = new Vec3();
  83609. var fwd = new Vec3();
  83610. var vel = new Vec3();
  83611. for (i = 0; i < numWheels; i++) {
  83612. var wheel = wheelInfos[i];
  83613. //var relpos = new Vec3();
  83614. //wheel.chassisConnectionPointWorld.vsub(chassisBody.position, relpos);
  83615. chassisBody.getVelocityAtWorldPoint(wheel.chassisConnectionPointWorld, vel);
  83616. // Hack to get the rotation in the correct direction
  83617. var m = 1;
  83618. switch(this.indexUpAxis){
  83619. case 1:
  83620. m = -1;
  83621. break;
  83622. }
  83623. if (wheel.isInContact) {
  83624. this.getVehicleAxisWorld(this.indexForwardAxis, fwd);
  83625. var proj = fwd.dot(wheel.raycastResult.hitNormalWorld);
  83626. wheel.raycastResult.hitNormalWorld.scale(proj, hitNormalWorldScaledWithProj);
  83627. fwd.vsub(hitNormalWorldScaledWithProj, fwd);
  83628. var proj2 = fwd.dot(vel);
  83629. wheel.deltaRotation = m * proj2 * timeStep / wheel.radius;
  83630. }
  83631. if((wheel.sliding || !wheel.isInContact) && wheel.engineForce !== 0 && wheel.useCustomSlidingRotationalSpeed){
  83632. // Apply custom rotation when accelerating and sliding
  83633. wheel.deltaRotation = (wheel.engineForce > 0 ? 1 : -1) * wheel.customSlidingRotationalSpeed * timeStep;
  83634. }
  83635. // Lock wheels
  83636. if(Math.abs(wheel.brake) > Math.abs(wheel.engineForce)){
  83637. wheel.deltaRotation = 0;
  83638. }
  83639. wheel.rotation += wheel.deltaRotation; // Use the old value
  83640. wheel.deltaRotation *= 0.99; // damping of rotation when not in contact
  83641. }
  83642. };
  83643. RaycastVehicle.prototype.updateSuspension = function(deltaTime) {
  83644. var chassisBody = this.chassisBody;
  83645. var chassisMass = chassisBody.mass;
  83646. var wheelInfos = this.wheelInfos;
  83647. var numWheels = wheelInfos.length;
  83648. for (var w_it = 0; w_it < numWheels; w_it++){
  83649. var wheel = wheelInfos[w_it];
  83650. if (wheel.isInContact){
  83651. var force;
  83652. // Spring
  83653. var susp_length = wheel.suspensionRestLength;
  83654. var current_length = wheel.suspensionLength;
  83655. var length_diff = (susp_length - current_length);
  83656. force = wheel.suspensionStiffness * length_diff * wheel.clippedInvContactDotSuspension;
  83657. // Damper
  83658. var projected_rel_vel = wheel.suspensionRelativeVelocity;
  83659. var susp_damping;
  83660. if (projected_rel_vel < 0) {
  83661. susp_damping = wheel.dampingCompression;
  83662. } else {
  83663. susp_damping = wheel.dampingRelaxation;
  83664. }
  83665. force -= susp_damping * projected_rel_vel;
  83666. wheel.suspensionForce = force * chassisMass;
  83667. if (wheel.suspensionForce < 0) {
  83668. wheel.suspensionForce = 0;
  83669. }
  83670. } else {
  83671. wheel.suspensionForce = 0;
  83672. }
  83673. }
  83674. };
  83675. /**
  83676. * Remove the vehicle including its constraints from the world.
  83677. * @method removeFromWorld
  83678. * @param {World} world
  83679. */
  83680. RaycastVehicle.prototype.removeFromWorld = function(world){
  83681. var constraints = this.constraints;
  83682. world.remove(this.chassisBody);
  83683. world.removeEventListener('preStep', this.preStepCallback);
  83684. this.world = null;
  83685. };
  83686. var castRay_rayvector = new Vec3();
  83687. var castRay_target = new Vec3();
  83688. RaycastVehicle.prototype.castRay = function(wheel) {
  83689. var rayvector = castRay_rayvector;
  83690. var target = castRay_target;
  83691. this.updateWheelTransformWorld(wheel);
  83692. var chassisBody = this.chassisBody;
  83693. var depth = -1;
  83694. var raylen = wheel.suspensionRestLength + wheel.radius;
  83695. wheel.directionWorld.scale(raylen, rayvector);
  83696. var source = wheel.chassisConnectionPointWorld;
  83697. source.vadd(rayvector, target);
  83698. var raycastResult = wheel.raycastResult;
  83699. var param = 0;
  83700. raycastResult.reset();
  83701. // Turn off ray collision with the chassis temporarily
  83702. var oldState = chassisBody.collisionResponse;
  83703. chassisBody.collisionResponse = false;
  83704. // Cast ray against world
  83705. this.world.rayTest(source, target, raycastResult);
  83706. chassisBody.collisionResponse = oldState;
  83707. var object = raycastResult.body;
  83708. wheel.raycastResult.groundObject = 0;
  83709. if (object) {
  83710. depth = raycastResult.distance;
  83711. wheel.raycastResult.hitNormalWorld = raycastResult.hitNormalWorld;
  83712. wheel.isInContact = true;
  83713. var hitDistance = raycastResult.distance;
  83714. wheel.suspensionLength = hitDistance - wheel.radius;
  83715. // clamp on max suspension travel
  83716. var minSuspensionLength = wheel.suspensionRestLength - wheel.maxSuspensionTravel;
  83717. var maxSuspensionLength = wheel.suspensionRestLength + wheel.maxSuspensionTravel;
  83718. if (wheel.suspensionLength < minSuspensionLength) {
  83719. wheel.suspensionLength = minSuspensionLength;
  83720. }
  83721. if (wheel.suspensionLength > maxSuspensionLength) {
  83722. wheel.suspensionLength = maxSuspensionLength;
  83723. wheel.raycastResult.reset();
  83724. }
  83725. var denominator = wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld);
  83726. var chassis_velocity_at_contactPoint = new Vec3();
  83727. chassisBody.getVelocityAtWorldPoint(wheel.raycastResult.hitPointWorld, chassis_velocity_at_contactPoint);
  83728. var projVel = wheel.raycastResult.hitNormalWorld.dot( chassis_velocity_at_contactPoint );
  83729. if (denominator >= -0.1) {
  83730. wheel.suspensionRelativeVelocity = 0;
  83731. wheel.clippedInvContactDotSuspension = 1 / 0.1;
  83732. } else {
  83733. var inv = -1 / denominator;
  83734. wheel.suspensionRelativeVelocity = projVel * inv;
  83735. wheel.clippedInvContactDotSuspension = inv;
  83736. }
  83737. } else {
  83738. //put wheel info as in rest position
  83739. wheel.suspensionLength = wheel.suspensionRestLength + 0 * wheel.maxSuspensionTravel;
  83740. wheel.suspensionRelativeVelocity = 0.0;
  83741. wheel.directionWorld.scale(-1, wheel.raycastResult.hitNormalWorld);
  83742. wheel.clippedInvContactDotSuspension = 1.0;
  83743. }
  83744. return depth;
  83745. };
  83746. RaycastVehicle.prototype.updateWheelTransformWorld = function(wheel){
  83747. wheel.isInContact = false;
  83748. var chassisBody = this.chassisBody;
  83749. chassisBody.pointToWorldFrame(wheel.chassisConnectionPointLocal, wheel.chassisConnectionPointWorld);
  83750. chassisBody.vectorToWorldFrame(wheel.directionLocal, wheel.directionWorld);
  83751. chassisBody.vectorToWorldFrame(wheel.axleLocal, wheel.axleWorld);
  83752. };
  83753. /**
  83754. * Update one of the wheel transform.
  83755. * Note when rendering wheels: during each step, wheel transforms are updated BEFORE the chassis; ie. their position becomes invalid after the step. Thus when you render wheels, you must update wheel transforms before rendering them. See raycastVehicle demo for an example.
  83756. * @method updateWheelTransform
  83757. * @param {integer} wheelIndex The wheel index to update.
  83758. */
  83759. RaycastVehicle.prototype.updateWheelTransform = function(wheelIndex){
  83760. var up = tmpVec4;
  83761. var right = tmpVec5;
  83762. var fwd = tmpVec6;
  83763. var wheel = this.wheelInfos[wheelIndex];
  83764. this.updateWheelTransformWorld(wheel);
  83765. wheel.directionLocal.scale(-1, up);
  83766. right.copy(wheel.axleLocal);
  83767. up.cross(right, fwd);
  83768. fwd.normalize();
  83769. right.normalize();
  83770. // Rotate around steering over the wheelAxle
  83771. var steering = wheel.steering;
  83772. var steeringOrn = new Quaternion();
  83773. steeringOrn.setFromAxisAngle(up, steering);
  83774. var rotatingOrn = new Quaternion();
  83775. rotatingOrn.setFromAxisAngle(right, wheel.rotation);
  83776. // World rotation of the wheel
  83777. var q = wheel.worldTransform.quaternion;
  83778. this.chassisBody.quaternion.mult(steeringOrn, q);
  83779. q.mult(rotatingOrn, q);
  83780. q.normalize();
  83781. // world position of the wheel
  83782. var p = wheel.worldTransform.position;
  83783. p.copy(wheel.directionWorld);
  83784. p.scale(wheel.suspensionLength, p);
  83785. p.vadd(wheel.chassisConnectionPointWorld, p);
  83786. };
  83787. var directions = [
  83788. new Vec3(1, 0, 0),
  83789. new Vec3(0, 1, 0),
  83790. new Vec3(0, 0, 1)
  83791. ];
  83792. /**
  83793. * Get the world transform of one of the wheels
  83794. * @method getWheelTransformWorld
  83795. * @param {integer} wheelIndex
  83796. * @return {Transform}
  83797. */
  83798. RaycastVehicle.prototype.getWheelTransformWorld = function(wheelIndex) {
  83799. return this.wheelInfos[wheelIndex].worldTransform;
  83800. };
  83801. var updateFriction_surfNormalWS_scaled_proj = new Vec3();
  83802. var updateFriction_axle = [];
  83803. var updateFriction_forwardWS = [];
  83804. var sideFrictionStiffness2 = 1;
  83805. RaycastVehicle.prototype.updateFriction = function(timeStep) {
  83806. var surfNormalWS_scaled_proj = updateFriction_surfNormalWS_scaled_proj;
  83807. //calculate the impulse, so that the wheels don't move sidewards
  83808. var wheelInfos = this.wheelInfos;
  83809. var numWheels = wheelInfos.length;
  83810. var chassisBody = this.chassisBody;
  83811. var forwardWS = updateFriction_forwardWS;
  83812. var axle = updateFriction_axle;
  83813. var numWheelsOnGround = 0;
  83814. for (var i = 0; i < numWheels; i++) {
  83815. var wheel = wheelInfos[i];
  83816. var groundObject = wheel.raycastResult.body;
  83817. if (groundObject){
  83818. numWheelsOnGround++;
  83819. }
  83820. wheel.sideImpulse = 0;
  83821. wheel.forwardImpulse = 0;
  83822. if(!forwardWS[i]){
  83823. forwardWS[i] = new Vec3();
  83824. }
  83825. if(!axle[i]){
  83826. axle[i] = new Vec3();
  83827. }
  83828. }
  83829. for (var i = 0; i < numWheels; i++){
  83830. var wheel = wheelInfos[i];
  83831. var groundObject = wheel.raycastResult.body;
  83832. if (groundObject) {
  83833. var axlei = axle[i];
  83834. var wheelTrans = this.getWheelTransformWorld(i);
  83835. // Get world axle
  83836. wheelTrans.vectorToWorldFrame(directions[this.indexRightAxis], axlei);
  83837. var surfNormalWS = wheel.raycastResult.hitNormalWorld;
  83838. var proj = axlei.dot(surfNormalWS);
  83839. surfNormalWS.scale(proj, surfNormalWS_scaled_proj);
  83840. axlei.vsub(surfNormalWS_scaled_proj, axlei);
  83841. axlei.normalize();
  83842. surfNormalWS.cross(axlei, forwardWS[i]);
  83843. forwardWS[i].normalize();
  83844. wheel.sideImpulse = resolveSingleBilateral(
  83845. chassisBody,
  83846. wheel.raycastResult.hitPointWorld,
  83847. groundObject,
  83848. wheel.raycastResult.hitPointWorld,
  83849. axlei
  83850. );
  83851. wheel.sideImpulse *= sideFrictionStiffness2;
  83852. }
  83853. }
  83854. var sideFactor = 1;
  83855. var fwdFactor = 0.5;
  83856. this.sliding = false;
  83857. for (var i = 0; i < numWheels; i++) {
  83858. var wheel = wheelInfos[i];
  83859. var groundObject = wheel.raycastResult.body;
  83860. var rollingFriction = 0;
  83861. wheel.slipInfo = 1;
  83862. if (groundObject) {
  83863. var defaultRollingFrictionImpulse = 0;
  83864. var maxImpulse = wheel.brake ? wheel.brake : defaultRollingFrictionImpulse;
  83865. // btWheelContactPoint contactPt(chassisBody,groundObject,wheelInfraycastInfo.hitPointWorld,forwardWS[wheel],maxImpulse);
  83866. // rollingFriction = calcRollingFriction(contactPt);
  83867. rollingFriction = calcRollingFriction(chassisBody, groundObject, wheel.raycastResult.hitPointWorld, forwardWS[i], maxImpulse);
  83868. rollingFriction += wheel.engineForce * timeStep;
  83869. // rollingFriction = 0;
  83870. var factor = maxImpulse / rollingFriction;
  83871. wheel.slipInfo *= factor;
  83872. }
  83873. //switch between active rolling (throttle), braking and non-active rolling friction (nthrottle/break)
  83874. wheel.forwardImpulse = 0;
  83875. wheel.skidInfo = 1;
  83876. if (groundObject) {
  83877. wheel.skidInfo = 1;
  83878. var maximp = wheel.suspensionForce * timeStep * wheel.frictionSlip;
  83879. var maximpSide = maximp;
  83880. var maximpSquared = maximp * maximpSide;
  83881. wheel.forwardImpulse = rollingFriction;//wheelInfo.engineForce* timeStep;
  83882. var x = wheel.forwardImpulse * fwdFactor;
  83883. var y = wheel.sideImpulse * sideFactor;
  83884. var impulseSquared = x * x + y * y;
  83885. wheel.sliding = false;
  83886. if (impulseSquared > maximpSquared) {
  83887. this.sliding = true;
  83888. wheel.sliding = true;
  83889. var factor = maximp / Math.sqrt(impulseSquared);
  83890. wheel.skidInfo *= factor;
  83891. }
  83892. }
  83893. }
  83894. if (this.sliding) {
  83895. for (var i = 0; i < numWheels; i++) {
  83896. var wheel = wheelInfos[i];
  83897. if (wheel.sideImpulse !== 0) {
  83898. if (wheel.skidInfo < 1){
  83899. wheel.forwardImpulse *= wheel.skidInfo;
  83900. wheel.sideImpulse *= wheel.skidInfo;
  83901. }
  83902. }
  83903. }
  83904. }
  83905. // apply the impulses
  83906. for (var i = 0; i < numWheels; i++) {
  83907. var wheel = wheelInfos[i];
  83908. var rel_pos = new Vec3();
  83909. //wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, rel_pos);
  83910. // cannons applyimpulse is using world coord for the position
  83911. rel_pos.copy(wheel.raycastResult.hitPointWorld);
  83912. if (wheel.forwardImpulse !== 0) {
  83913. var impulse = new Vec3();
  83914. forwardWS[i].scale(wheel.forwardImpulse, impulse);
  83915. chassisBody.applyImpulse(impulse, rel_pos);
  83916. }
  83917. if (wheel.sideImpulse !== 0){
  83918. var groundObject = wheel.raycastResult.body;
  83919. var rel_pos2 = new Vec3();
  83920. //wheel.raycastResult.hitPointWorld.vsub(groundObject.position, rel_pos2);
  83921. rel_pos2.copy(wheel.raycastResult.hitPointWorld);
  83922. var sideImp = new Vec3();
  83923. axle[i].scale(wheel.sideImpulse, sideImp);
  83924. // Scale the relative position in the up direction with rollInfluence.
  83925. // If rollInfluence is 1, the impulse will be applied on the hitPoint (easy to roll over), if it is zero it will be applied in the same plane as the center of mass (not easy to roll over).
  83926. chassisBody.pointToLocalFrame(rel_pos, rel_pos);
  83927. rel_pos['xyz'[this.indexUpAxis]] *= wheel.rollInfluence;
  83928. chassisBody.pointToWorldFrame(rel_pos, rel_pos);
  83929. chassisBody.applyImpulse(sideImp, rel_pos);
  83930. //apply friction impulse on the ground
  83931. sideImp.scale(-1, sideImp);
  83932. groundObject.applyImpulse(sideImp, rel_pos2);
  83933. }
  83934. }
  83935. };
  83936. var calcRollingFriction_vel1 = new Vec3();
  83937. var calcRollingFriction_vel2 = new Vec3();
  83938. var calcRollingFriction_vel = new Vec3();
  83939. function calcRollingFriction(body0, body1, frictionPosWorld, frictionDirectionWorld, maxImpulse) {
  83940. var j1 = 0;
  83941. var contactPosWorld = frictionPosWorld;
  83942. // var rel_pos1 = new Vec3();
  83943. // var rel_pos2 = new Vec3();
  83944. var vel1 = calcRollingFriction_vel1;
  83945. var vel2 = calcRollingFriction_vel2;
  83946. var vel = calcRollingFriction_vel;
  83947. // contactPosWorld.vsub(body0.position, rel_pos1);
  83948. // contactPosWorld.vsub(body1.position, rel_pos2);
  83949. body0.getVelocityAtWorldPoint(contactPosWorld, vel1);
  83950. body1.getVelocityAtWorldPoint(contactPosWorld, vel2);
  83951. vel1.vsub(vel2, vel);
  83952. var vrel = frictionDirectionWorld.dot(vel);
  83953. var denom0 = computeImpulseDenominator(body0, frictionPosWorld, frictionDirectionWorld);
  83954. var denom1 = computeImpulseDenominator(body1, frictionPosWorld, frictionDirectionWorld);
  83955. var relaxation = 1;
  83956. var jacDiagABInv = relaxation / (denom0 + denom1);
  83957. // calculate j that moves us to zero relative velocity
  83958. j1 = -vrel * jacDiagABInv;
  83959. if (maxImpulse < j1) {
  83960. j1 = maxImpulse;
  83961. }
  83962. if (j1 < -maxImpulse) {
  83963. j1 = -maxImpulse;
  83964. }
  83965. return j1;
  83966. }
  83967. var computeImpulseDenominator_r0 = new Vec3();
  83968. var computeImpulseDenominator_c0 = new Vec3();
  83969. var computeImpulseDenominator_vec = new Vec3();
  83970. var computeImpulseDenominator_m = new Vec3();
  83971. function computeImpulseDenominator(body, pos, normal) {
  83972. var r0 = computeImpulseDenominator_r0;
  83973. var c0 = computeImpulseDenominator_c0;
  83974. var vec = computeImpulseDenominator_vec;
  83975. var m = computeImpulseDenominator_m;
  83976. pos.vsub(body.position, r0);
  83977. r0.cross(normal, c0);
  83978. body.invInertiaWorld.vmult(c0, m);
  83979. m.cross(r0, vec);
  83980. return body.invMass + normal.dot(vec);
  83981. }
  83982. var resolveSingleBilateral_vel1 = new Vec3();
  83983. var resolveSingleBilateral_vel2 = new Vec3();
  83984. var resolveSingleBilateral_vel = new Vec3();
  83985. //bilateral constraint between two dynamic objects
  83986. function resolveSingleBilateral(body1, pos1, body2, pos2, normal, impulse){
  83987. var normalLenSqr = normal.norm2();
  83988. if (normalLenSqr > 1.1){
  83989. return 0; // no impulse
  83990. }
  83991. // var rel_pos1 = new Vec3();
  83992. // var rel_pos2 = new Vec3();
  83993. // pos1.vsub(body1.position, rel_pos1);
  83994. // pos2.vsub(body2.position, rel_pos2);
  83995. var vel1 = resolveSingleBilateral_vel1;
  83996. var vel2 = resolveSingleBilateral_vel2;
  83997. var vel = resolveSingleBilateral_vel;
  83998. body1.getVelocityAtWorldPoint(pos1, vel1);
  83999. body2.getVelocityAtWorldPoint(pos2, vel2);
  84000. vel1.vsub(vel2, vel);
  84001. var rel_vel = normal.dot(vel);
  84002. var contactDamping = 0.2;
  84003. var massTerm = 1 / (body1.invMass + body2.invMass);
  84004. var impulse = - contactDamping * rel_vel * massTerm;
  84005. return impulse;
  84006. }
  84007. },{"../collision/Ray":9,"../collision/RaycastResult":10,"../math/Quaternion":28,"../math/Vec3":30,"../objects/WheelInfo":36,"./Body":31}],33:[function(_dereq_,module,exports){
  84008. var Body = _dereq_('./Body');
  84009. var Sphere = _dereq_('../shapes/Sphere');
  84010. var Box = _dereq_('../shapes/Box');
  84011. var Vec3 = _dereq_('../math/Vec3');
  84012. var HingeConstraint = _dereq_('../constraints/HingeConstraint');
  84013. module.exports = RigidVehicle;
  84014. /**
  84015. * Simple vehicle helper class with spherical rigid body wheels.
  84016. * @class RigidVehicle
  84017. * @constructor
  84018. * @param {Body} [options.chassisBody]
  84019. */
  84020. function RigidVehicle(options){
  84021. this.wheelBodies = [];
  84022. /**
  84023. * @property coordinateSystem
  84024. * @type {Vec3}
  84025. */
  84026. this.coordinateSystem = typeof(options.coordinateSystem)==='undefined' ? new Vec3(1, 2, 3) : options.coordinateSystem.clone();
  84027. /**
  84028. * @property {Body} chassisBody
  84029. */
  84030. this.chassisBody = options.chassisBody;
  84031. if(!this.chassisBody){
  84032. // No chassis body given. Create it!
  84033. var chassisShape = new Box(new Vec3(5, 2, 0.5));
  84034. this.chassisBody = new Body(1, chassisShape);
  84035. }
  84036. /**
  84037. * @property constraints
  84038. * @type {Array}
  84039. */
  84040. this.constraints = [];
  84041. this.wheelAxes = [];
  84042. this.wheelForces = [];
  84043. }
  84044. /**
  84045. * Add a wheel
  84046. * @method addWheel
  84047. * @param {object} options
  84048. * @param {boolean} [options.isFrontWheel]
  84049. * @param {Vec3} [options.position] Position of the wheel, locally in the chassis body.
  84050. * @param {Vec3} [options.direction] Slide direction of the wheel along the suspension.
  84051. * @param {Vec3} [options.axis] Axis of rotation of the wheel, locally defined in the chassis.
  84052. * @param {Body} [options.body] The wheel body.
  84053. */
  84054. RigidVehicle.prototype.addWheel = function(options){
  84055. options = options || {};
  84056. var wheelBody = options.body;
  84057. if(!wheelBody){
  84058. wheelBody = new Body(1, new Sphere(1.2));
  84059. }
  84060. this.wheelBodies.push(wheelBody);
  84061. this.wheelForces.push(0);
  84062. // Position constrain wheels
  84063. var zero = new Vec3();
  84064. var position = typeof(options.position) !== 'undefined' ? options.position.clone() : new Vec3();
  84065. // Set position locally to the chassis
  84066. var worldPosition = new Vec3();
  84067. this.chassisBody.pointToWorldFrame(position, worldPosition);
  84068. wheelBody.position.set(worldPosition.x, worldPosition.y, worldPosition.z);
  84069. // Constrain wheel
  84070. var axis = typeof(options.axis) !== 'undefined' ? options.axis.clone() : new Vec3(0, 1, 0);
  84071. this.wheelAxes.push(axis);
  84072. var hingeConstraint = new HingeConstraint(this.chassisBody, wheelBody, {
  84073. pivotA: position,
  84074. axisA: axis,
  84075. pivotB: Vec3.ZERO,
  84076. axisB: axis,
  84077. collideConnected: false
  84078. });
  84079. this.constraints.push(hingeConstraint);
  84080. return this.wheelBodies.length - 1;
  84081. };
  84082. /**
  84083. * Set the steering value of a wheel.
  84084. * @method setSteeringValue
  84085. * @param {number} value
  84086. * @param {integer} wheelIndex
  84087. * @todo check coordinateSystem
  84088. */
  84089. RigidVehicle.prototype.setSteeringValue = function(value, wheelIndex){
  84090. // Set angle of the hinge axis
  84091. var axis = this.wheelAxes[wheelIndex];
  84092. var c = Math.cos(value),
  84093. s = Math.sin(value),
  84094. x = axis.x,
  84095. y = axis.y;
  84096. this.constraints[wheelIndex].axisA.set(
  84097. c*x -s*y,
  84098. s*x +c*y,
  84099. 0
  84100. );
  84101. };
  84102. /**
  84103. * Set the target rotational speed of the hinge constraint.
  84104. * @method setMotorSpeed
  84105. * @param {number} value
  84106. * @param {integer} wheelIndex
  84107. */
  84108. RigidVehicle.prototype.setMotorSpeed = function(value, wheelIndex){
  84109. var hingeConstraint = this.constraints[wheelIndex];
  84110. hingeConstraint.enableMotor();
  84111. hingeConstraint.motorTargetVelocity = value;
  84112. };
  84113. /**
  84114. * Set the target rotational speed of the hinge constraint.
  84115. * @method disableMotor
  84116. * @param {number} value
  84117. * @param {integer} wheelIndex
  84118. */
  84119. RigidVehicle.prototype.disableMotor = function(wheelIndex){
  84120. var hingeConstraint = this.constraints[wheelIndex];
  84121. hingeConstraint.disableMotor();
  84122. };
  84123. var torque = new Vec3();
  84124. /**
  84125. * Set the wheel force to apply on one of the wheels each time step
  84126. * @method setWheelForce
  84127. * @param {number} value
  84128. * @param {integer} wheelIndex
  84129. */
  84130. RigidVehicle.prototype.setWheelForce = function(value, wheelIndex){
  84131. this.wheelForces[wheelIndex] = value;
  84132. };
  84133. /**
  84134. * Apply a torque on one of the wheels.
  84135. * @method applyWheelForce
  84136. * @param {number} value
  84137. * @param {integer} wheelIndex
  84138. */
  84139. RigidVehicle.prototype.applyWheelForce = function(value, wheelIndex){
  84140. var axis = this.wheelAxes[wheelIndex];
  84141. var wheelBody = this.wheelBodies[wheelIndex];
  84142. var bodyTorque = wheelBody.torque;
  84143. axis.scale(value, torque);
  84144. wheelBody.vectorToWorldFrame(torque, torque);
  84145. bodyTorque.vadd(torque, bodyTorque);
  84146. };
  84147. /**
  84148. * Add the vehicle including its constraints to the world.
  84149. * @method addToWorld
  84150. * @param {World} world
  84151. */
  84152. RigidVehicle.prototype.addToWorld = function(world){
  84153. var constraints = this.constraints;
  84154. var bodies = this.wheelBodies.concat([this.chassisBody]);
  84155. for (var i = 0; i < bodies.length; i++) {
  84156. world.add(bodies[i]);
  84157. }
  84158. for (var i = 0; i < constraints.length; i++) {
  84159. world.addConstraint(constraints[i]);
  84160. }
  84161. world.addEventListener('preStep', this._update.bind(this));
  84162. };
  84163. RigidVehicle.prototype._update = function(){
  84164. var wheelForces = this.wheelForces;
  84165. for (var i = 0; i < wheelForces.length; i++) {
  84166. this.applyWheelForce(wheelForces[i], i);
  84167. }
  84168. };
  84169. /**
  84170. * Remove the vehicle including its constraints from the world.
  84171. * @method removeFromWorld
  84172. * @param {World} world
  84173. */
  84174. RigidVehicle.prototype.removeFromWorld = function(world){
  84175. var constraints = this.constraints;
  84176. var bodies = this.wheelBodies.concat([this.chassisBody]);
  84177. for (var i = 0; i < bodies.length; i++) {
  84178. world.remove(bodies[i]);
  84179. }
  84180. for (var i = 0; i < constraints.length; i++) {
  84181. world.removeConstraint(constraints[i]);
  84182. }
  84183. };
  84184. var worldAxis = new Vec3();
  84185. /**
  84186. * Get current rotational velocity of a wheel
  84187. * @method getWheelSpeed
  84188. * @param {integer} wheelIndex
  84189. */
  84190. RigidVehicle.prototype.getWheelSpeed = function(wheelIndex){
  84191. var axis = this.wheelAxes[wheelIndex];
  84192. var wheelBody = this.wheelBodies[wheelIndex];
  84193. var w = wheelBody.angularVelocity;
  84194. this.chassisBody.vectorToWorldFrame(axis, worldAxis);
  84195. return w.dot(worldAxis);
  84196. };
  84197. },{"../constraints/HingeConstraint":15,"../math/Vec3":30,"../shapes/Box":37,"../shapes/Sphere":44,"./Body":31}],34:[function(_dereq_,module,exports){
  84198. module.exports = SPHSystem;
  84199. var Shape = _dereq_('../shapes/Shape');
  84200. var Vec3 = _dereq_('../math/Vec3');
  84201. var Quaternion = _dereq_('../math/Quaternion');
  84202. var Particle = _dereq_('../shapes/Particle');
  84203. var Body = _dereq_('../objects/Body');
  84204. var Material = _dereq_('../material/Material');
  84205. /**
  84206. * Smoothed-particle hydrodynamics system
  84207. * @class SPHSystem
  84208. * @constructor
  84209. */
  84210. function SPHSystem(){
  84211. this.particles = [];
  84212. /**
  84213. * Density of the system (kg/m3).
  84214. * @property {number} density
  84215. */
  84216. this.density = 1;
  84217. /**
  84218. * Distance below which two particles are considered to be neighbors.
  84219. * It should be adjusted so there are about 15-20 neighbor particles within this radius.
  84220. * @property {number} smoothingRadius
  84221. */
  84222. this.smoothingRadius = 1;
  84223. this.speedOfSound = 1;
  84224. /**
  84225. * Viscosity of the system.
  84226. * @property {number} viscosity
  84227. */
  84228. this.viscosity = 0.01;
  84229. this.eps = 0.000001;
  84230. // Stuff Computed per particle
  84231. this.pressures = [];
  84232. this.densities = [];
  84233. this.neighbors = [];
  84234. }
  84235. /**
  84236. * Add a particle to the system.
  84237. * @method add
  84238. * @param {Body} particle
  84239. */
  84240. SPHSystem.prototype.add = function(particle){
  84241. this.particles.push(particle);
  84242. if(this.neighbors.length < this.particles.length){
  84243. this.neighbors.push([]);
  84244. }
  84245. };
  84246. /**
  84247. * Remove a particle from the system.
  84248. * @method remove
  84249. * @param {Body} particle
  84250. */
  84251. SPHSystem.prototype.remove = function(particle){
  84252. var idx = this.particles.indexOf(particle);
  84253. if(idx !== -1){
  84254. this.particles.splice(idx,1);
  84255. if(this.neighbors.length > this.particles.length){
  84256. this.neighbors.pop();
  84257. }
  84258. }
  84259. };
  84260. /**
  84261. * Get neighbors within smoothing volume, save in the array neighbors
  84262. * @method getNeighbors
  84263. * @param {Body} particle
  84264. * @param {Array} neighbors
  84265. */
  84266. var SPHSystem_getNeighbors_dist = new Vec3();
  84267. SPHSystem.prototype.getNeighbors = function(particle,neighbors){
  84268. var N = this.particles.length,
  84269. id = particle.id,
  84270. R2 = this.smoothingRadius * this.smoothingRadius,
  84271. dist = SPHSystem_getNeighbors_dist;
  84272. for(var i=0; i!==N; i++){
  84273. var p = this.particles[i];
  84274. p.position.vsub(particle.position,dist);
  84275. if(id!==p.id && dist.norm2() < R2){
  84276. neighbors.push(p);
  84277. }
  84278. }
  84279. };
  84280. // Temp vectors for calculation
  84281. var SPHSystem_update_dist = new Vec3(),
  84282. SPHSystem_update_a_pressure = new Vec3(),
  84283. SPHSystem_update_a_visc = new Vec3(),
  84284. SPHSystem_update_gradW = new Vec3(),
  84285. SPHSystem_update_r_vec = new Vec3(),
  84286. SPHSystem_update_u = new Vec3(); // Relative velocity
  84287. SPHSystem.prototype.update = function(){
  84288. var N = this.particles.length,
  84289. dist = SPHSystem_update_dist,
  84290. cs = this.speedOfSound,
  84291. eps = this.eps;
  84292. for(var i=0; i!==N; i++){
  84293. var p = this.particles[i]; // Current particle
  84294. var neighbors = this.neighbors[i];
  84295. // Get neighbors
  84296. neighbors.length = 0;
  84297. this.getNeighbors(p,neighbors);
  84298. neighbors.push(this.particles[i]); // Add current too
  84299. var numNeighbors = neighbors.length;
  84300. // Accumulate density for the particle
  84301. var sum = 0.0;
  84302. for(var j=0; j!==numNeighbors; j++){
  84303. //printf("Current particle has position %f %f %f\n",objects[id].pos.x(),objects[id].pos.y(),objects[id].pos.z());
  84304. p.position.vsub(neighbors[j].position, dist);
  84305. var len = dist.norm();
  84306. var weight = this.w(len);
  84307. sum += neighbors[j].mass * weight;
  84308. }
  84309. // Save
  84310. this.densities[i] = sum;
  84311. this.pressures[i] = cs * cs * (this.densities[i] - this.density);
  84312. }
  84313. // Add forces
  84314. // Sum to these accelerations
  84315. var a_pressure= SPHSystem_update_a_pressure;
  84316. var a_visc = SPHSystem_update_a_visc;
  84317. var gradW = SPHSystem_update_gradW;
  84318. var r_vec = SPHSystem_update_r_vec;
  84319. var u = SPHSystem_update_u;
  84320. for(var i=0; i!==N; i++){
  84321. var particle = this.particles[i];
  84322. a_pressure.set(0,0,0);
  84323. a_visc.set(0,0,0);
  84324. // Init vars
  84325. var Pij;
  84326. var nabla;
  84327. var Vij;
  84328. // Sum up for all other neighbors
  84329. var neighbors = this.neighbors[i];
  84330. var numNeighbors = neighbors.length;
  84331. //printf("Neighbors: ");
  84332. for(var j=0; j!==numNeighbors; j++){
  84333. var neighbor = neighbors[j];
  84334. //printf("%d ",nj);
  84335. // Get r once for all..
  84336. particle.position.vsub(neighbor.position,r_vec);
  84337. var r = r_vec.norm();
  84338. // Pressure contribution
  84339. Pij = -neighbor.mass * (this.pressures[i] / (this.densities[i]*this.densities[i] + eps) + this.pressures[j] / (this.densities[j]*this.densities[j] + eps));
  84340. this.gradw(r_vec, gradW);
  84341. // Add to pressure acceleration
  84342. gradW.mult(Pij , gradW);
  84343. a_pressure.vadd(gradW, a_pressure);
  84344. // Viscosity contribution
  84345. neighbor.velocity.vsub(particle.velocity, u);
  84346. u.mult( 1.0 / (0.0001+this.densities[i] * this.densities[j]) * this.viscosity * neighbor.mass , u );
  84347. nabla = this.nablaw(r);
  84348. u.mult(nabla,u);
  84349. // Add to viscosity acceleration
  84350. a_visc.vadd( u, a_visc );
  84351. }
  84352. // Calculate force
  84353. a_visc.mult(particle.mass, a_visc);
  84354. a_pressure.mult(particle.mass, a_pressure);
  84355. // Add force to particles
  84356. particle.force.vadd(a_visc, particle.force);
  84357. particle.force.vadd(a_pressure, particle.force);
  84358. }
  84359. };
  84360. // Calculate the weight using the W(r) weightfunction
  84361. SPHSystem.prototype.w = function(r){
  84362. // 315
  84363. var h = this.smoothingRadius;
  84364. return 315.0/(64.0*Math.PI*Math.pow(h,9)) * Math.pow(h*h-r*r,3);
  84365. };
  84366. // calculate gradient of the weight function
  84367. SPHSystem.prototype.gradw = function(rVec,resultVec){
  84368. var r = rVec.norm(),
  84369. h = this.smoothingRadius;
  84370. rVec.mult(945.0/(32.0*Math.PI*Math.pow(h,9)) * Math.pow((h*h-r*r),2) , resultVec);
  84371. };
  84372. // Calculate nabla(W)
  84373. SPHSystem.prototype.nablaw = function(r){
  84374. var h = this.smoothingRadius;
  84375. var nabla = 945.0/(32.0*Math.PI*Math.pow(h,9)) * (h*h-r*r)*(7*r*r - 3*h*h);
  84376. return nabla;
  84377. };
  84378. },{"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Particle":41,"../shapes/Shape":43}],35:[function(_dereq_,module,exports){
  84379. var Vec3 = _dereq_('../math/Vec3');
  84380. module.exports = Spring;
  84381. /**
  84382. * A spring, connecting two bodies.
  84383. *
  84384. * @class Spring
  84385. * @constructor
  84386. * @param {Body} bodyA
  84387. * @param {Body} bodyB
  84388. * @param {Object} [options]
  84389. * @param {number} [options.restLength] A number > 0. Default: 1
  84390. * @param {number} [options.stiffness] A number >= 0. Default: 100
  84391. * @param {number} [options.damping] A number >= 0. Default: 1
  84392. * @param {Vec3} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates.
  84393. * @param {Vec3} [options.worldAnchorB]
  84394. * @param {Vec3} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates.
  84395. * @param {Vec3} [options.localAnchorB]
  84396. */
  84397. function Spring(bodyA,bodyB,options){
  84398. options = options || {};
  84399. /**
  84400. * Rest length of the spring.
  84401. * @property restLength
  84402. * @type {number}
  84403. */
  84404. this.restLength = typeof(options.restLength) === "number" ? options.restLength : 1;
  84405. /**
  84406. * Stiffness of the spring.
  84407. * @property stiffness
  84408. * @type {number}
  84409. */
  84410. this.stiffness = options.stiffness || 100;
  84411. /**
  84412. * Damping of the spring.
  84413. * @property damping
  84414. * @type {number}
  84415. */
  84416. this.damping = options.damping || 1;
  84417. /**
  84418. * First connected body.
  84419. * @property bodyA
  84420. * @type {Body}
  84421. */
  84422. this.bodyA = bodyA;
  84423. /**
  84424. * Second connected body.
  84425. * @property bodyB
  84426. * @type {Body}
  84427. */
  84428. this.bodyB = bodyB;
  84429. /**
  84430. * Anchor for bodyA in local bodyA coordinates.
  84431. * @property localAnchorA
  84432. * @type {Vec3}
  84433. */
  84434. this.localAnchorA = new Vec3();
  84435. /**
  84436. * Anchor for bodyB in local bodyB coordinates.
  84437. * @property localAnchorB
  84438. * @type {Vec3}
  84439. */
  84440. this.localAnchorB = new Vec3();
  84441. if(options.localAnchorA){
  84442. this.localAnchorA.copy(options.localAnchorA);
  84443. }
  84444. if(options.localAnchorB){
  84445. this.localAnchorB.copy(options.localAnchorB);
  84446. }
  84447. if(options.worldAnchorA){
  84448. this.setWorldAnchorA(options.worldAnchorA);
  84449. }
  84450. if(options.worldAnchorB){
  84451. this.setWorldAnchorB(options.worldAnchorB);
  84452. }
  84453. }
  84454. /**
  84455. * Set the anchor point on body A, using world coordinates.
  84456. * @method setWorldAnchorA
  84457. * @param {Vec3} worldAnchorA
  84458. */
  84459. Spring.prototype.setWorldAnchorA = function(worldAnchorA){
  84460. this.bodyA.pointToLocalFrame(worldAnchorA,this.localAnchorA);
  84461. };
  84462. /**
  84463. * Set the anchor point on body B, using world coordinates.
  84464. * @method setWorldAnchorB
  84465. * @param {Vec3} worldAnchorB
  84466. */
  84467. Spring.prototype.setWorldAnchorB = function(worldAnchorB){
  84468. this.bodyB.pointToLocalFrame(worldAnchorB,this.localAnchorB);
  84469. };
  84470. /**
  84471. * Get the anchor point on body A, in world coordinates.
  84472. * @method getWorldAnchorA
  84473. * @param {Vec3} result The vector to store the result in.
  84474. */
  84475. Spring.prototype.getWorldAnchorA = function(result){
  84476. this.bodyA.pointToWorldFrame(this.localAnchorA,result);
  84477. };
  84478. /**
  84479. * Get the anchor point on body B, in world coordinates.
  84480. * @method getWorldAnchorB
  84481. * @param {Vec3} result The vector to store the result in.
  84482. */
  84483. Spring.prototype.getWorldAnchorB = function(result){
  84484. this.bodyB.pointToWorldFrame(this.localAnchorB,result);
  84485. };
  84486. var applyForce_r = new Vec3(),
  84487. applyForce_r_unit = new Vec3(),
  84488. applyForce_u = new Vec3(),
  84489. applyForce_f = new Vec3(),
  84490. applyForce_worldAnchorA = new Vec3(),
  84491. applyForce_worldAnchorB = new Vec3(),
  84492. applyForce_ri = new Vec3(),
  84493. applyForce_rj = new Vec3(),
  84494. applyForce_ri_x_f = new Vec3(),
  84495. applyForce_rj_x_f = new Vec3(),
  84496. applyForce_tmp = new Vec3();
  84497. /**
  84498. * Apply the spring force to the connected bodies.
  84499. * @method applyForce
  84500. */
  84501. Spring.prototype.applyForce = function(){
  84502. var k = this.stiffness,
  84503. d = this.damping,
  84504. l = this.restLength,
  84505. bodyA = this.bodyA,
  84506. bodyB = this.bodyB,
  84507. r = applyForce_r,
  84508. r_unit = applyForce_r_unit,
  84509. u = applyForce_u,
  84510. f = applyForce_f,
  84511. tmp = applyForce_tmp;
  84512. var worldAnchorA = applyForce_worldAnchorA,
  84513. worldAnchorB = applyForce_worldAnchorB,
  84514. ri = applyForce_ri,
  84515. rj = applyForce_rj,
  84516. ri_x_f = applyForce_ri_x_f,
  84517. rj_x_f = applyForce_rj_x_f;
  84518. // Get world anchors
  84519. this.getWorldAnchorA(worldAnchorA);
  84520. this.getWorldAnchorB(worldAnchorB);
  84521. // Get offset points
  84522. worldAnchorA.vsub(bodyA.position,ri);
  84523. worldAnchorB.vsub(bodyB.position,rj);
  84524. // Compute distance vector between world anchor points
  84525. worldAnchorB.vsub(worldAnchorA,r);
  84526. var rlen = r.norm();
  84527. r_unit.copy(r);
  84528. r_unit.normalize();
  84529. // Compute relative velocity of the anchor points, u
  84530. bodyB.velocity.vsub(bodyA.velocity,u);
  84531. // Add rotational velocity
  84532. bodyB.angularVelocity.cross(rj,tmp);
  84533. u.vadd(tmp,u);
  84534. bodyA.angularVelocity.cross(ri,tmp);
  84535. u.vsub(tmp,u);
  84536. // F = - k * ( x - L ) - D * ( u )
  84537. r_unit.mult(-k*(rlen-l) - d*u.dot(r_unit), f);
  84538. // Add forces to bodies
  84539. bodyA.force.vsub(f,bodyA.force);
  84540. bodyB.force.vadd(f,bodyB.force);
  84541. // Angular force
  84542. ri.cross(f,ri_x_f);
  84543. rj.cross(f,rj_x_f);
  84544. bodyA.torque.vsub(ri_x_f,bodyA.torque);
  84545. bodyB.torque.vadd(rj_x_f,bodyB.torque);
  84546. };
  84547. },{"../math/Vec3":30}],36:[function(_dereq_,module,exports){
  84548. var Vec3 = _dereq_('../math/Vec3');
  84549. var Transform = _dereq_('../math/Transform');
  84550. var RaycastResult = _dereq_('../collision/RaycastResult');
  84551. var Utils = _dereq_('../utils/Utils');
  84552. module.exports = WheelInfo;
  84553. /**
  84554. * @class WheelInfo
  84555. * @constructor
  84556. * @param {Object} [options]
  84557. *
  84558. * @param {Vec3} [options.chassisConnectionPointLocal]
  84559. * @param {Vec3} [options.chassisConnectionPointWorld]
  84560. * @param {Vec3} [options.directionLocal]
  84561. * @param {Vec3} [options.directionWorld]
  84562. * @param {Vec3} [options.axleLocal]
  84563. * @param {Vec3} [options.axleWorld]
  84564. * @param {number} [options.suspensionRestLength=1]
  84565. * @param {number} [options.suspensionMaxLength=2]
  84566. * @param {number} [options.radius=1]
  84567. * @param {number} [options.suspensionStiffness=100]
  84568. * @param {number} [options.dampingCompression=10]
  84569. * @param {number} [options.dampingRelaxation=10]
  84570. * @param {number} [options.frictionSlip=10000]
  84571. * @param {number} [options.steering=0]
  84572. * @param {number} [options.rotation=0]
  84573. * @param {number} [options.deltaRotation=0]
  84574. * @param {number} [options.rollInfluence=0.01]
  84575. * @param {number} [options.maxSuspensionForce]
  84576. * @param {boolean} [options.isFrontWheel=true]
  84577. * @param {number} [options.clippedInvContactDotSuspension=1]
  84578. * @param {number} [options.suspensionRelativeVelocity=0]
  84579. * @param {number} [options.suspensionForce=0]
  84580. * @param {number} [options.skidInfo=0]
  84581. * @param {number} [options.suspensionLength=0]
  84582. * @param {number} [options.maxSuspensionTravel=1]
  84583. * @param {boolean} [options.useCustomSlidingRotationalSpeed=false]
  84584. * @param {number} [options.customSlidingRotationalSpeed=-0.1]
  84585. */
  84586. function WheelInfo(options){
  84587. options = Utils.defaults(options, {
  84588. chassisConnectionPointLocal: new Vec3(),
  84589. chassisConnectionPointWorld: new Vec3(),
  84590. directionLocal: new Vec3(),
  84591. directionWorld: new Vec3(),
  84592. axleLocal: new Vec3(),
  84593. axleWorld: new Vec3(),
  84594. suspensionRestLength: 1,
  84595. suspensionMaxLength: 2,
  84596. radius: 1,
  84597. suspensionStiffness: 100,
  84598. dampingCompression: 10,
  84599. dampingRelaxation: 10,
  84600. frictionSlip: 10000,
  84601. steering: 0,
  84602. rotation: 0,
  84603. deltaRotation: 0,
  84604. rollInfluence: 0.01,
  84605. maxSuspensionForce: Number.MAX_VALUE,
  84606. isFrontWheel: true,
  84607. clippedInvContactDotSuspension: 1,
  84608. suspensionRelativeVelocity: 0,
  84609. suspensionForce: 0,
  84610. skidInfo: 0,
  84611. suspensionLength: 0,
  84612. maxSuspensionTravel: 1,
  84613. useCustomSlidingRotationalSpeed: false,
  84614. customSlidingRotationalSpeed: -0.1
  84615. });
  84616. /**
  84617. * Max travel distance of the suspension, in meters.
  84618. * @property {number} maxSuspensionTravel
  84619. */
  84620. this.maxSuspensionTravel = options.maxSuspensionTravel;
  84621. /**
  84622. * Speed to apply to the wheel rotation when the wheel is sliding.
  84623. * @property {number} customSlidingRotationalSpeed
  84624. */
  84625. this.customSlidingRotationalSpeed = options.customSlidingRotationalSpeed;
  84626. /**
  84627. * If the customSlidingRotationalSpeed should be used.
  84628. * @property {Boolean} useCustomSlidingRotationalSpeed
  84629. */
  84630. this.useCustomSlidingRotationalSpeed = options.useCustomSlidingRotationalSpeed;
  84631. /**
  84632. * @property {Boolean} sliding
  84633. */
  84634. this.sliding = false;
  84635. /**
  84636. * Connection point, defined locally in the chassis body frame.
  84637. * @property {Vec3} chassisConnectionPointLocal
  84638. */
  84639. this.chassisConnectionPointLocal = options.chassisConnectionPointLocal.clone();
  84640. /**
  84641. * @property {Vec3} chassisConnectionPointWorld
  84642. */
  84643. this.chassisConnectionPointWorld = options.chassisConnectionPointWorld.clone();
  84644. /**
  84645. * @property {Vec3} directionLocal
  84646. */
  84647. this.directionLocal = options.directionLocal.clone();
  84648. /**
  84649. * @property {Vec3} directionWorld
  84650. */
  84651. this.directionWorld = options.directionWorld.clone();
  84652. /**
  84653. * @property {Vec3} axleLocal
  84654. */
  84655. this.axleLocal = options.axleLocal.clone();
  84656. /**
  84657. * @property {Vec3} axleWorld
  84658. */
  84659. this.axleWorld = options.axleWorld.clone();
  84660. /**
  84661. * @property {number} suspensionRestLength
  84662. */
  84663. this.suspensionRestLength = options.suspensionRestLength;
  84664. /**
  84665. * @property {number} suspensionMaxLength
  84666. */
  84667. this.suspensionMaxLength = options.suspensionMaxLength;
  84668. /**
  84669. * @property {number} radius
  84670. */
  84671. this.radius = options.radius;
  84672. /**
  84673. * @property {number} suspensionStiffness
  84674. */
  84675. this.suspensionStiffness = options.suspensionStiffness;
  84676. /**
  84677. * @property {number} dampingCompression
  84678. */
  84679. this.dampingCompression = options.dampingCompression;
  84680. /**
  84681. * @property {number} dampingRelaxation
  84682. */
  84683. this.dampingRelaxation = options.dampingRelaxation;
  84684. /**
  84685. * @property {number} frictionSlip
  84686. */
  84687. this.frictionSlip = options.frictionSlip;
  84688. /**
  84689. * @property {number} steering
  84690. */
  84691. this.steering = 0;
  84692. /**
  84693. * Rotation value, in radians.
  84694. * @property {number} rotation
  84695. */
  84696. this.rotation = 0;
  84697. /**
  84698. * @property {number} deltaRotation
  84699. */
  84700. this.deltaRotation = 0;
  84701. /**
  84702. * @property {number} rollInfluence
  84703. */
  84704. this.rollInfluence = options.rollInfluence;
  84705. /**
  84706. * @property {number} maxSuspensionForce
  84707. */
  84708. this.maxSuspensionForce = options.maxSuspensionForce;
  84709. /**
  84710. * @property {number} engineForce
  84711. */
  84712. this.engineForce = 0;
  84713. /**
  84714. * @property {number} brake
  84715. */
  84716. this.brake = 0;
  84717. /**
  84718. * @property {number} isFrontWheel
  84719. */
  84720. this.isFrontWheel = options.isFrontWheel;
  84721. /**
  84722. * @property {number} clippedInvContactDotSuspension
  84723. */
  84724. this.clippedInvContactDotSuspension = 1;
  84725. /**
  84726. * @property {number} suspensionRelativeVelocity
  84727. */
  84728. this.suspensionRelativeVelocity = 0;
  84729. /**
  84730. * @property {number} suspensionForce
  84731. */
  84732. this.suspensionForce = 0;
  84733. /**
  84734. * @property {number} skidInfo
  84735. */
  84736. this.skidInfo = 0;
  84737. /**
  84738. * @property {number} suspensionLength
  84739. */
  84740. this.suspensionLength = 0;
  84741. /**
  84742. * @property {number} sideImpulse
  84743. */
  84744. this.sideImpulse = 0;
  84745. /**
  84746. * @property {number} forwardImpulse
  84747. */
  84748. this.forwardImpulse = 0;
  84749. /**
  84750. * The result from raycasting
  84751. * @property {RaycastResult} raycastResult
  84752. */
  84753. this.raycastResult = new RaycastResult();
  84754. /**
  84755. * Wheel world transform
  84756. * @property {Transform} worldTransform
  84757. */
  84758. this.worldTransform = new Transform();
  84759. /**
  84760. * @property {boolean} isInContact
  84761. */
  84762. this.isInContact = false;
  84763. }
  84764. var chassis_velocity_at_contactPoint = new Vec3();
  84765. var relpos = new Vec3();
  84766. var chassis_velocity_at_contactPoint = new Vec3();
  84767. WheelInfo.prototype.updateWheel = function(chassis){
  84768. var raycastResult = this.raycastResult;
  84769. if (this.isInContact){
  84770. var project= raycastResult.hitNormalWorld.dot(raycastResult.directionWorld);
  84771. raycastResult.hitPointWorld.vsub(chassis.position, relpos);
  84772. chassis.getVelocityAtWorldPoint(relpos, chassis_velocity_at_contactPoint);
  84773. var projVel = raycastResult.hitNormalWorld.dot( chassis_velocity_at_contactPoint );
  84774. if (project >= -0.1) {
  84775. this.suspensionRelativeVelocity = 0.0;
  84776. this.clippedInvContactDotSuspension = 1.0 / 0.1;
  84777. } else {
  84778. var inv = -1 / project;
  84779. this.suspensionRelativeVelocity = projVel * inv;
  84780. this.clippedInvContactDotSuspension = inv;
  84781. }
  84782. } else {
  84783. // Not in contact : position wheel in a nice (rest length) position
  84784. raycastResult.suspensionLength = this.suspensionRestLength;
  84785. this.suspensionRelativeVelocity = 0.0;
  84786. raycastResult.directionWorld.scale(-1, raycastResult.hitNormalWorld);
  84787. this.clippedInvContactDotSuspension = 1.0;
  84788. }
  84789. };
  84790. },{"../collision/RaycastResult":10,"../math/Transform":29,"../math/Vec3":30,"../utils/Utils":53}],37:[function(_dereq_,module,exports){
  84791. module.exports = Box;
  84792. var Shape = _dereq_('./Shape');
  84793. var Vec3 = _dereq_('../math/Vec3');
  84794. var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');
  84795. /**
  84796. * A 3d box shape.
  84797. * @class Box
  84798. * @constructor
  84799. * @param {Vec3} halfExtents
  84800. * @author schteppe
  84801. * @extends Shape
  84802. */
  84803. function Box(halfExtents){
  84804. Shape.call(this);
  84805. this.type = Shape.types.BOX;
  84806. /**
  84807. * @property halfExtents
  84808. * @type {Vec3}
  84809. */
  84810. this.halfExtents = halfExtents;
  84811. /**
  84812. * Used by the contact generator to make contacts with other convex polyhedra for example
  84813. * @property convexPolyhedronRepresentation
  84814. * @type {ConvexPolyhedron}
  84815. */
  84816. this.convexPolyhedronRepresentation = null;
  84817. this.updateConvexPolyhedronRepresentation();
  84818. this.updateBoundingSphereRadius();
  84819. }
  84820. Box.prototype = new Shape();
  84821. Box.prototype.constructor = Box;
  84822. /**
  84823. * Updates the local convex polyhedron representation used for some collisions.
  84824. * @method updateConvexPolyhedronRepresentation
  84825. */
  84826. Box.prototype.updateConvexPolyhedronRepresentation = function(){
  84827. var sx = this.halfExtents.x;
  84828. var sy = this.halfExtents.y;
  84829. var sz = this.halfExtents.z;
  84830. var V = Vec3;
  84831. var vertices = [
  84832. new V(-sx,-sy,-sz),
  84833. new V( sx,-sy,-sz),
  84834. new V( sx, sy,-sz),
  84835. new V(-sx, sy,-sz),
  84836. new V(-sx,-sy, sz),
  84837. new V( sx,-sy, sz),
  84838. new V( sx, sy, sz),
  84839. new V(-sx, sy, sz)
  84840. ];
  84841. var indices = [
  84842. [3,2,1,0], // -z
  84843. [4,5,6,7], // +z
  84844. [5,4,0,1], // -y
  84845. [2,3,7,6], // +y
  84846. [0,4,7,3], // -x
  84847. [1,2,6,5], // +x
  84848. ];
  84849. var axes = [
  84850. new V(0, 0, 1),
  84851. new V(0, 1, 0),
  84852. new V(1, 0, 0)
  84853. ];
  84854. var h = new ConvexPolyhedron(vertices, indices);
  84855. this.convexPolyhedronRepresentation = h;
  84856. h.material = this.material;
  84857. };
  84858. /**
  84859. * @method calculateLocalInertia
  84860. * @param {Number} mass
  84861. * @param {Vec3} target
  84862. * @return {Vec3}
  84863. */
  84864. Box.prototype.calculateLocalInertia = function(mass,target){
  84865. target = target || new Vec3();
  84866. Box.calculateInertia(this.halfExtents, mass, target);
  84867. return target;
  84868. };
  84869. Box.calculateInertia = function(halfExtents,mass,target){
  84870. var e = halfExtents;
  84871. target.x = 1.0 / 12.0 * mass * ( 2*e.y*2*e.y + 2*e.z*2*e.z );
  84872. target.y = 1.0 / 12.0 * mass * ( 2*e.x*2*e.x + 2*e.z*2*e.z );
  84873. target.z = 1.0 / 12.0 * mass * ( 2*e.y*2*e.y + 2*e.x*2*e.x );
  84874. };
  84875. /**
  84876. * Get the box 6 side normals
  84877. * @method getSideNormals
  84878. * @param {array} sixTargetVectors An array of 6 vectors, to store the resulting side normals in.
  84879. * @param {Quaternion} quat Orientation to apply to the normal vectors. If not provided, the vectors will be in respect to the local frame.
  84880. * @return {array}
  84881. */
  84882. Box.prototype.getSideNormals = function(sixTargetVectors,quat){
  84883. var sides = sixTargetVectors;
  84884. var ex = this.halfExtents;
  84885. sides[0].set( ex.x, 0, 0);
  84886. sides[1].set( 0, ex.y, 0);
  84887. sides[2].set( 0, 0, ex.z);
  84888. sides[3].set( -ex.x, 0, 0);
  84889. sides[4].set( 0, -ex.y, 0);
  84890. sides[5].set( 0, 0, -ex.z);
  84891. if(quat!==undefined){
  84892. for(var i=0; i!==sides.length; i++){
  84893. quat.vmult(sides[i],sides[i]);
  84894. }
  84895. }
  84896. return sides;
  84897. };
  84898. Box.prototype.volume = function(){
  84899. return 8.0 * this.halfExtents.x * this.halfExtents.y * this.halfExtents.z;
  84900. };
  84901. Box.prototype.updateBoundingSphereRadius = function(){
  84902. this.boundingSphereRadius = this.halfExtents.norm();
  84903. };
  84904. var worldCornerTempPos = new Vec3();
  84905. var worldCornerTempNeg = new Vec3();
  84906. Box.prototype.forEachWorldCorner = function(pos,quat,callback){
  84907. var e = this.halfExtents;
  84908. var corners = [[ e.x, e.y, e.z],
  84909. [ -e.x, e.y, e.z],
  84910. [ -e.x, -e.y, e.z],
  84911. [ -e.x, -e.y, -e.z],
  84912. [ e.x, -e.y, -e.z],
  84913. [ e.x, e.y, -e.z],
  84914. [ -e.x, e.y, -e.z],
  84915. [ e.x, -e.y, e.z]];
  84916. for(var i=0; i<corners.length; i++){
  84917. worldCornerTempPos.set(corners[i][0],corners[i][1],corners[i][2]);
  84918. quat.vmult(worldCornerTempPos,worldCornerTempPos);
  84919. pos.vadd(worldCornerTempPos,worldCornerTempPos);
  84920. callback(worldCornerTempPos.x,
  84921. worldCornerTempPos.y,
  84922. worldCornerTempPos.z);
  84923. }
  84924. };
  84925. var worldCornersTemp = [
  84926. new Vec3(),
  84927. new Vec3(),
  84928. new Vec3(),
  84929. new Vec3(),
  84930. new Vec3(),
  84931. new Vec3(),
  84932. new Vec3(),
  84933. new Vec3()
  84934. ];
  84935. Box.prototype.calculateWorldAABB = function(pos,quat,min,max){
  84936. var e = this.halfExtents;
  84937. worldCornersTemp[0].set(e.x, e.y, e.z);
  84938. worldCornersTemp[1].set(-e.x, e.y, e.z);
  84939. worldCornersTemp[2].set(-e.x, -e.y, e.z);
  84940. worldCornersTemp[3].set(-e.x, -e.y, -e.z);
  84941. worldCornersTemp[4].set(e.x, -e.y, -e.z);
  84942. worldCornersTemp[5].set(e.x, e.y, -e.z);
  84943. worldCornersTemp[6].set(-e.x, e.y, -e.z);
  84944. worldCornersTemp[7].set(e.x, -e.y, e.z);
  84945. var wc = worldCornersTemp[0];
  84946. quat.vmult(wc, wc);
  84947. pos.vadd(wc, wc);
  84948. max.copy(wc);
  84949. min.copy(wc);
  84950. for(var i=1; i<8; i++){
  84951. var wc = worldCornersTemp[i];
  84952. quat.vmult(wc, wc);
  84953. pos.vadd(wc, wc);
  84954. var x = wc.x;
  84955. var y = wc.y;
  84956. var z = wc.z;
  84957. if(x > max.x){
  84958. max.x = x;
  84959. }
  84960. if(y > max.y){
  84961. max.y = y;
  84962. }
  84963. if(z > max.z){
  84964. max.z = z;
  84965. }
  84966. if(x < min.x){
  84967. min.x = x;
  84968. }
  84969. if(y < min.y){
  84970. min.y = y;
  84971. }
  84972. if(z < min.z){
  84973. min.z = z;
  84974. }
  84975. }
  84976. // Get each axis max
  84977. // min.set(Infinity,Infinity,Infinity);
  84978. // max.set(-Infinity,-Infinity,-Infinity);
  84979. // this.forEachWorldCorner(pos,quat,function(x,y,z){
  84980. // if(x > max.x){
  84981. // max.x = x;
  84982. // }
  84983. // if(y > max.y){
  84984. // max.y = y;
  84985. // }
  84986. // if(z > max.z){
  84987. // max.z = z;
  84988. // }
  84989. // if(x < min.x){
  84990. // min.x = x;
  84991. // }
  84992. // if(y < min.y){
  84993. // min.y = y;
  84994. // }
  84995. // if(z < min.z){
  84996. // min.z = z;
  84997. // }
  84998. // });
  84999. };
  85000. },{"../math/Vec3":30,"./ConvexPolyhedron":38,"./Shape":43}],38:[function(_dereq_,module,exports){
  85001. module.exports = ConvexPolyhedron;
  85002. var Shape = _dereq_('./Shape');
  85003. var Vec3 = _dereq_('../math/Vec3');
  85004. var Quaternion = _dereq_('../math/Quaternion');
  85005. var Transform = _dereq_('../math/Transform');
  85006. /**
  85007. * A set of polygons describing a convex shape.
  85008. * @class ConvexPolyhedron
  85009. * @constructor
  85010. * @extends Shape
  85011. * @description The shape MUST be convex for the code to work properly. No polygons may be coplanar (contained
  85012. * in the same 3D plane), instead these should be merged into one polygon.
  85013. *
  85014. * @param {array} points An array of Vec3's
  85015. * @param {array} faces Array of integer arrays, describing which vertices that is included in each face.
  85016. *
  85017. * @author qiao / https://github.com/qiao (original author, see https://github.com/qiao/three.js/commit/85026f0c769e4000148a67d45a9e9b9c5108836f)
  85018. * @author schteppe / https://github.com/schteppe
  85019. * @see http://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/
  85020. * @see http://bullet.googlecode.com/svn/trunk/src/BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.cpp
  85021. *
  85022. * @todo Move the clipping functions to ContactGenerator?
  85023. * @todo Automatically merge coplanar polygons in constructor.
  85024. */
  85025. function ConvexPolyhedron(points, faces, uniqueAxes) {
  85026. var that = this;
  85027. Shape.call(this);
  85028. this.type = Shape.types.CONVEXPOLYHEDRON;
  85029. /**
  85030. * Array of Vec3
  85031. * @property vertices
  85032. * @type {Array}
  85033. */
  85034. this.vertices = points||[];
  85035. this.worldVertices = []; // World transformed version of .vertices
  85036. this.worldVerticesNeedsUpdate = true;
  85037. /**
  85038. * Array of integer arrays, indicating which vertices each face consists of
  85039. * @property faces
  85040. * @type {Array}
  85041. */
  85042. this.faces = faces||[];
  85043. /**
  85044. * Array of Vec3
  85045. * @property faceNormals
  85046. * @type {Array}
  85047. */
  85048. this.faceNormals = [];
  85049. this.computeNormals();
  85050. this.worldFaceNormalsNeedsUpdate = true;
  85051. this.worldFaceNormals = []; // World transformed version of .faceNormals
  85052. /**
  85053. * Array of Vec3
  85054. * @property uniqueEdges
  85055. * @type {Array}
  85056. */
  85057. this.uniqueEdges = [];
  85058. /**
  85059. * If given, these locally defined, normalized axes are the only ones being checked when doing separating axis check.
  85060. * @property {Array} uniqueAxes
  85061. */
  85062. this.uniqueAxes = uniqueAxes ? uniqueAxes.slice() : null;
  85063. this.computeEdges();
  85064. this.updateBoundingSphereRadius();
  85065. }
  85066. ConvexPolyhedron.prototype = new Shape();
  85067. ConvexPolyhedron.prototype.constructor = ConvexPolyhedron;
  85068. var computeEdges_tmpEdge = new Vec3();
  85069. /**
  85070. * Computes uniqueEdges
  85071. * @method computeEdges
  85072. */
  85073. ConvexPolyhedron.prototype.computeEdges = function(){
  85074. var faces = this.faces;
  85075. var vertices = this.vertices;
  85076. var nv = vertices.length;
  85077. var edges = this.uniqueEdges;
  85078. edges.length = 0;
  85079. var edge = computeEdges_tmpEdge;
  85080. for(var i=0; i !== faces.length; i++){
  85081. var face = faces[i];
  85082. var numVertices = face.length;
  85083. for(var j = 0; j !== numVertices; j++){
  85084. var k = ( j+1 ) % numVertices;
  85085. vertices[face[j]].vsub(vertices[face[k]], edge);
  85086. edge.normalize();
  85087. var found = false;
  85088. for(var p=0; p !== edges.length; p++){
  85089. if (edges[p].almostEquals(edge) || edges[p].almostEquals(edge)){
  85090. found = true;
  85091. break;
  85092. }
  85093. }
  85094. if (!found){
  85095. edges.push(edge.clone());
  85096. }
  85097. }
  85098. }
  85099. };
  85100. /**
  85101. * Compute the normals of the faces. Will reuse existing Vec3 objects in the .faceNormals array if they exist.
  85102. * @method computeNormals
  85103. */
  85104. ConvexPolyhedron.prototype.computeNormals = function(){
  85105. this.faceNormals.length = this.faces.length;
  85106. // Generate normals
  85107. for(var i=0; i<this.faces.length; i++){
  85108. // Check so all vertices exists for this face
  85109. for(var j=0; j<this.faces[i].length; j++){
  85110. if(!this.vertices[this.faces[i][j]]){
  85111. throw new Error("Vertex "+this.faces[i][j]+" not found!");
  85112. }
  85113. }
  85114. var n = this.faceNormals[i] || new Vec3();
  85115. this.getFaceNormal(i,n);
  85116. n.negate(n);
  85117. this.faceNormals[i] = n;
  85118. var vertex = this.vertices[this.faces[i][0]];
  85119. if(n.dot(vertex) < 0){
  85120. console.error(".faceNormals[" + i + "] = Vec3("+n.toString()+") looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right hand rule.");
  85121. for(var j=0; j<this.faces[i].length; j++){
  85122. console.warn(".vertices["+this.faces[i][j]+"] = Vec3("+this.vertices[this.faces[i][j]].toString()+")");
  85123. }
  85124. }
  85125. }
  85126. };
  85127. /**
  85128. * Get face normal given 3 vertices
  85129. * @static
  85130. * @method getFaceNormal
  85131. * @param {Vec3} va
  85132. * @param {Vec3} vb
  85133. * @param {Vec3} vc
  85134. * @param {Vec3} target
  85135. */
  85136. var cb = new Vec3();
  85137. var ab = new Vec3();
  85138. ConvexPolyhedron.computeNormal = function ( va, vb, vc, target ) {
  85139. vb.vsub(va,ab);
  85140. vc.vsub(vb,cb);
  85141. cb.cross(ab,target);
  85142. if ( !target.isZero() ) {
  85143. target.normalize();
  85144. }
  85145. };
  85146. /**
  85147. * Compute the normal of a face from its vertices
  85148. * @method getFaceNormal
  85149. * @param {Number} i
  85150. * @param {Vec3} target
  85151. */
  85152. ConvexPolyhedron.prototype.getFaceNormal = function(i,target){
  85153. var f = this.faces[i];
  85154. var va = this.vertices[f[0]];
  85155. var vb = this.vertices[f[1]];
  85156. var vc = this.vertices[f[2]];
  85157. return ConvexPolyhedron.computeNormal(va,vb,vc,target);
  85158. };
  85159. /**
  85160. * @method clipAgainstHull
  85161. * @param {Vec3} posA
  85162. * @param {Quaternion} quatA
  85163. * @param {ConvexPolyhedron} hullB
  85164. * @param {Vec3} posB
  85165. * @param {Quaternion} quatB
  85166. * @param {Vec3} separatingNormal
  85167. * @param {Number} minDist Clamp distance
  85168. * @param {Number} maxDist
  85169. * @param {array} result The an array of contact point objects, see clipFaceAgainstHull
  85170. * @see http://bullet.googlecode.com/svn/trunk/src/BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.cpp
  85171. */
  85172. var cah_WorldNormal = new Vec3();
  85173. ConvexPolyhedron.prototype.clipAgainstHull = function(posA,quatA,hullB,posB,quatB,separatingNormal,minDist,maxDist,result){
  85174. var WorldNormal = cah_WorldNormal;
  85175. var hullA = this;
  85176. var curMaxDist = maxDist;
  85177. var closestFaceB = -1;
  85178. var dmax = -Number.MAX_VALUE;
  85179. for(var face=0; face < hullB.faces.length; face++){
  85180. WorldNormal.copy(hullB.faceNormals[face]);
  85181. quatB.vmult(WorldNormal,WorldNormal);
  85182. //posB.vadd(WorldNormal,WorldNormal);
  85183. var d = WorldNormal.dot(separatingNormal);
  85184. if (d > dmax){
  85185. dmax = d;
  85186. closestFaceB = face;
  85187. }
  85188. }
  85189. var worldVertsB1 = [];
  85190. var polyB = hullB.faces[closestFaceB];
  85191. var numVertices = polyB.length;
  85192. for(var e0=0; e0<numVertices; e0++){
  85193. var b = hullB.vertices[polyB[e0]];
  85194. var worldb = new Vec3();
  85195. worldb.copy(b);
  85196. quatB.vmult(worldb,worldb);
  85197. posB.vadd(worldb,worldb);
  85198. worldVertsB1.push(worldb);
  85199. }
  85200. if (closestFaceB>=0){
  85201. this.clipFaceAgainstHull(separatingNormal,
  85202. posA,
  85203. quatA,
  85204. worldVertsB1,
  85205. minDist,
  85206. maxDist,
  85207. result);
  85208. }
  85209. };
  85210. /**
  85211. * Find the separating axis between this hull and another
  85212. * @method findSeparatingAxis
  85213. * @param {ConvexPolyhedron} hullB
  85214. * @param {Vec3} posA
  85215. * @param {Quaternion} quatA
  85216. * @param {Vec3} posB
  85217. * @param {Quaternion} quatB
  85218. * @param {Vec3} target The target vector to save the axis in
  85219. * @return {bool} Returns false if a separation is found, else true
  85220. */
  85221. var fsa_faceANormalWS3 = new Vec3(),
  85222. fsa_Worldnormal1 = new Vec3(),
  85223. fsa_deltaC = new Vec3(),
  85224. fsa_worldEdge0 = new Vec3(),
  85225. fsa_worldEdge1 = new Vec3(),
  85226. fsa_Cross = new Vec3();
  85227. ConvexPolyhedron.prototype.findSeparatingAxis = function(hullB,posA,quatA,posB,quatB,target, faceListA, faceListB){
  85228. var faceANormalWS3 = fsa_faceANormalWS3,
  85229. Worldnormal1 = fsa_Worldnormal1,
  85230. deltaC = fsa_deltaC,
  85231. worldEdge0 = fsa_worldEdge0,
  85232. worldEdge1 = fsa_worldEdge1,
  85233. Cross = fsa_Cross;
  85234. var dmin = Number.MAX_VALUE;
  85235. var hullA = this;
  85236. var curPlaneTests=0;
  85237. if(!hullA.uniqueAxes){
  85238. var numFacesA = faceListA ? faceListA.length : hullA.faces.length;
  85239. // Test face normals from hullA
  85240. for(var i=0; i<numFacesA; i++){
  85241. var fi = faceListA ? faceListA[i] : i;
  85242. // Get world face normal
  85243. faceANormalWS3.copy(hullA.faceNormals[fi]);
  85244. quatA.vmult(faceANormalWS3,faceANormalWS3);
  85245. var d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
  85246. if(d===false){
  85247. return false;
  85248. }
  85249. if(d<dmin){
  85250. dmin = d;
  85251. target.copy(faceANormalWS3);
  85252. }
  85253. }
  85254. } else {
  85255. // Test unique axes
  85256. for(var i = 0; i !== hullA.uniqueAxes.length; i++){
  85257. // Get world axis
  85258. quatA.vmult(hullA.uniqueAxes[i],faceANormalWS3);
  85259. var d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
  85260. if(d===false){
  85261. return false;
  85262. }
  85263. if(d<dmin){
  85264. dmin = d;
  85265. target.copy(faceANormalWS3);
  85266. }
  85267. }
  85268. }
  85269. if(!hullB.uniqueAxes){
  85270. // Test face normals from hullB
  85271. var numFacesB = faceListB ? faceListB.length : hullB.faces.length;
  85272. for(var i=0;i<numFacesB;i++){
  85273. var fi = faceListB ? faceListB[i] : i;
  85274. Worldnormal1.copy(hullB.faceNormals[fi]);
  85275. quatB.vmult(Worldnormal1,Worldnormal1);
  85276. curPlaneTests++;
  85277. var d = hullA.testSepAxis(Worldnormal1, hullB,posA,quatA,posB,quatB);
  85278. if(d===false){
  85279. return false;
  85280. }
  85281. if(d<dmin){
  85282. dmin = d;
  85283. target.copy(Worldnormal1);
  85284. }
  85285. }
  85286. } else {
  85287. // Test unique axes in B
  85288. for(var i = 0; i !== hullB.uniqueAxes.length; i++){
  85289. quatB.vmult(hullB.uniqueAxes[i],Worldnormal1);
  85290. curPlaneTests++;
  85291. var d = hullA.testSepAxis(Worldnormal1, hullB,posA,quatA,posB,quatB);
  85292. if(d===false){
  85293. return false;
  85294. }
  85295. if(d<dmin){
  85296. dmin = d;
  85297. target.copy(Worldnormal1);
  85298. }
  85299. }
  85300. }
  85301. // Test edges
  85302. for(var e0=0; e0 !== hullA.uniqueEdges.length; e0++){
  85303. // Get world edge
  85304. quatA.vmult(hullA.uniqueEdges[e0],worldEdge0);
  85305. for(var e1=0; e1 !== hullB.uniqueEdges.length; e1++){
  85306. // Get world edge 2
  85307. quatB.vmult(hullB.uniqueEdges[e1], worldEdge1);
  85308. worldEdge0.cross(worldEdge1,Cross);
  85309. if(!Cross.almostZero()){
  85310. Cross.normalize();
  85311. var dist = hullA.testSepAxis(Cross, hullB, posA, quatA, posB, quatB);
  85312. if(dist === false){
  85313. return false;
  85314. }
  85315. if(dist < dmin){
  85316. dmin = dist;
  85317. target.copy(Cross);
  85318. }
  85319. }
  85320. }
  85321. }
  85322. posB.vsub(posA,deltaC);
  85323. if((deltaC.dot(target))>0.0){
  85324. target.negate(target);
  85325. }
  85326. return true;
  85327. };
  85328. var maxminA=[], maxminB=[];
  85329. /**
  85330. * Test separating axis against two hulls. Both hulls are projected onto the axis and the overlap size is returned if there is one.
  85331. * @method testSepAxis
  85332. * @param {Vec3} axis
  85333. * @param {ConvexPolyhedron} hullB
  85334. * @param {Vec3} posA
  85335. * @param {Quaternion} quatA
  85336. * @param {Vec3} posB
  85337. * @param {Quaternion} quatB
  85338. * @return {number} The overlap depth, or FALSE if no penetration.
  85339. */
  85340. ConvexPolyhedron.prototype.testSepAxis = function(axis, hullB, posA, quatA, posB, quatB){
  85341. var hullA=this;
  85342. ConvexPolyhedron.project(hullA, axis, posA, quatA, maxminA);
  85343. ConvexPolyhedron.project(hullB, axis, posB, quatB, maxminB);
  85344. var maxA = maxminA[0];
  85345. var minA = maxminA[1];
  85346. var maxB = maxminB[0];
  85347. var minB = maxminB[1];
  85348. if(maxA<minB || maxB<minA){
  85349. return false; // Separated
  85350. }
  85351. var d0 = maxA - minB;
  85352. var d1 = maxB - minA;
  85353. var depth = d0<d1 ? d0:d1;
  85354. return depth;
  85355. };
  85356. var cli_aabbmin = new Vec3(),
  85357. cli_aabbmax = new Vec3();
  85358. /**
  85359. * @method calculateLocalInertia
  85360. * @param {Number} mass
  85361. * @param {Vec3} target
  85362. */
  85363. ConvexPolyhedron.prototype.calculateLocalInertia = function(mass,target){
  85364. // Approximate with box inertia
  85365. // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
  85366. this.computeLocalAABB(cli_aabbmin,cli_aabbmax);
  85367. var x = cli_aabbmax.x - cli_aabbmin.x,
  85368. y = cli_aabbmax.y - cli_aabbmin.y,
  85369. z = cli_aabbmax.z - cli_aabbmin.z;
  85370. target.x = 1.0 / 12.0 * mass * ( 2*y*2*y + 2*z*2*z );
  85371. target.y = 1.0 / 12.0 * mass * ( 2*x*2*x + 2*z*2*z );
  85372. target.z = 1.0 / 12.0 * mass * ( 2*y*2*y + 2*x*2*x );
  85373. };
  85374. /**
  85375. * @method getPlaneConstantOfFace
  85376. * @param {Number} face_i Index of the face
  85377. * @return {Number}
  85378. */
  85379. ConvexPolyhedron.prototype.getPlaneConstantOfFace = function(face_i){
  85380. var f = this.faces[face_i];
  85381. var n = this.faceNormals[face_i];
  85382. var v = this.vertices[f[0]];
  85383. var c = -n.dot(v);
  85384. return c;
  85385. };
  85386. /**
  85387. * Clip a face against a hull.
  85388. * @method clipFaceAgainstHull
  85389. * @param {Vec3} separatingNormal
  85390. * @param {Vec3} posA
  85391. * @param {Quaternion} quatA
  85392. * @param {Array} worldVertsB1 An array of Vec3 with vertices in the world frame.
  85393. * @param {Number} minDist Distance clamping
  85394. * @param {Number} maxDist
  85395. * @param Array result Array to store resulting contact points in. Will be objects with properties: point, depth, normal. These are represented in world coordinates.
  85396. */
  85397. var cfah_faceANormalWS = new Vec3(),
  85398. cfah_edge0 = new Vec3(),
  85399. cfah_WorldEdge0 = new Vec3(),
  85400. cfah_worldPlaneAnormal1 = new Vec3(),
  85401. cfah_planeNormalWS1 = new Vec3(),
  85402. cfah_worldA1 = new Vec3(),
  85403. cfah_localPlaneNormal = new Vec3(),
  85404. cfah_planeNormalWS = new Vec3();
  85405. ConvexPolyhedron.prototype.clipFaceAgainstHull = function(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist,result){
  85406. var faceANormalWS = cfah_faceANormalWS,
  85407. edge0 = cfah_edge0,
  85408. WorldEdge0 = cfah_WorldEdge0,
  85409. worldPlaneAnormal1 = cfah_worldPlaneAnormal1,
  85410. planeNormalWS1 = cfah_planeNormalWS1,
  85411. worldA1 = cfah_worldA1,
  85412. localPlaneNormal = cfah_localPlaneNormal,
  85413. planeNormalWS = cfah_planeNormalWS;
  85414. var hullA = this;
  85415. var worldVertsB2 = [];
  85416. var pVtxIn = worldVertsB1;
  85417. var pVtxOut = worldVertsB2;
  85418. // Find the face with normal closest to the separating axis
  85419. var closestFaceA = -1;
  85420. var dmin = Number.MAX_VALUE;
  85421. for(var face=0; face<hullA.faces.length; face++){
  85422. faceANormalWS.copy(hullA.faceNormals[face]);
  85423. quatA.vmult(faceANormalWS,faceANormalWS);
  85424. //posA.vadd(faceANormalWS,faceANormalWS);
  85425. var d = faceANormalWS.dot(separatingNormal);
  85426. if (d < dmin){
  85427. dmin = d;
  85428. closestFaceA = face;
  85429. }
  85430. }
  85431. if (closestFaceA < 0){
  85432. // console.log("--- did not find any closest face... ---");
  85433. return;
  85434. }
  85435. //console.log("closest A: ",closestFaceA);
  85436. // Get the face and construct connected faces
  85437. var polyA = hullA.faces[closestFaceA];
  85438. polyA.connectedFaces = [];
  85439. for(var i=0; i<hullA.faces.length; i++){
  85440. for(var j=0; j<hullA.faces[i].length; j++){
  85441. if(polyA.indexOf(hullA.faces[i][j])!==-1 /* Sharing a vertex*/ && i!==closestFaceA /* Not the one we are looking for connections from */ && polyA.connectedFaces.indexOf(i)===-1 /* Not already added */ ){
  85442. polyA.connectedFaces.push(i);
  85443. }
  85444. }
  85445. }
  85446. // Clip the polygon to the back of the planes of all faces of hull A, that are adjacent to the witness face
  85447. var numContacts = pVtxIn.length;
  85448. var numVerticesA = polyA.length;
  85449. var res = [];
  85450. for(var e0=0; e0<numVerticesA; e0++){
  85451. var a = hullA.vertices[polyA[e0]];
  85452. var b = hullA.vertices[polyA[(e0+1)%numVerticesA]];
  85453. a.vsub(b,edge0);
  85454. WorldEdge0.copy(edge0);
  85455. quatA.vmult(WorldEdge0,WorldEdge0);
  85456. posA.vadd(WorldEdge0,WorldEdge0);
  85457. worldPlaneAnormal1.copy(this.faceNormals[closestFaceA]);//transA.getBasis()* btVector3(polyA.m_plane[0],polyA.m_plane[1],polyA.m_plane[2]);
  85458. quatA.vmult(worldPlaneAnormal1,worldPlaneAnormal1);
  85459. posA.vadd(worldPlaneAnormal1,worldPlaneAnormal1);
  85460. WorldEdge0.cross(worldPlaneAnormal1,planeNormalWS1);
  85461. planeNormalWS1.negate(planeNormalWS1);
  85462. worldA1.copy(a);
  85463. quatA.vmult(worldA1,worldA1);
  85464. posA.vadd(worldA1,worldA1);
  85465. var planeEqWS1 = -worldA1.dot(planeNormalWS1);
  85466. var planeEqWS;
  85467. if(true){
  85468. var otherFace = polyA.connectedFaces[e0];
  85469. localPlaneNormal.copy(this.faceNormals[otherFace]);
  85470. var localPlaneEq = this.getPlaneConstantOfFace(otherFace);
  85471. planeNormalWS.copy(localPlaneNormal);
  85472. quatA.vmult(planeNormalWS,planeNormalWS);
  85473. //posA.vadd(planeNormalWS,planeNormalWS);
  85474. var planeEqWS = localPlaneEq - planeNormalWS.dot(posA);
  85475. } else {
  85476. planeNormalWS.copy(planeNormalWS1);
  85477. planeEqWS = planeEqWS1;
  85478. }
  85479. // Clip face against our constructed plane
  85480. this.clipFaceAgainstPlane(pVtxIn, pVtxOut, planeNormalWS, planeEqWS);
  85481. // Throw away all clipped points, but save the reamining until next clip
  85482. while(pVtxIn.length){
  85483. pVtxIn.shift();
  85484. }
  85485. while(pVtxOut.length){
  85486. pVtxIn.push(pVtxOut.shift());
  85487. }
  85488. }
  85489. //console.log("Resulting points after clip:",pVtxIn);
  85490. // only keep contact points that are behind the witness face
  85491. localPlaneNormal.copy(this.faceNormals[closestFaceA]);
  85492. var localPlaneEq = this.getPlaneConstantOfFace(closestFaceA);
  85493. planeNormalWS.copy(localPlaneNormal);
  85494. quatA.vmult(planeNormalWS,planeNormalWS);
  85495. var planeEqWS = localPlaneEq - planeNormalWS.dot(posA);
  85496. for (var i=0; i<pVtxIn.length; i++){
  85497. var depth = planeNormalWS.dot(pVtxIn[i]) + planeEqWS; //???
  85498. /*console.log("depth calc from normal=",planeNormalWS.toString()," and constant "+planeEqWS+" and vertex ",pVtxIn[i].toString()," gives "+depth);*/
  85499. if (depth <=minDist){
  85500. console.log("clamped: depth="+depth+" to minDist="+(minDist+""));
  85501. depth = minDist;
  85502. }
  85503. if (depth <=maxDist){
  85504. var point = pVtxIn[i];
  85505. if(depth<=0){
  85506. /*console.log("Got contact point ",point.toString(),
  85507. ", depth=",depth,
  85508. "contact normal=",separatingNormal.toString(),
  85509. "plane",planeNormalWS.toString(),
  85510. "planeConstant",planeEqWS);*/
  85511. var p = {
  85512. point:point,
  85513. normal:planeNormalWS,
  85514. depth: depth,
  85515. };
  85516. result.push(p);
  85517. }
  85518. }
  85519. }
  85520. };
  85521. /**
  85522. * Clip a face in a hull against the back of a plane.
  85523. * @method clipFaceAgainstPlane
  85524. * @param {Array} inVertices
  85525. * @param {Array} outVertices
  85526. * @param {Vec3} planeNormal
  85527. * @param {Number} planeConstant The constant in the mathematical plane equation
  85528. */
  85529. ConvexPolyhedron.prototype.clipFaceAgainstPlane = function(inVertices,outVertices, planeNormal, planeConstant){
  85530. var n_dot_first, n_dot_last;
  85531. var numVerts = inVertices.length;
  85532. if(numVerts < 2){
  85533. return outVertices;
  85534. }
  85535. var firstVertex = inVertices[inVertices.length-1],
  85536. lastVertex = inVertices[0];
  85537. n_dot_first = planeNormal.dot(firstVertex) + planeConstant;
  85538. for(var vi = 0; vi < numVerts; vi++){
  85539. lastVertex = inVertices[vi];
  85540. n_dot_last = planeNormal.dot(lastVertex) + planeConstant;
  85541. if(n_dot_first < 0){
  85542. if(n_dot_last < 0){
  85543. // Start < 0, end < 0, so output lastVertex
  85544. var newv = new Vec3();
  85545. newv.copy(lastVertex);
  85546. outVertices.push(newv);
  85547. } else {
  85548. // Start < 0, end >= 0, so output intersection
  85549. var newv = new Vec3();
  85550. firstVertex.lerp(lastVertex,
  85551. n_dot_first / (n_dot_first - n_dot_last),
  85552. newv);
  85553. outVertices.push(newv);
  85554. }
  85555. } else {
  85556. if(n_dot_last<0){
  85557. // Start >= 0, end < 0 so output intersection and end
  85558. var newv = new Vec3();
  85559. firstVertex.lerp(lastVertex,
  85560. n_dot_first / (n_dot_first - n_dot_last),
  85561. newv);
  85562. outVertices.push(newv);
  85563. outVertices.push(lastVertex);
  85564. }
  85565. }
  85566. firstVertex = lastVertex;
  85567. n_dot_first = n_dot_last;
  85568. }
  85569. return outVertices;
  85570. };
  85571. // Updates .worldVertices and sets .worldVerticesNeedsUpdate to false.
  85572. ConvexPolyhedron.prototype.computeWorldVertices = function(position,quat){
  85573. var N = this.vertices.length;
  85574. while(this.worldVertices.length < N){
  85575. this.worldVertices.push( new Vec3() );
  85576. }
  85577. var verts = this.vertices,
  85578. worldVerts = this.worldVertices;
  85579. for(var i=0; i!==N; i++){
  85580. quat.vmult( verts[i] , worldVerts[i] );
  85581. position.vadd( worldVerts[i] , worldVerts[i] );
  85582. }
  85583. this.worldVerticesNeedsUpdate = false;
  85584. };
  85585. var computeLocalAABB_worldVert = new Vec3();
  85586. ConvexPolyhedron.prototype.computeLocalAABB = function(aabbmin,aabbmax){
  85587. var n = this.vertices.length,
  85588. vertices = this.vertices,
  85589. worldVert = computeLocalAABB_worldVert;
  85590. aabbmin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  85591. aabbmax.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  85592. for(var i=0; i<n; i++){
  85593. var v = vertices[i];
  85594. if (v.x < aabbmin.x){
  85595. aabbmin.x = v.x;
  85596. } else if(v.x > aabbmax.x){
  85597. aabbmax.x = v.x;
  85598. }
  85599. if (v.y < aabbmin.y){
  85600. aabbmin.y = v.y;
  85601. } else if(v.y > aabbmax.y){
  85602. aabbmax.y = v.y;
  85603. }
  85604. if (v.z < aabbmin.z){
  85605. aabbmin.z = v.z;
  85606. } else if(v.z > aabbmax.z){
  85607. aabbmax.z = v.z;
  85608. }
  85609. }
  85610. };
  85611. /**
  85612. * Updates .worldVertices and sets .worldVerticesNeedsUpdate to false.
  85613. * @method computeWorldFaceNormals
  85614. * @param {Quaternion} quat
  85615. */
  85616. ConvexPolyhedron.prototype.computeWorldFaceNormals = function(quat){
  85617. var N = this.faceNormals.length;
  85618. while(this.worldFaceNormals.length < N){
  85619. this.worldFaceNormals.push( new Vec3() );
  85620. }
  85621. var normals = this.faceNormals,
  85622. worldNormals = this.worldFaceNormals;
  85623. for(var i=0; i!==N; i++){
  85624. quat.vmult( normals[i] , worldNormals[i] );
  85625. }
  85626. this.worldFaceNormalsNeedsUpdate = false;
  85627. };
  85628. /**
  85629. * @method updateBoundingSphereRadius
  85630. */
  85631. ConvexPolyhedron.prototype.updateBoundingSphereRadius = function(){
  85632. // Assume points are distributed with local (0,0,0) as center
  85633. var max2 = 0;
  85634. var verts = this.vertices;
  85635. for(var i=0, N=verts.length; i!==N; i++) {
  85636. var norm2 = verts[i].norm2();
  85637. if(norm2 > max2){
  85638. max2 = norm2;
  85639. }
  85640. }
  85641. this.boundingSphereRadius = Math.sqrt(max2);
  85642. };
  85643. var tempWorldVertex = new Vec3();
  85644. /**
  85645. * @method calculateWorldAABB
  85646. * @param {Vec3} pos
  85647. * @param {Quaternion} quat
  85648. * @param {Vec3} min
  85649. * @param {Vec3} max
  85650. */
  85651. ConvexPolyhedron.prototype.calculateWorldAABB = function(pos,quat,min,max){
  85652. var n = this.vertices.length, verts = this.vertices;
  85653. var minx,miny,minz,maxx,maxy,maxz;
  85654. for(var i=0; i<n; i++){
  85655. tempWorldVertex.copy(verts[i]);
  85656. quat.vmult(tempWorldVertex,tempWorldVertex);
  85657. pos.vadd(tempWorldVertex,tempWorldVertex);
  85658. var v = tempWorldVertex;
  85659. if (v.x < minx || minx===undefined){
  85660. minx = v.x;
  85661. } else if(v.x > maxx || maxx===undefined){
  85662. maxx = v.x;
  85663. }
  85664. if (v.y < miny || miny===undefined){
  85665. miny = v.y;
  85666. } else if(v.y > maxy || maxy===undefined){
  85667. maxy = v.y;
  85668. }
  85669. if (v.z < minz || minz===undefined){
  85670. minz = v.z;
  85671. } else if(v.z > maxz || maxz===undefined){
  85672. maxz = v.z;
  85673. }
  85674. }
  85675. min.set(minx,miny,minz);
  85676. max.set(maxx,maxy,maxz);
  85677. };
  85678. /**
  85679. * Get approximate convex volume
  85680. * @method volume
  85681. * @return {Number}
  85682. */
  85683. ConvexPolyhedron.prototype.volume = function(){
  85684. return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  85685. };
  85686. /**
  85687. * Get an average of all the vertices positions
  85688. * @method getAveragePointLocal
  85689. * @param {Vec3} target
  85690. * @return {Vec3}
  85691. */
  85692. ConvexPolyhedron.prototype.getAveragePointLocal = function(target){
  85693. target = target || new Vec3();
  85694. var n = this.vertices.length,
  85695. verts = this.vertices;
  85696. for(var i=0; i<n; i++){
  85697. target.vadd(verts[i],target);
  85698. }
  85699. target.mult(1/n,target);
  85700. return target;
  85701. };
  85702. /**
  85703. * Transform all local points. Will change the .vertices
  85704. * @method transformAllPoints
  85705. * @param {Vec3} offset
  85706. * @param {Quaternion} quat
  85707. */
  85708. ConvexPolyhedron.prototype.transformAllPoints = function(offset,quat){
  85709. var n = this.vertices.length,
  85710. verts = this.vertices;
  85711. // Apply rotation
  85712. if(quat){
  85713. // Rotate vertices
  85714. for(var i=0; i<n; i++){
  85715. var v = verts[i];
  85716. quat.vmult(v,v);
  85717. }
  85718. // Rotate face normals
  85719. for(var i=0; i<this.faceNormals.length; i++){
  85720. var v = this.faceNormals[i];
  85721. quat.vmult(v,v);
  85722. }
  85723. /*
  85724. // Rotate edges
  85725. for(var i=0; i<this.uniqueEdges.length; i++){
  85726. var v = this.uniqueEdges[i];
  85727. quat.vmult(v,v);
  85728. }*/
  85729. }
  85730. // Apply offset
  85731. if(offset){
  85732. for(var i=0; i<n; i++){
  85733. var v = verts[i];
  85734. v.vadd(offset,v);
  85735. }
  85736. }
  85737. };
  85738. /**
  85739. * Checks whether p is inside the polyhedra. Must be in local coords. The point lies outside of the convex hull of the other points if and only if the direction of all the vectors from it to those other points are on less than one half of a sphere around it.
  85740. * @method pointIsInside
  85741. * @param {Vec3} p A point given in local coordinates
  85742. * @return {Boolean}
  85743. */
  85744. var ConvexPolyhedron_pointIsInside = new Vec3();
  85745. var ConvexPolyhedron_vToP = new Vec3();
  85746. var ConvexPolyhedron_vToPointInside = new Vec3();
  85747. ConvexPolyhedron.prototype.pointIsInside = function(p){
  85748. var n = this.vertices.length,
  85749. verts = this.vertices,
  85750. faces = this.faces,
  85751. normals = this.faceNormals;
  85752. var positiveResult = null;
  85753. var N = this.faces.length;
  85754. var pointInside = ConvexPolyhedron_pointIsInside;
  85755. this.getAveragePointLocal(pointInside);
  85756. for(var i=0; i<N; i++){
  85757. var numVertices = this.faces[i].length;
  85758. var n = normals[i];
  85759. var v = verts[faces[i][0]]; // We only need one point in the face
  85760. // This dot product determines which side of the edge the point is
  85761. var vToP = ConvexPolyhedron_vToP;
  85762. p.vsub(v,vToP);
  85763. var r1 = n.dot(vToP);
  85764. var vToPointInside = ConvexPolyhedron_vToPointInside;
  85765. pointInside.vsub(v,vToPointInside);
  85766. var r2 = n.dot(vToPointInside);
  85767. if((r1<0 && r2>0) || (r1>0 && r2<0)){
  85768. return false; // Encountered some other sign. Exit.
  85769. } else {
  85770. }
  85771. }
  85772. // If we got here, all dot products were of the same sign.
  85773. return positiveResult ? 1 : -1;
  85774. };
  85775. /**
  85776. * Get max and min dot product of a convex hull at position (pos,quat) projected onto an axis. Results are saved in the array maxmin.
  85777. * @static
  85778. * @method project
  85779. * @param {ConvexPolyhedron} hull
  85780. * @param {Vec3} axis
  85781. * @param {Vec3} pos
  85782. * @param {Quaternion} quat
  85783. * @param {array} result result[0] and result[1] will be set to maximum and minimum, respectively.
  85784. */
  85785. var project_worldVertex = new Vec3();
  85786. var project_localAxis = new Vec3();
  85787. var project_localOrigin = new Vec3();
  85788. ConvexPolyhedron.project = function(hull, axis, pos, quat, result){
  85789. var n = hull.vertices.length,
  85790. worldVertex = project_worldVertex,
  85791. localAxis = project_localAxis,
  85792. max = 0,
  85793. min = 0,
  85794. localOrigin = project_localOrigin,
  85795. vs = hull.vertices;
  85796. localOrigin.setZero();
  85797. // Transform the axis to local
  85798. Transform.vectorToLocalFrame(pos, quat, axis, localAxis);
  85799. Transform.pointToLocalFrame(pos, quat, localOrigin, localOrigin);
  85800. var add = localOrigin.dot(localAxis);
  85801. min = max = vs[0].dot(localAxis);
  85802. for(var i = 1; i < n; i++){
  85803. var val = vs[i].dot(localAxis);
  85804. if(val > max){
  85805. max = val;
  85806. }
  85807. if(val < min){
  85808. min = val;
  85809. }
  85810. }
  85811. min -= add;
  85812. max -= add;
  85813. if(min > max){
  85814. // Inconsistent - swap
  85815. var temp = min;
  85816. min = max;
  85817. max = temp;
  85818. }
  85819. // Output
  85820. result[0] = max;
  85821. result[1] = min;
  85822. };
  85823. },{"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"./Shape":43}],39:[function(_dereq_,module,exports){
  85824. module.exports = Cylinder;
  85825. var Shape = _dereq_('./Shape');
  85826. var Vec3 = _dereq_('../math/Vec3');
  85827. var Quaternion = _dereq_('../math/Quaternion');
  85828. var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');
  85829. /**
  85830. * @class Cylinder
  85831. * @constructor
  85832. * @extends ConvexPolyhedron
  85833. * @author schteppe / https://github.com/schteppe
  85834. * @param {Number} radiusTop
  85835. * @param {Number} radiusBottom
  85836. * @param {Number} height
  85837. * @param {Number} numSegments The number of segments to build the cylinder out of
  85838. */
  85839. function Cylinder( radiusTop, radiusBottom, height , numSegments ) {
  85840. var N = numSegments,
  85841. verts = [],
  85842. axes = [],
  85843. faces = [],
  85844. bottomface = [],
  85845. topface = [],
  85846. cos = Math.cos,
  85847. sin = Math.sin;
  85848. // First bottom point
  85849. verts.push(new Vec3(radiusBottom*cos(0),
  85850. radiusBottom*sin(0),
  85851. -height*0.5));
  85852. bottomface.push(0);
  85853. // First top point
  85854. verts.push(new Vec3(radiusTop*cos(0),
  85855. radiusTop*sin(0),
  85856. height*0.5));
  85857. topface.push(1);
  85858. for(var i=0; i<N; i++){
  85859. var theta = 2*Math.PI/N * (i+1);
  85860. var thetaN = 2*Math.PI/N * (i+0.5);
  85861. if(i<N-1){
  85862. // Bottom
  85863. verts.push(new Vec3(radiusBottom*cos(theta),
  85864. radiusBottom*sin(theta),
  85865. -height*0.5));
  85866. bottomface.push(2*i+2);
  85867. // Top
  85868. verts.push(new Vec3(radiusTop*cos(theta),
  85869. radiusTop*sin(theta),
  85870. height*0.5));
  85871. topface.push(2*i+3);
  85872. // Face
  85873. faces.push([2*i+2, 2*i+3, 2*i+1,2*i]);
  85874. } else {
  85875. faces.push([0,1, 2*i+1, 2*i]); // Connect
  85876. }
  85877. // Axis: we can cut off half of them if we have even number of segments
  85878. if(N % 2 === 1 || i < N / 2){
  85879. axes.push(new Vec3(cos(thetaN), sin(thetaN), 0));
  85880. }
  85881. }
  85882. faces.push(topface);
  85883. axes.push(new Vec3(0,0,1));
  85884. // Reorder bottom face
  85885. var temp = [];
  85886. for(var i=0; i<bottomface.length; i++){
  85887. temp.push(bottomface[bottomface.length - i - 1]);
  85888. }
  85889. faces.push(temp);
  85890. this.type = Shape.types.CONVEXPOLYHEDRON;
  85891. ConvexPolyhedron.call( this, verts, faces, axes );
  85892. }
  85893. Cylinder.prototype = new ConvexPolyhedron();
  85894. },{"../math/Quaternion":28,"../math/Vec3":30,"./ConvexPolyhedron":38,"./Shape":43}],40:[function(_dereq_,module,exports){
  85895. var Shape = _dereq_('./Shape');
  85896. var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');
  85897. var Vec3 = _dereq_('../math/Vec3');
  85898. var Utils = _dereq_('../utils/Utils');
  85899. module.exports = Heightfield;
  85900. /**
  85901. * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a given distance.
  85902. * @class Heightfield
  85903. * @extends Shape
  85904. * @constructor
  85905. * @param {Array} data An array of Y values that will be used to construct the terrain.
  85906. * @param {object} options
  85907. * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given.
  85908. * @param {Number} [options.maxValue] Maximum value.
  85909. * @param {Number} [options.elementSize=0.1] World spacing between the data points in X direction.
  85910. * @todo Should be possible to use along all axes, not just y
  85911. *
  85912. * @example
  85913. * // Generate some height data (y-values).
  85914. * var data = [];
  85915. * for(var i = 0; i < 1000; i++){
  85916. * var y = 0.5 * Math.cos(0.2 * i);
  85917. * data.push(y);
  85918. * }
  85919. *
  85920. * // Create the heightfield shape
  85921. * var heightfieldShape = new Heightfield(data, {
  85922. * elementSize: 1 // Distance between the data points in X and Y directions
  85923. * });
  85924. * var heightfieldBody = new Body();
  85925. * heightfieldBody.addShape(heightfieldShape);
  85926. * world.addBody(heightfieldBody);
  85927. */
  85928. function Heightfield(data, options){
  85929. options = Utils.defaults(options, {
  85930. maxValue : null,
  85931. minValue : null,
  85932. elementSize : 1
  85933. });
  85934. /**
  85935. * An array of numbers, or height values, that are spread out along the x axis.
  85936. * @property {array} data
  85937. */
  85938. this.data = data;
  85939. /**
  85940. * Max value of the data
  85941. * @property {number} maxValue
  85942. */
  85943. this.maxValue = options.maxValue;
  85944. /**
  85945. * Max value of the data
  85946. * @property {number} minValue
  85947. */
  85948. this.minValue = options.minValue;
  85949. /**
  85950. * The width of each element
  85951. * @property {number} elementSize
  85952. * @todo elementSizeX and Y
  85953. */
  85954. this.elementSize = options.elementSize;
  85955. if(options.minValue === null){
  85956. this.updateMinValue();
  85957. }
  85958. if(options.maxValue === null){
  85959. this.updateMaxValue();
  85960. }
  85961. this.cacheEnabled = true;
  85962. Shape.call(this);
  85963. this.pillarConvex = new ConvexPolyhedron();
  85964. this.pillarOffset = new Vec3();
  85965. this.type = Shape.types.HEIGHTFIELD;
  85966. this.updateBoundingSphereRadius();
  85967. // "i_j_isUpper" => { convex: ..., offset: ... }
  85968. // for example:
  85969. // _cachedPillars["0_2_1"]
  85970. this._cachedPillars = {};
  85971. }
  85972. Heightfield.prototype = new Shape();
  85973. /**
  85974. * Call whenever you change the data array.
  85975. * @method update
  85976. */
  85977. Heightfield.prototype.update = function(){
  85978. this._cachedPillars = {};
  85979. };
  85980. /**
  85981. * Update the .minValue property
  85982. * @method updateMinValue
  85983. */
  85984. Heightfield.prototype.updateMinValue = function(){
  85985. var data = this.data;
  85986. var minValue = data[0][0];
  85987. for(var i=0; i !== data.length; i++){
  85988. for(var j=0; j !== data[i].length; j++){
  85989. var v = data[i][j];
  85990. if(v < minValue){
  85991. minValue = v;
  85992. }
  85993. }
  85994. }
  85995. this.minValue = minValue;
  85996. };
  85997. /**
  85998. * Update the .maxValue property
  85999. * @method updateMaxValue
  86000. */
  86001. Heightfield.prototype.updateMaxValue = function(){
  86002. var data = this.data;
  86003. var maxValue = data[0][0];
  86004. for(var i=0; i !== data.length; i++){
  86005. for(var j=0; j !== data[i].length; j++){
  86006. var v = data[i][j];
  86007. if(v > maxValue){
  86008. maxValue = v;
  86009. }
  86010. }
  86011. }
  86012. this.maxValue = maxValue;
  86013. };
  86014. /**
  86015. * Set the height value at an index. Don't forget to update maxValue and minValue after you're done.
  86016. * @method setHeightValueAtIndex
  86017. * @param {integer} xi
  86018. * @param {integer} yi
  86019. * @param {number} value
  86020. */
  86021. Heightfield.prototype.setHeightValueAtIndex = function(xi, yi, value){
  86022. var data = this.data;
  86023. data[xi][yi] = value;
  86024. // Invalidate cache
  86025. this.clearCachedConvexTrianglePillar(xi, yi, false);
  86026. if(xi > 0){
  86027. this.clearCachedConvexTrianglePillar(xi - 1, yi, true);
  86028. this.clearCachedConvexTrianglePillar(xi - 1, yi, false);
  86029. }
  86030. if(yi > 0){
  86031. this.clearCachedConvexTrianglePillar(xi, yi - 1, true);
  86032. this.clearCachedConvexTrianglePillar(xi, yi - 1, false);
  86033. }
  86034. if(yi > 0 && xi > 0){
  86035. this.clearCachedConvexTrianglePillar(xi - 1, yi - 1, true);
  86036. }
  86037. };
  86038. /**
  86039. * Get max/min in a rectangle in the matrix data
  86040. * @method getRectMinMax
  86041. * @param {integer} iMinX
  86042. * @param {integer} iMinY
  86043. * @param {integer} iMaxX
  86044. * @param {integer} iMaxY
  86045. * @param {array} [result] An array to store the results in.
  86046. * @return {array} The result array, if it was passed in. Minimum will be at position 0 and max at 1.
  86047. */
  86048. Heightfield.prototype.getRectMinMax = function (iMinX, iMinY, iMaxX, iMaxY, result) {
  86049. result = result || [];
  86050. // Get max and min of the data
  86051. var data = this.data,
  86052. max = this.minValue; // Set first value
  86053. for(var i = iMinX; i <= iMaxX; i++){
  86054. for(var j = iMinY; j <= iMaxY; j++){
  86055. var height = data[i][j];
  86056. if(height > max){
  86057. max = height;
  86058. }
  86059. }
  86060. }
  86061. result[0] = this.minValue;
  86062. result[1] = max;
  86063. };
  86064. /**
  86065. * Get the index of a local position on the heightfield. The indexes indicate the rectangles, so if your terrain is made of N x N height data points, you will have rectangle indexes ranging from 0 to N-1.
  86066. * @method getIndexOfPosition
  86067. * @param {number} x
  86068. * @param {number} y
  86069. * @param {array} result Two-element array
  86070. * @param {boolean} clamp If the position should be clamped to the heightfield edge.
  86071. * @return {boolean}
  86072. */
  86073. Heightfield.prototype.getIndexOfPosition = function (x, y, result, clamp) {
  86074. // Get the index of the data points to test against
  86075. var w = this.elementSize;
  86076. var data = this.data;
  86077. var xi = Math.floor(x / w);
  86078. var yi = Math.floor(y / w);
  86079. result[0] = xi;
  86080. result[1] = yi;
  86081. if(clamp){
  86082. // Clamp index to edges
  86083. if(xi < 0){ xi = 0; }
  86084. if(yi < 0){ yi = 0; }
  86085. if(xi >= data.length - 1){ xi = data.length - 1; }
  86086. if(yi >= data[0].length - 1){ yi = data[0].length - 1; }
  86087. }
  86088. // Bail out if we are out of the terrain
  86089. if(xi < 0 || yi < 0 || xi >= data.length-1 || yi >= data[0].length-1){
  86090. return false;
  86091. }
  86092. return true;
  86093. };
  86094. Heightfield.prototype.getHeightAt = function(x, y, edgeClamp){
  86095. var idx = [];
  86096. this.getIndexOfPosition(x, y, idx, edgeClamp);
  86097. // TODO: get upper or lower triangle, then use barycentric interpolation to get the height in the triangle.
  86098. var minmax = [];
  86099. this.getRectMinMax(idx[0], idx[1] + 1, idx[0], idx[1] + 1, minmax);
  86100. return (minmax[0] + minmax[1]) / 2; // average
  86101. };
  86102. Heightfield.prototype.getCacheConvexTrianglePillarKey = function(xi, yi, getUpperTriangle){
  86103. return xi + '_' + yi + '_' + (getUpperTriangle ? 1 : 0);
  86104. };
  86105. Heightfield.prototype.getCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle){
  86106. return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  86107. };
  86108. Heightfield.prototype.setCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle, convex, offset){
  86109. this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)] = {
  86110. convex: convex,
  86111. offset: offset
  86112. };
  86113. };
  86114. Heightfield.prototype.clearCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle){
  86115. delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
  86116. };
  86117. /**
  86118. * Get a triangle in the terrain in the form of a triangular convex shape.
  86119. * @method getConvexTrianglePillar
  86120. * @param {integer} i
  86121. * @param {integer} j
  86122. * @param {boolean} getUpperTriangle
  86123. */
  86124. Heightfield.prototype.getConvexTrianglePillar = function(xi, yi, getUpperTriangle){
  86125. var result = this.pillarConvex;
  86126. var offsetResult = this.pillarOffset;
  86127. if(this.cacheEnabled){
  86128. var data = this.getCachedConvexTrianglePillar(xi, yi, getUpperTriangle);
  86129. if(data){
  86130. this.pillarConvex = data.convex;
  86131. this.pillarOffset = data.offset;
  86132. return;
  86133. }
  86134. result = new ConvexPolyhedron();
  86135. offsetResult = new Vec3();
  86136. this.pillarConvex = result;
  86137. this.pillarOffset = offsetResult;
  86138. }
  86139. var data = this.data;
  86140. var elementSize = this.elementSize;
  86141. var faces = result.faces;
  86142. // Reuse verts if possible
  86143. result.vertices.length = 6;
  86144. for (var i = 0; i < 6; i++) {
  86145. if(!result.vertices[i]){
  86146. result.vertices[i] = new Vec3();
  86147. }
  86148. }
  86149. // Reuse faces if possible
  86150. faces.length = 5;
  86151. for (var i = 0; i < 5; i++) {
  86152. if(!faces[i]){
  86153. faces[i] = [];
  86154. }
  86155. }
  86156. var verts = result.vertices;
  86157. var h = (Math.min(
  86158. data[xi][yi],
  86159. data[xi+1][yi],
  86160. data[xi][yi+1],
  86161. data[xi+1][yi+1]
  86162. ) - this.minValue ) / 2 + this.minValue;
  86163. if (!getUpperTriangle) {
  86164. // Center of the triangle pillar - all polygons are given relative to this one
  86165. offsetResult.set(
  86166. (xi + 0.25) * elementSize, // sort of center of a triangle
  86167. (yi + 0.25) * elementSize,
  86168. h // vertical center
  86169. );
  86170. // Top triangle verts
  86171. verts[0].set(
  86172. -0.25 * elementSize,
  86173. -0.25 * elementSize,
  86174. data[xi][yi] - h
  86175. );
  86176. verts[1].set(
  86177. 0.75 * elementSize,
  86178. -0.25 * elementSize,
  86179. data[xi + 1][yi] - h
  86180. );
  86181. verts[2].set(
  86182. -0.25 * elementSize,
  86183. 0.75 * elementSize,
  86184. data[xi][yi + 1] - h
  86185. );
  86186. // bottom triangle verts
  86187. verts[3].set(
  86188. -0.25 * elementSize,
  86189. -0.25 * elementSize,
  86190. -h-1
  86191. );
  86192. verts[4].set(
  86193. 0.75 * elementSize,
  86194. -0.25 * elementSize,
  86195. -h-1
  86196. );
  86197. verts[5].set(
  86198. -0.25 * elementSize,
  86199. 0.75 * elementSize,
  86200. -h-1
  86201. );
  86202. // top triangle
  86203. faces[0][0] = 0;
  86204. faces[0][1] = 1;
  86205. faces[0][2] = 2;
  86206. // bottom triangle
  86207. faces[1][0] = 5;
  86208. faces[1][1] = 4;
  86209. faces[1][2] = 3;
  86210. // -x facing quad
  86211. faces[2][0] = 0;
  86212. faces[2][1] = 2;
  86213. faces[2][2] = 5;
  86214. faces[2][3] = 3;
  86215. // -y facing quad
  86216. faces[3][0] = 1;
  86217. faces[3][1] = 0;
  86218. faces[3][2] = 3;
  86219. faces[3][3] = 4;
  86220. // +xy facing quad
  86221. faces[4][0] = 4;
  86222. faces[4][1] = 5;
  86223. faces[4][2] = 2;
  86224. faces[4][3] = 1;
  86225. } else {
  86226. // Center of the triangle pillar - all polygons are given relative to this one
  86227. offsetResult.set(
  86228. (xi + 0.75) * elementSize, // sort of center of a triangle
  86229. (yi + 0.75) * elementSize,
  86230. h // vertical center
  86231. );
  86232. // Top triangle verts
  86233. verts[0].set(
  86234. 0.25 * elementSize,
  86235. 0.25 * elementSize,
  86236. data[xi + 1][yi + 1] - h
  86237. );
  86238. verts[1].set(
  86239. -0.75 * elementSize,
  86240. 0.25 * elementSize,
  86241. data[xi][yi + 1] - h
  86242. );
  86243. verts[2].set(
  86244. 0.25 * elementSize,
  86245. -0.75 * elementSize,
  86246. data[xi + 1][yi] - h
  86247. );
  86248. // bottom triangle verts
  86249. verts[3].set(
  86250. 0.25 * elementSize,
  86251. 0.25 * elementSize,
  86252. - h-1
  86253. );
  86254. verts[4].set(
  86255. -0.75 * elementSize,
  86256. 0.25 * elementSize,
  86257. - h-1
  86258. );
  86259. verts[5].set(
  86260. 0.25 * elementSize,
  86261. -0.75 * elementSize,
  86262. - h-1
  86263. );
  86264. // Top triangle
  86265. faces[0][0] = 0;
  86266. faces[0][1] = 1;
  86267. faces[0][2] = 2;
  86268. // bottom triangle
  86269. faces[1][0] = 5;
  86270. faces[1][1] = 4;
  86271. faces[1][2] = 3;
  86272. // +x facing quad
  86273. faces[2][0] = 2;
  86274. faces[2][1] = 5;
  86275. faces[2][2] = 3;
  86276. faces[2][3] = 0;
  86277. // +y facing quad
  86278. faces[3][0] = 3;
  86279. faces[3][1] = 4;
  86280. faces[3][2] = 1;
  86281. faces[3][3] = 0;
  86282. // -xy facing quad
  86283. faces[4][0] = 1;
  86284. faces[4][1] = 4;
  86285. faces[4][2] = 5;
  86286. faces[4][3] = 2;
  86287. }
  86288. result.computeNormals();
  86289. result.computeEdges();
  86290. result.updateBoundingSphereRadius();
  86291. this.setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, result, offsetResult);
  86292. };
  86293. Heightfield.prototype.calculateLocalInertia = function(mass, target){
  86294. target = target || new Vec3();
  86295. target.set(0, 0, 0);
  86296. return target;
  86297. };
  86298. Heightfield.prototype.volume = function(){
  86299. return Number.MAX_VALUE; // The terrain is infinite
  86300. };
  86301. Heightfield.prototype.calculateWorldAABB = function(pos, quat, min, max){
  86302. // TODO: do it properly
  86303. min.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  86304. max.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  86305. };
  86306. Heightfield.prototype.updateBoundingSphereRadius = function(){
  86307. // Use the bounding box of the min/max values
  86308. var data = this.data,
  86309. s = this.elementSize;
  86310. this.boundingSphereRadius = new Vec3(data.length * s, data[0].length * s, Math.max(Math.abs(this.maxValue), Math.abs(this.minValue))).norm();
  86311. };
  86312. },{"../math/Vec3":30,"../utils/Utils":53,"./ConvexPolyhedron":38,"./Shape":43}],41:[function(_dereq_,module,exports){
  86313. module.exports = Particle;
  86314. var Shape = _dereq_('./Shape');
  86315. var Vec3 = _dereq_('../math/Vec3');
  86316. /**
  86317. * Particle shape.
  86318. * @class Particle
  86319. * @constructor
  86320. * @author schteppe
  86321. * @extends Shape
  86322. */
  86323. function Particle(){
  86324. Shape.call(this);
  86325. this.type = Shape.types.PARTICLE;
  86326. }
  86327. Particle.prototype = new Shape();
  86328. Particle.prototype.constructor = Particle;
  86329. /**
  86330. * @method calculateLocalInertia
  86331. * @param {Number} mass
  86332. * @param {Vec3} target
  86333. * @return {Vec3}
  86334. */
  86335. Particle.prototype.calculateLocalInertia = function(mass,target){
  86336. target = target || new Vec3();
  86337. target.set(0, 0, 0);
  86338. return target;
  86339. };
  86340. Particle.prototype.volume = function(){
  86341. return 0;
  86342. };
  86343. Particle.prototype.updateBoundingSphereRadius = function(){
  86344. this.boundingSphereRadius = 0;
  86345. };
  86346. Particle.prototype.calculateWorldAABB = function(pos,quat,min,max){
  86347. // Get each axis max
  86348. min.copy(pos);
  86349. max.copy(pos);
  86350. };
  86351. },{"../math/Vec3":30,"./Shape":43}],42:[function(_dereq_,module,exports){
  86352. module.exports = Plane;
  86353. var Shape = _dereq_('./Shape');
  86354. var Vec3 = _dereq_('../math/Vec3');
  86355. /**
  86356. * A plane, facing in the Z direction. The plane has its surface at z=0 and everything below z=0 is assumed to be solid plane. To make the plane face in some other direction than z, you must put it inside a RigidBody and rotate that body. See the demos.
  86357. * @class Plane
  86358. * @constructor
  86359. * @extends Shape
  86360. * @author schteppe
  86361. */
  86362. function Plane(){
  86363. Shape.call(this);
  86364. this.type = Shape.types.PLANE;
  86365. // World oriented normal
  86366. this.worldNormal = new Vec3();
  86367. this.worldNormalNeedsUpdate = true;
  86368. this.boundingSphereRadius = Number.MAX_VALUE;
  86369. }
  86370. Plane.prototype = new Shape();
  86371. Plane.prototype.constructor = Plane;
  86372. Plane.prototype.computeWorldNormal = function(quat){
  86373. var n = this.worldNormal;
  86374. n.set(0,0,1);
  86375. quat.vmult(n,n);
  86376. this.worldNormalNeedsUpdate = false;
  86377. };
  86378. Plane.prototype.calculateLocalInertia = function(mass,target){
  86379. target = target || new Vec3();
  86380. return target;
  86381. };
  86382. Plane.prototype.volume = function(){
  86383. return Number.MAX_VALUE; // The plane is infinite...
  86384. };
  86385. var tempNormal = new Vec3();
  86386. Plane.prototype.calculateWorldAABB = function(pos, quat, min, max){
  86387. // The plane AABB is infinite, except if the normal is pointing along any axis
  86388. tempNormal.set(0,0,1); // Default plane normal is z
  86389. quat.vmult(tempNormal,tempNormal);
  86390. var maxVal = Number.MAX_VALUE;
  86391. min.set(-maxVal, -maxVal, -maxVal);
  86392. max.set(maxVal, maxVal, maxVal);
  86393. if(tempNormal.x === 1){ max.x = pos.x; }
  86394. if(tempNormal.y === 1){ max.y = pos.y; }
  86395. if(tempNormal.z === 1){ max.z = pos.z; }
  86396. if(tempNormal.x === -1){ min.x = pos.x; }
  86397. if(tempNormal.y === -1){ min.y = pos.y; }
  86398. if(tempNormal.z === -1){ min.z = pos.z; }
  86399. };
  86400. Plane.prototype.updateBoundingSphereRadius = function(){
  86401. this.boundingSphereRadius = Number.MAX_VALUE;
  86402. };
  86403. },{"../math/Vec3":30,"./Shape":43}],43:[function(_dereq_,module,exports){
  86404. module.exports = Shape;
  86405. var Shape = _dereq_('./Shape');
  86406. var Vec3 = _dereq_('../math/Vec3');
  86407. var Quaternion = _dereq_('../math/Quaternion');
  86408. var Material = _dereq_('../material/Material');
  86409. /**
  86410. * Base class for shapes
  86411. * @class Shape
  86412. * @constructor
  86413. * @author schteppe
  86414. * @todo Should have a mechanism for caching bounding sphere radius instead of calculating it each time
  86415. */
  86416. function Shape(){
  86417. /**
  86418. * Identifyer of the Shape.
  86419. * @property {number} id
  86420. */
  86421. this.id = Shape.idCounter++;
  86422. /**
  86423. * The type of this shape. Must be set to an int > 0 by subclasses.
  86424. * @property type
  86425. * @type {Number}
  86426. * @see Shape.types
  86427. */
  86428. this.type = 0;
  86429. /**
  86430. * The local bounding sphere radius of this shape.
  86431. * @property {Number} boundingSphereRadius
  86432. */
  86433. this.boundingSphereRadius = 0;
  86434. /**
  86435. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
  86436. * @property {boolean} collisionResponse
  86437. */
  86438. this.collisionResponse = true;
  86439. /**
  86440. * @property {Material} material
  86441. */
  86442. this.material = null;
  86443. }
  86444. Shape.prototype.constructor = Shape;
  86445. /**
  86446. * Computes the bounding sphere radius. The result is stored in the property .boundingSphereRadius
  86447. * @method updateBoundingSphereRadius
  86448. * @return {Number}
  86449. */
  86450. Shape.prototype.updateBoundingSphereRadius = function(){
  86451. throw "computeBoundingSphereRadius() not implemented for shape type "+this.type;
  86452. };
  86453. /**
  86454. * Get the volume of this shape
  86455. * @method volume
  86456. * @return {Number}
  86457. */
  86458. Shape.prototype.volume = function(){
  86459. throw "volume() not implemented for shape type "+this.type;
  86460. };
  86461. /**
  86462. * Calculates the inertia in the local frame for this shape.
  86463. * @method calculateLocalInertia
  86464. * @return {Vec3}
  86465. * @see http://en.wikipedia.org/wiki/List_of_moments_of_inertia
  86466. */
  86467. Shape.prototype.calculateLocalInertia = function(mass,target){
  86468. throw "calculateLocalInertia() not implemented for shape type "+this.type;
  86469. };
  86470. Shape.idCounter = 0;
  86471. /**
  86472. * The available shape types.
  86473. * @static
  86474. * @property types
  86475. * @type {Object}
  86476. */
  86477. Shape.types = {
  86478. SPHERE:1,
  86479. PLANE:2,
  86480. BOX:4,
  86481. COMPOUND:8,
  86482. CONVEXPOLYHEDRON:16,
  86483. HEIGHTFIELD:32,
  86484. PARTICLE:64,
  86485. CYLINDER:128,
  86486. TRIMESH:256
  86487. };
  86488. },{"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"./Shape":43}],44:[function(_dereq_,module,exports){
  86489. module.exports = Sphere;
  86490. var Shape = _dereq_('./Shape');
  86491. var Vec3 = _dereq_('../math/Vec3');
  86492. /**
  86493. * Spherical shape
  86494. * @class Sphere
  86495. * @constructor
  86496. * @extends Shape
  86497. * @param {Number} radius The radius of the sphere, a non-negative number.
  86498. * @author schteppe / http://github.com/schteppe
  86499. */
  86500. function Sphere(radius){
  86501. Shape.call(this);
  86502. /**
  86503. * @property {Number} radius
  86504. */
  86505. this.radius = radius!==undefined ? Number(radius) : 1.0;
  86506. this.type = Shape.types.SPHERE;
  86507. if(this.radius < 0){
  86508. throw new Error('The sphere radius cannot be negative.');
  86509. }
  86510. this.updateBoundingSphereRadius();
  86511. }
  86512. Sphere.prototype = new Shape();
  86513. Sphere.prototype.constructor = Sphere;
  86514. Sphere.prototype.calculateLocalInertia = function(mass,target){
  86515. target = target || new Vec3();
  86516. var I = 2.0*mass*this.radius*this.radius/5.0;
  86517. target.x = I;
  86518. target.y = I;
  86519. target.z = I;
  86520. return target;
  86521. };
  86522. Sphere.prototype.volume = function(){
  86523. return 4.0 * Math.PI * this.radius / 3.0;
  86524. };
  86525. Sphere.prototype.updateBoundingSphereRadius = function(){
  86526. this.boundingSphereRadius = this.radius;
  86527. };
  86528. Sphere.prototype.calculateWorldAABB = function(pos,quat,min,max){
  86529. var r = this.radius;
  86530. var axes = ['x','y','z'];
  86531. for(var i=0; i<axes.length; i++){
  86532. var ax = axes[i];
  86533. min[ax] = pos[ax] - r;
  86534. max[ax] = pos[ax] + r;
  86535. }
  86536. };
  86537. },{"../math/Vec3":30,"./Shape":43}],45:[function(_dereq_,module,exports){
  86538. module.exports = Trimesh;
  86539. var Shape = _dereq_('./Shape');
  86540. var Vec3 = _dereq_('../math/Vec3');
  86541. var Quaternion = _dereq_('../math/Quaternion');
  86542. var Transform = _dereq_('../math/Transform');
  86543. var AABB = _dereq_('../collision/AABB');
  86544. var Octree = _dereq_('../utils/Octree');
  86545. /**
  86546. * @class Trimesh
  86547. * @constructor
  86548. * @param {array} vertices
  86549. * @param {array} indices
  86550. * @extends Shape
  86551. * @example
  86552. * // How to make a mesh with a single triangle
  86553. * var vertices = [
  86554. * 0, 0, 0, // vertex 0
  86555. * 1, 0, 0, // vertex 1
  86556. * 0, 1, 0 // vertex 2
  86557. * ];
  86558. * var indices = [
  86559. * 0, 1, 2 // triangle 0
  86560. * ];
  86561. * var trimeshShape = new Trimesh(vertices, indices);
  86562. */
  86563. function Trimesh(vertices, indices) {
  86564. Shape.call(this);
  86565. this.type = Shape.types.TRIMESH;
  86566. /**
  86567. * @property vertices
  86568. * @type {Array}
  86569. */
  86570. this.vertices = new Float32Array(vertices);
  86571. /**
  86572. * Array of integers, indicating which vertices each triangle consists of. The length of this array is thus 3 times the number of triangles.
  86573. * @property indices
  86574. * @type {Array}
  86575. */
  86576. this.indices = new Int16Array(indices);
  86577. /**
  86578. * The normals data.
  86579. * @property normals
  86580. * @type {Array}
  86581. */
  86582. this.normals = new Float32Array(indices.length);
  86583. /**
  86584. * The local AABB of the mesh.
  86585. * @property aabb
  86586. * @type {Array}
  86587. */
  86588. this.aabb = new AABB();
  86589. /**
  86590. * References to vertex pairs, making up all unique edges in the trimesh.
  86591. * @property {array} edges
  86592. */
  86593. this.edges = null;
  86594. /**
  86595. * Local scaling of the mesh. Use .setScale() to set it.
  86596. * @property {Vec3} scale
  86597. */
  86598. this.scale = new Vec3(1, 1, 1);
  86599. /**
  86600. * The indexed triangles. Use .updateTree() to update it.
  86601. * @property {Octree} tree
  86602. */
  86603. this.tree = new Octree();
  86604. this.updateEdges();
  86605. this.updateNormals();
  86606. this.updateAABB();
  86607. this.updateBoundingSphereRadius();
  86608. this.updateTree();
  86609. }
  86610. Trimesh.prototype = new Shape();
  86611. Trimesh.prototype.constructor = Trimesh;
  86612. var computeNormals_n = new Vec3();
  86613. /**
  86614. * @method updateTree
  86615. */
  86616. Trimesh.prototype.updateTree = function(){
  86617. var tree = this.tree;
  86618. tree.reset();
  86619. tree.aabb.copy(this.aabb);
  86620. var scale = this.scale; // The local mesh AABB is scaled, but the octree AABB should be unscaled
  86621. tree.aabb.lowerBound.x *= 1 / scale.x;
  86622. tree.aabb.lowerBound.y *= 1 / scale.y;
  86623. tree.aabb.lowerBound.z *= 1 / scale.z;
  86624. tree.aabb.upperBound.x *= 1 / scale.x;
  86625. tree.aabb.upperBound.y *= 1 / scale.y;
  86626. tree.aabb.upperBound.z *= 1 / scale.z;
  86627. // Insert all triangles
  86628. var triangleAABB = new AABB();
  86629. var a = new Vec3();
  86630. var b = new Vec3();
  86631. var c = new Vec3();
  86632. var points = [a, b, c];
  86633. for (var i = 0; i < this.indices.length / 3; i++) {
  86634. //this.getTriangleVertices(i, a, b, c);
  86635. // Get unscaled triangle verts
  86636. var i3 = i * 3;
  86637. this._getUnscaledVertex(this.indices[i3], a);
  86638. this._getUnscaledVertex(this.indices[i3 + 1], b);
  86639. this._getUnscaledVertex(this.indices[i3 + 2], c);
  86640. triangleAABB.setFromPoints(points);
  86641. tree.insert(triangleAABB, i);
  86642. }
  86643. tree.removeEmptyNodes();
  86644. };
  86645. var unscaledAABB = new AABB();
  86646. /**
  86647. * Get triangles in a local AABB from the trimesh.
  86648. * @method getTrianglesInAABB
  86649. * @param {AABB} aabb
  86650. * @param {array} result An array of integers, referencing the queried triangles.
  86651. */
  86652. Trimesh.prototype.getTrianglesInAABB = function(aabb, result){
  86653. unscaledAABB.copy(aabb);
  86654. // Scale it to local
  86655. var scale = this.scale;
  86656. var isx = scale.x;
  86657. var isy = scale.y;
  86658. var isz = scale.z;
  86659. var l = unscaledAABB.lowerBound;
  86660. var u = unscaledAABB.upperBound;
  86661. l.x /= isx;
  86662. l.y /= isy;
  86663. l.z /= isz;
  86664. u.x /= isx;
  86665. u.y /= isy;
  86666. u.z /= isz;
  86667. return this.tree.aabbQuery(unscaledAABB, result);
  86668. };
  86669. /**
  86670. * @method setScale
  86671. * @param {Vec3} scale
  86672. */
  86673. Trimesh.prototype.setScale = function(scale){
  86674. var wasUniform = this.scale.x === this.scale.y === this.scale.z;
  86675. var isUniform = scale.x === scale.y === scale.z;
  86676. if(!(wasUniform && isUniform)){
  86677. // Non-uniform scaling. Need to update normals.
  86678. this.updateNormals();
  86679. }
  86680. this.scale.copy(scale);
  86681. this.updateAABB();
  86682. this.updateBoundingSphereRadius();
  86683. };
  86684. /**
  86685. * Compute the normals of the faces. Will save in the .normals array.
  86686. * @method updateNormals
  86687. */
  86688. Trimesh.prototype.updateNormals = function(){
  86689. var n = computeNormals_n;
  86690. // Generate normals
  86691. var normals = this.normals;
  86692. for(var i=0; i < this.indices.length / 3; i++){
  86693. var i3 = i * 3;
  86694. var a = this.indices[i3],
  86695. b = this.indices[i3 + 1],
  86696. c = this.indices[i3 + 2];
  86697. this.getVertex(a, va);
  86698. this.getVertex(b, vb);
  86699. this.getVertex(c, vc);
  86700. Trimesh.computeNormal(vb, va, vc, n);
  86701. normals[i3] = n.x;
  86702. normals[i3 + 1] = n.y;
  86703. normals[i3 + 2] = n.z;
  86704. }
  86705. };
  86706. /**
  86707. * Update the .edges property
  86708. * @method updateEdges
  86709. */
  86710. Trimesh.prototype.updateEdges = function(){
  86711. var edges = {};
  86712. var add = function(indexA, indexB){
  86713. var key = a < b ? a + '_' + b : b + '_' + a;
  86714. edges[key] = true;
  86715. };
  86716. for(var i=0; i < this.indices.length / 3; i++){
  86717. var i3 = i * 3;
  86718. var a = this.indices[i3],
  86719. b = this.indices[i3 + 1],
  86720. c = this.indices[i3 + 2];
  86721. add(a,b);
  86722. add(b,c);
  86723. add(c,a);
  86724. }
  86725. var keys = Object.keys(edges);
  86726. this.edges = new Int16Array(keys.length * 2);
  86727. for (var i = 0; i < keys.length; i++) {
  86728. var indices = keys[i].split('_');
  86729. this.edges[2 * i] = parseInt(indices[0], 10);
  86730. this.edges[2 * i + 1] = parseInt(indices[1], 10);
  86731. }
  86732. };
  86733. /**
  86734. * Get an edge vertex
  86735. * @method getEdgeVertex
  86736. * @param {number} edgeIndex
  86737. * @param {number} firstOrSecond 0 or 1, depending on which one of the vertices you need.
  86738. * @param {Vec3} vertexStore Where to store the result
  86739. */
  86740. Trimesh.prototype.getEdgeVertex = function(edgeIndex, firstOrSecond, vertexStore){
  86741. var vertexIndex = this.edges[edgeIndex * 2 + (firstOrSecond ? 1 : 0)];
  86742. this.getVertex(vertexIndex, vertexStore);
  86743. };
  86744. var getEdgeVector_va = new Vec3();
  86745. var getEdgeVector_vb = new Vec3();
  86746. /**
  86747. * Get a vector along an edge.
  86748. * @method getEdgeVector
  86749. * @param {number} edgeIndex
  86750. * @param {Vec3} vectorStore
  86751. */
  86752. Trimesh.prototype.getEdgeVector = function(edgeIndex, vectorStore){
  86753. var va = getEdgeVector_va;
  86754. var vb = getEdgeVector_vb;
  86755. this.getEdgeVertex(edgeIndex, 0, va);
  86756. this.getEdgeVertex(edgeIndex, 1, vb);
  86757. vb.vsub(va, vectorStore);
  86758. };
  86759. /**
  86760. * Get face normal given 3 vertices
  86761. * @static
  86762. * @method computeNormal
  86763. * @param {Vec3} va
  86764. * @param {Vec3} vb
  86765. * @param {Vec3} vc
  86766. * @param {Vec3} target
  86767. */
  86768. var cb = new Vec3();
  86769. var ab = new Vec3();
  86770. Trimesh.computeNormal = function ( va, vb, vc, target ) {
  86771. vb.vsub(va,ab);
  86772. vc.vsub(vb,cb);
  86773. cb.cross(ab,target);
  86774. if ( !target.isZero() ) {
  86775. target.normalize();
  86776. }
  86777. };
  86778. var va = new Vec3();
  86779. var vb = new Vec3();
  86780. var vc = new Vec3();
  86781. /**
  86782. * Get vertex i.
  86783. * @method getVertex
  86784. * @param {number} i
  86785. * @param {Vec3} out
  86786. * @return {Vec3} The "out" vector object
  86787. */
  86788. Trimesh.prototype.getVertex = function(i, out){
  86789. var scale = this.scale;
  86790. this._getUnscaledVertex(i, out);
  86791. out.x *= scale.x;
  86792. out.y *= scale.y;
  86793. out.z *= scale.z;
  86794. return out;
  86795. };
  86796. /**
  86797. * Get raw vertex i
  86798. * @private
  86799. * @method _getUnscaledVertex
  86800. * @param {number} i
  86801. * @param {Vec3} out
  86802. * @return {Vec3} The "out" vector object
  86803. */
  86804. Trimesh.prototype._getUnscaledVertex = function(i, out){
  86805. var i3 = i * 3;
  86806. var vertices = this.vertices;
  86807. return out.set(
  86808. vertices[i3],
  86809. vertices[i3 + 1],
  86810. vertices[i3 + 2]
  86811. );
  86812. };
  86813. /**
  86814. * Get a vertex from the trimesh,transformed by the given position and quaternion.
  86815. * @method getWorldVertex
  86816. * @param {number} i
  86817. * @param {Vec3} pos
  86818. * @param {Quaternion} quat
  86819. * @param {Vec3} out
  86820. * @return {Vec3} The "out" vector object
  86821. */
  86822. Trimesh.prototype.getWorldVertex = function(i, pos, quat, out){
  86823. this.getVertex(i, out);
  86824. Transform.pointToWorldFrame(pos, quat, out, out);
  86825. return out;
  86826. };
  86827. /**
  86828. * Get the three vertices for triangle i.
  86829. * @method getTriangleVertices
  86830. * @param {number} i
  86831. * @param {Vec3} a
  86832. * @param {Vec3} b
  86833. * @param {Vec3} c
  86834. */
  86835. Trimesh.prototype.getTriangleVertices = function(i, a, b, c){
  86836. var i3 = i * 3;
  86837. this.getVertex(this.indices[i3], a);
  86838. this.getVertex(this.indices[i3 + 1], b);
  86839. this.getVertex(this.indices[i3 + 2], c);
  86840. };
  86841. /**
  86842. * Compute the normal of triangle i.
  86843. * @method getNormal
  86844. * @param {Number} i
  86845. * @param {Vec3} target
  86846. * @return {Vec3} The "target" vector object
  86847. */
  86848. Trimesh.prototype.getNormal = function(i, target){
  86849. var i3 = i * 3;
  86850. return target.set(
  86851. this.normals[i3],
  86852. this.normals[i3 + 1],
  86853. this.normals[i3 + 2]
  86854. );
  86855. };
  86856. var cli_aabb = new AABB();
  86857. /**
  86858. * @method calculateLocalInertia
  86859. * @param {Number} mass
  86860. * @param {Vec3} target
  86861. * @return {Vec3} The "target" vector object
  86862. */
  86863. Trimesh.prototype.calculateLocalInertia = function(mass,target){
  86864. // Approximate with box inertia
  86865. // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
  86866. this.computeLocalAABB(cli_aabb);
  86867. var x = cli_aabb.upperBound.x - cli_aabb.lowerBound.x,
  86868. y = cli_aabb.upperBound.y - cli_aabb.lowerBound.y,
  86869. z = cli_aabb.upperBound.z - cli_aabb.lowerBound.z;
  86870. return target.set(
  86871. 1.0 / 12.0 * mass * ( 2*y*2*y + 2*z*2*z ),
  86872. 1.0 / 12.0 * mass * ( 2*x*2*x + 2*z*2*z ),
  86873. 1.0 / 12.0 * mass * ( 2*y*2*y + 2*x*2*x )
  86874. );
  86875. };
  86876. var computeLocalAABB_worldVert = new Vec3();
  86877. /**
  86878. * Compute the local AABB for the trimesh
  86879. * @method computeLocalAABB
  86880. * @param {AABB} aabb
  86881. */
  86882. Trimesh.prototype.computeLocalAABB = function(aabb){
  86883. var l = aabb.lowerBound,
  86884. u = aabb.upperBound,
  86885. n = this.vertices.length,
  86886. vertices = this.vertices,
  86887. v = computeLocalAABB_worldVert;
  86888. this.getVertex(0, v);
  86889. l.copy(v);
  86890. u.copy(v);
  86891. for(var i=0; i !== n; i++){
  86892. this.getVertex(i, v);
  86893. if(v.x < l.x){
  86894. l.x = v.x;
  86895. } else if(v.x > u.x){
  86896. u.x = v.x;
  86897. }
  86898. if(v.y < l.y){
  86899. l.y = v.y;
  86900. } else if(v.y > u.y){
  86901. u.y = v.y;
  86902. }
  86903. if(v.z < l.z){
  86904. l.z = v.z;
  86905. } else if(v.z > u.z){
  86906. u.z = v.z;
  86907. }
  86908. }
  86909. };
  86910. /**
  86911. * Update the .aabb property
  86912. * @method updateAABB
  86913. */
  86914. Trimesh.prototype.updateAABB = function(){
  86915. this.computeLocalAABB(this.aabb);
  86916. };
  86917. /**
  86918. * Will update the .boundingSphereRadius property
  86919. * @method updateBoundingSphereRadius
  86920. */
  86921. Trimesh.prototype.updateBoundingSphereRadius = function(){
  86922. // Assume points are distributed with local (0,0,0) as center
  86923. var max2 = 0;
  86924. var vertices = this.vertices;
  86925. var v = new Vec3();
  86926. for(var i=0, N=vertices.length / 3; i !== N; i++) {
  86927. this.getVertex(i, v);
  86928. var norm2 = v.norm2();
  86929. if(norm2 > max2){
  86930. max2 = norm2;
  86931. }
  86932. }
  86933. this.boundingSphereRadius = Math.sqrt(max2);
  86934. };
  86935. var tempWorldVertex = new Vec3();
  86936. var calculateWorldAABB_frame = new Transform();
  86937. var calculateWorldAABB_aabb = new AABB();
  86938. /**
  86939. * @method calculateWorldAABB
  86940. * @param {Vec3} pos
  86941. * @param {Quaternion} quat
  86942. * @param {Vec3} min
  86943. * @param {Vec3} max
  86944. */
  86945. Trimesh.prototype.calculateWorldAABB = function(pos,quat,min,max){
  86946. /*
  86947. var n = this.vertices.length / 3,
  86948. verts = this.vertices;
  86949. var minx,miny,minz,maxx,maxy,maxz;
  86950. var v = tempWorldVertex;
  86951. for(var i=0; i<n; i++){
  86952. this.getVertex(i, v);
  86953. quat.vmult(v, v);
  86954. pos.vadd(v, v);
  86955. if (v.x < minx || minx===undefined){
  86956. minx = v.x;
  86957. } else if(v.x > maxx || maxx===undefined){
  86958. maxx = v.x;
  86959. }
  86960. if (v.y < miny || miny===undefined){
  86961. miny = v.y;
  86962. } else if(v.y > maxy || maxy===undefined){
  86963. maxy = v.y;
  86964. }
  86965. if (v.z < minz || minz===undefined){
  86966. minz = v.z;
  86967. } else if(v.z > maxz || maxz===undefined){
  86968. maxz = v.z;
  86969. }
  86970. }
  86971. min.set(minx,miny,minz);
  86972. max.set(maxx,maxy,maxz);
  86973. */
  86974. // Faster approximation using local AABB
  86975. var frame = calculateWorldAABB_frame;
  86976. var result = calculateWorldAABB_aabb;
  86977. frame.position = pos;
  86978. frame.quaternion = quat;
  86979. this.aabb.toWorldFrame(frame, result);
  86980. min.copy(result.lowerBound);
  86981. max.copy(result.upperBound);
  86982. };
  86983. /**
  86984. * Get approximate volume
  86985. * @method volume
  86986. * @return {Number}
  86987. */
  86988. Trimesh.prototype.volume = function(){
  86989. return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
  86990. };
  86991. /**
  86992. * Create a Trimesh instance, shaped as a torus.
  86993. * @static
  86994. * @method createTorus
  86995. * @param {number} [radius=1]
  86996. * @param {number} [tube=0.5]
  86997. * @param {number} [radialSegments=8]
  86998. * @param {number} [tubularSegments=6]
  86999. * @param {number} [arc=6.283185307179586]
  87000. * @return {Trimesh} A torus
  87001. */
  87002. Trimesh.createTorus = function (radius, tube, radialSegments, tubularSegments, arc) {
  87003. radius = radius || 1;
  87004. tube = tube || 0.5;
  87005. radialSegments = radialSegments || 8;
  87006. tubularSegments = tubularSegments || 6;
  87007. arc = arc || Math.PI * 2;
  87008. var vertices = [];
  87009. var indices = [];
  87010. for ( var j = 0; j <= radialSegments; j ++ ) {
  87011. for ( var i = 0; i <= tubularSegments; i ++ ) {
  87012. var u = i / tubularSegments * arc;
  87013. var v = j / radialSegments * Math.PI * 2;
  87014. var x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  87015. var y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  87016. var z = tube * Math.sin( v );
  87017. vertices.push( x, y, z );
  87018. }
  87019. }
  87020. for ( var j = 1; j <= radialSegments; j ++ ) {
  87021. for ( var i = 1; i <= tubularSegments; i ++ ) {
  87022. var a = ( tubularSegments + 1 ) * j + i - 1;
  87023. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  87024. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  87025. var d = ( tubularSegments + 1 ) * j + i;
  87026. indices.push(a, b, d);
  87027. indices.push(b, c, d);
  87028. }
  87029. }
  87030. return new Trimesh(vertices, indices);
  87031. };
  87032. },{"../collision/AABB":3,"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"../utils/Octree":50,"./Shape":43}],46:[function(_dereq_,module,exports){
  87033. module.exports = GSSolver;
  87034. var Vec3 = _dereq_('../math/Vec3');
  87035. var Quaternion = _dereq_('../math/Quaternion');
  87036. var Solver = _dereq_('./Solver');
  87037. /**
  87038. * Constraint equation Gauss-Seidel solver.
  87039. * @class GSSolver
  87040. * @constructor
  87041. * @todo The spook parameters should be specified for each constraint, not globally.
  87042. * @author schteppe / https://github.com/schteppe
  87043. * @see https://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf
  87044. * @extends Solver
  87045. */
  87046. function GSSolver(){
  87047. Solver.call(this);
  87048. /**
  87049. * The number of solver iterations determines quality of the constraints in the world. The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations.
  87050. * @property iterations
  87051. * @type {Number}
  87052. * @todo write more about solver and iterations in the wiki
  87053. */
  87054. this.iterations = 10;
  87055. /**
  87056. * When tolerance is reached, the system is assumed to be converged.
  87057. * @property tolerance
  87058. * @type {Number}
  87059. */
  87060. this.tolerance = 1e-7;
  87061. }
  87062. GSSolver.prototype = new Solver();
  87063. var GSSolver_solve_lambda = []; // Just temporary number holders that we want to reuse each solve.
  87064. var GSSolver_solve_invCs = [];
  87065. var GSSolver_solve_Bs = [];
  87066. GSSolver.prototype.solve = function(dt,world){
  87067. var iter = 0,
  87068. maxIter = this.iterations,
  87069. tolSquared = this.tolerance*this.tolerance,
  87070. equations = this.equations,
  87071. Neq = equations.length,
  87072. bodies = world.bodies,
  87073. Nbodies = bodies.length,
  87074. h = dt,
  87075. q, B, invC, deltalambda, deltalambdaTot, GWlambda, lambdaj;
  87076. // Update solve mass
  87077. if(Neq !== 0){
  87078. for(var i=0; i!==Nbodies; i++){
  87079. bodies[i].updateSolveMassProperties();
  87080. }
  87081. }
  87082. // Things that does not change during iteration can be computed once
  87083. var invCs = GSSolver_solve_invCs,
  87084. Bs = GSSolver_solve_Bs,
  87085. lambda = GSSolver_solve_lambda;
  87086. invCs.length = Neq;
  87087. Bs.length = Neq;
  87088. lambda.length = Neq;
  87089. for(var i=0; i!==Neq; i++){
  87090. var c = equations[i];
  87091. lambda[i] = 0.0;
  87092. Bs[i] = c.computeB(h);
  87093. invCs[i] = 1.0 / c.computeC();
  87094. }
  87095. if(Neq !== 0){
  87096. // Reset vlambda
  87097. for(var i=0; i!==Nbodies; i++){
  87098. var b=bodies[i],
  87099. vlambda=b.vlambda,
  87100. wlambda=b.wlambda;
  87101. vlambda.set(0,0,0);
  87102. if(wlambda){
  87103. wlambda.set(0,0,0);
  87104. }
  87105. }
  87106. // Iterate over equations
  87107. for(iter=0; iter!==maxIter; iter++){
  87108. // Accumulate the total error for each iteration.
  87109. deltalambdaTot = 0.0;
  87110. for(var j=0; j!==Neq; j++){
  87111. var c = equations[j];
  87112. // Compute iteration
  87113. B = Bs[j];
  87114. invC = invCs[j];
  87115. lambdaj = lambda[j];
  87116. GWlambda = c.computeGWlambda();
  87117. deltalambda = invC * ( B - GWlambda - c.eps * lambdaj );
  87118. // Clamp if we are not within the min/max interval
  87119. if(lambdaj + deltalambda < c.minForce){
  87120. deltalambda = c.minForce - lambdaj;
  87121. } else if(lambdaj + deltalambda > c.maxForce){
  87122. deltalambda = c.maxForce - lambdaj;
  87123. }
  87124. lambda[j] += deltalambda;
  87125. deltalambdaTot += deltalambda > 0.0 ? deltalambda : -deltalambda; // abs(deltalambda)
  87126. c.addToWlambda(deltalambda);
  87127. }
  87128. // If the total error is small enough - stop iterate
  87129. if(deltalambdaTot*deltalambdaTot < tolSquared){
  87130. break;
  87131. }
  87132. }
  87133. // Add result to velocity
  87134. for(var i=0; i!==Nbodies; i++){
  87135. var b=bodies[i],
  87136. v=b.velocity,
  87137. w=b.angularVelocity;
  87138. v.vadd(b.vlambda, v);
  87139. if(w){
  87140. w.vadd(b.wlambda, w);
  87141. }
  87142. }
  87143. }
  87144. return iter;
  87145. };
  87146. },{"../math/Quaternion":28,"../math/Vec3":30,"./Solver":47}],47:[function(_dereq_,module,exports){
  87147. module.exports = Solver;
  87148. /**
  87149. * Constraint equation solver base class.
  87150. * @class Solver
  87151. * @constructor
  87152. * @author schteppe / https://github.com/schteppe
  87153. */
  87154. function Solver(){
  87155. /**
  87156. * All equations to be solved
  87157. * @property {Array} equations
  87158. */
  87159. this.equations = [];
  87160. }
  87161. /**
  87162. * Should be implemented in subclasses!
  87163. * @method solve
  87164. * @param {Number} dt
  87165. * @param {World} world
  87166. */
  87167. Solver.prototype.solve = function(dt,world){
  87168. // Should return the number of iterations done!
  87169. return 0;
  87170. };
  87171. /**
  87172. * Add an equation
  87173. * @method addEquation
  87174. * @param {Equation} eq
  87175. */
  87176. Solver.prototype.addEquation = function(eq){
  87177. if (eq.enabled) {
  87178. this.equations.push(eq);
  87179. }
  87180. };
  87181. /**
  87182. * Remove an equation
  87183. * @method removeEquation
  87184. * @param {Equation} eq
  87185. */
  87186. Solver.prototype.removeEquation = function(eq){
  87187. var eqs = this.equations;
  87188. var i = eqs.indexOf(eq);
  87189. if(i !== -1){
  87190. eqs.splice(i,1);
  87191. }
  87192. };
  87193. /**
  87194. * Add all equations
  87195. * @method removeAllEquations
  87196. */
  87197. Solver.prototype.removeAllEquations = function(){
  87198. this.equations.length = 0;
  87199. };
  87200. },{}],48:[function(_dereq_,module,exports){
  87201. module.exports = SplitSolver;
  87202. var Vec3 = _dereq_('../math/Vec3');
  87203. var Quaternion = _dereq_('../math/Quaternion');
  87204. var Solver = _dereq_('./Solver');
  87205. var Body = _dereq_('../objects/Body');
  87206. /**
  87207. * Splits the equations into islands and solves them independently. Can improve performance.
  87208. * @class SplitSolver
  87209. * @constructor
  87210. * @extends Solver
  87211. * @param {Solver} subsolver
  87212. */
  87213. function SplitSolver(subsolver){
  87214. Solver.call(this);
  87215. this.iterations = 10;
  87216. this.tolerance = 1e-7;
  87217. this.subsolver = subsolver;
  87218. this.nodes = [];
  87219. this.nodePool = [];
  87220. // Create needed nodes, reuse if possible
  87221. while(this.nodePool.length < 128){
  87222. this.nodePool.push(this.createNode());
  87223. }
  87224. }
  87225. SplitSolver.prototype = new Solver();
  87226. // Returns the number of subsystems
  87227. var SplitSolver_solve_nodes = []; // All allocated node objects
  87228. var SplitSolver_solve_nodePool = []; // All allocated node objects
  87229. var SplitSolver_solve_eqs = []; // Temp array
  87230. var SplitSolver_solve_bds = []; // Temp array
  87231. var SplitSolver_solve_dummyWorld = {bodies:[]}; // Temp object
  87232. var STATIC = Body.STATIC;
  87233. function getUnvisitedNode(nodes){
  87234. var Nnodes = nodes.length;
  87235. for(var i=0; i!==Nnodes; i++){
  87236. var node = nodes[i];
  87237. if(!node.visited && !(node.body.type & STATIC)){
  87238. return node;
  87239. }
  87240. }
  87241. return false;
  87242. }
  87243. var queue = [];
  87244. function bfs(root,visitFunc,bds,eqs){
  87245. queue.push(root);
  87246. root.visited = true;
  87247. visitFunc(root,bds,eqs);
  87248. while(queue.length) {
  87249. var node = queue.pop();
  87250. // Loop over unvisited child nodes
  87251. var child;
  87252. while((child = getUnvisitedNode(node.children))) {
  87253. child.visited = true;
  87254. visitFunc(child,bds,eqs);
  87255. queue.push(child);
  87256. }
  87257. }
  87258. }
  87259. function visitFunc(node,bds,eqs){
  87260. bds.push(node.body);
  87261. var Neqs = node.eqs.length;
  87262. for(var i=0; i!==Neqs; i++){
  87263. var eq = node.eqs[i];
  87264. if(eqs.indexOf(eq) === -1){
  87265. eqs.push(eq);
  87266. }
  87267. }
  87268. }
  87269. SplitSolver.prototype.createNode = function(){
  87270. return { body:null, children:[], eqs:[], visited:false };
  87271. };
  87272. /**
  87273. * Solve the subsystems
  87274. * @method solve
  87275. * @param {Number} dt
  87276. * @param {World} world
  87277. */
  87278. SplitSolver.prototype.solve = function(dt,world){
  87279. var nodes=SplitSolver_solve_nodes,
  87280. nodePool=this.nodePool,
  87281. bodies=world.bodies,
  87282. equations=this.equations,
  87283. Neq=equations.length,
  87284. Nbodies=bodies.length,
  87285. subsolver=this.subsolver;
  87286. // Create needed nodes, reuse if possible
  87287. while(nodePool.length < Nbodies){
  87288. nodePool.push(this.createNode());
  87289. }
  87290. nodes.length = Nbodies;
  87291. for (var i = 0; i < Nbodies; i++) {
  87292. nodes[i] = nodePool[i];
  87293. }
  87294. // Reset node values
  87295. for(var i=0; i!==Nbodies; i++){
  87296. var node = nodes[i];
  87297. node.body = bodies[i];
  87298. node.children.length = 0;
  87299. node.eqs.length = 0;
  87300. node.visited = false;
  87301. }
  87302. for(var k=0; k!==Neq; k++){
  87303. var eq=equations[k],
  87304. i=bodies.indexOf(eq.bi),
  87305. j=bodies.indexOf(eq.bj),
  87306. ni=nodes[i],
  87307. nj=nodes[j];
  87308. ni.children.push(nj);
  87309. ni.eqs.push(eq);
  87310. nj.children.push(ni);
  87311. nj.eqs.push(eq);
  87312. }
  87313. var child, n=0, eqs=SplitSolver_solve_eqs;
  87314. subsolver.tolerance = this.tolerance;
  87315. subsolver.iterations = this.iterations;
  87316. var dummyWorld = SplitSolver_solve_dummyWorld;
  87317. while((child = getUnvisitedNode(nodes))){
  87318. eqs.length = 0;
  87319. dummyWorld.bodies.length = 0;
  87320. bfs(child, visitFunc, dummyWorld.bodies, eqs);
  87321. var Neqs = eqs.length;
  87322. eqs = eqs.sort(sortById);
  87323. for(var i=0; i!==Neqs; i++){
  87324. subsolver.addEquation(eqs[i]);
  87325. }
  87326. var iter = subsolver.solve(dt,dummyWorld);
  87327. subsolver.removeAllEquations();
  87328. n++;
  87329. }
  87330. return n;
  87331. };
  87332. function sortById(a, b){
  87333. return b.id - a.id;
  87334. }
  87335. },{"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"./Solver":47}],49:[function(_dereq_,module,exports){
  87336. /**
  87337. * Base class for objects that dispatches events.
  87338. * @class EventTarget
  87339. * @constructor
  87340. */
  87341. var EventTarget = function () {
  87342. };
  87343. module.exports = EventTarget;
  87344. EventTarget.prototype = {
  87345. constructor: EventTarget,
  87346. /**
  87347. * Add an event listener
  87348. * @method addEventListener
  87349. * @param {String} type
  87350. * @param {Function} listener
  87351. * @return {EventTarget} The self object, for chainability.
  87352. */
  87353. addEventListener: function ( type, listener ) {
  87354. if ( this._listeners === undefined ){ this._listeners = {}; }
  87355. var listeners = this._listeners;
  87356. if ( listeners[ type ] === undefined ) {
  87357. listeners[ type ] = [];
  87358. }
  87359. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  87360. listeners[ type ].push( listener );
  87361. }
  87362. return this;
  87363. },
  87364. /**
  87365. * Check if an event listener is added
  87366. * @method hasEventListener
  87367. * @param {String} type
  87368. * @param {Function} listener
  87369. * @return {Boolean}
  87370. */
  87371. hasEventListener: function ( type, listener ) {
  87372. if ( this._listeners === undefined ){ return false; }
  87373. var listeners = this._listeners;
  87374. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  87375. return true;
  87376. }
  87377. return false;
  87378. },
  87379. /**
  87380. * Remove an event listener
  87381. * @method removeEventListener
  87382. * @param {String} type
  87383. * @param {Function} listener
  87384. * @return {EventTarget} The self object, for chainability.
  87385. */
  87386. removeEventListener: function ( type, listener ) {
  87387. if ( this._listeners === undefined ){ return this; }
  87388. var listeners = this._listeners;
  87389. if ( listeners[type] === undefined ){ return this; }
  87390. var index = listeners[ type ].indexOf( listener );
  87391. if ( index !== - 1 ) {
  87392. listeners[ type ].splice( index, 1 );
  87393. }
  87394. return this;
  87395. },
  87396. /**
  87397. * Emit an event.
  87398. * @method dispatchEvent
  87399. * @param {Object} event
  87400. * @param {String} event.type
  87401. * @return {EventTarget} The self object, for chainability.
  87402. */
  87403. dispatchEvent: function ( event ) {
  87404. if ( this._listeners === undefined ){ return this; }
  87405. var listeners = this._listeners;
  87406. var listenerArray = listeners[ event.type ];
  87407. if ( listenerArray !== undefined ) {
  87408. event.target = this;
  87409. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  87410. listenerArray[ i ].call( this, event );
  87411. }
  87412. }
  87413. return this;
  87414. }
  87415. };
  87416. },{}],50:[function(_dereq_,module,exports){
  87417. var AABB = _dereq_('../collision/AABB');
  87418. var Vec3 = _dereq_('../math/Vec3');
  87419. module.exports = Octree;
  87420. /**
  87421. * @class OctreeNode
  87422. * @param {object} [options]
  87423. * @param {Octree} [options.root]
  87424. * @param {AABB} [options.aabb]
  87425. */
  87426. function OctreeNode(options){
  87427. options = options || {};
  87428. /**
  87429. * The root node
  87430. * @property {OctreeNode} root
  87431. */
  87432. this.root = options.root || null;
  87433. /**
  87434. * Boundary of this node
  87435. * @property {AABB} aabb
  87436. */
  87437. this.aabb = options.aabb ? options.aabb.clone() : new AABB();
  87438. /**
  87439. * Contained data at the current node level.
  87440. * @property {Array} data
  87441. */
  87442. this.data = [];
  87443. /**
  87444. * Children to this node
  87445. * @property {Array} children
  87446. */
  87447. this.children = [];
  87448. }
  87449. /**
  87450. * @class Octree
  87451. * @param {AABB} aabb The total AABB of the tree
  87452. * @param {object} [options]
  87453. * @param {number} [options.maxDepth=8]
  87454. * @extends OctreeNode
  87455. */
  87456. function Octree(aabb, options){
  87457. options = options || {};
  87458. options.root = null;
  87459. options.aabb = aabb;
  87460. OctreeNode.call(this, options);
  87461. /**
  87462. * Maximum subdivision depth
  87463. * @property {number} maxDepth
  87464. */
  87465. this.maxDepth = typeof(options.maxDepth) !== 'undefined' ? options.maxDepth : 8;
  87466. }
  87467. Octree.prototype = new OctreeNode();
  87468. OctreeNode.prototype.reset = function(aabb, options){
  87469. this.children.length = this.data.length = 0;
  87470. };
  87471. /**
  87472. * Insert data into this node
  87473. * @method insert
  87474. * @param {AABB} aabb
  87475. * @param {object} elementData
  87476. * @return {boolean} True if successful, otherwise false
  87477. */
  87478. OctreeNode.prototype.insert = function(aabb, elementData, level){
  87479. var nodeData = this.data;
  87480. level = level || 0;
  87481. // Ignore objects that do not belong in this node
  87482. if (!this.aabb.contains(aabb)){
  87483. return false; // object cannot be added
  87484. }
  87485. var children = this.children;
  87486. if(level < (this.maxDepth || this.root.maxDepth)){
  87487. // Subdivide if there are no children yet
  87488. var subdivided = false;
  87489. if (!children.length){
  87490. this.subdivide();
  87491. subdivided = true;
  87492. }
  87493. // add to whichever node will accept it
  87494. for (var i = 0; i !== 8; i++) {
  87495. if (children[i].insert(aabb, elementData, level + 1)){
  87496. return true;
  87497. }
  87498. }
  87499. if(subdivided){
  87500. // No children accepted! Might as well just remove em since they contain none
  87501. children.length = 0;
  87502. }
  87503. }
  87504. // Too deep, or children didnt want it. add it in current node
  87505. nodeData.push(elementData);
  87506. return true;
  87507. };
  87508. var halfDiagonal = new Vec3();
  87509. /**
  87510. * Create 8 equally sized children nodes and put them in the .children array.
  87511. * @method subdivide
  87512. */
  87513. OctreeNode.prototype.subdivide = function() {
  87514. var aabb = this.aabb;
  87515. var l = aabb.lowerBound;
  87516. var u = aabb.upperBound;
  87517. var children = this.children;
  87518. children.push(
  87519. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,0,0) }) }),
  87520. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,0,0) }) }),
  87521. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,1,0) }) }),
  87522. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,1,1) }) }),
  87523. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,1,1) }) }),
  87524. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,0,1) }) }),
  87525. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,0,1) }) }),
  87526. new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,1,0) }) })
  87527. );
  87528. u.vsub(l, halfDiagonal);
  87529. halfDiagonal.scale(0.5, halfDiagonal);
  87530. var root = this.root || this;
  87531. for (var i = 0; i !== 8; i++) {
  87532. var child = children[i];
  87533. // Set current node as root
  87534. child.root = root;
  87535. // Compute bounds
  87536. var lowerBound = child.aabb.lowerBound;
  87537. lowerBound.x *= halfDiagonal.x;
  87538. lowerBound.y *= halfDiagonal.y;
  87539. lowerBound.z *= halfDiagonal.z;
  87540. lowerBound.vadd(l, lowerBound);
  87541. // Upper bound is always lower bound + halfDiagonal
  87542. lowerBound.vadd(halfDiagonal, child.aabb.upperBound);
  87543. }
  87544. };
  87545. /**
  87546. * Get all data, potentially within an AABB
  87547. * @method aabbQuery
  87548. * @param {AABB} aabb
  87549. * @param {array} result
  87550. * @return {array} The "result" object
  87551. */
  87552. OctreeNode.prototype.aabbQuery = function(aabb, result) {
  87553. var nodeData = this.data;
  87554. // abort if the range does not intersect this node
  87555. // if (!this.aabb.overlaps(aabb)){
  87556. // return result;
  87557. // }
  87558. // Add objects at this level
  87559. // Array.prototype.push.apply(result, nodeData);
  87560. // Add child data
  87561. // @todo unwrap recursion into a queue / loop, that's faster in JS
  87562. var children = this.children;
  87563. // for (var i = 0, N = this.children.length; i !== N; i++) {
  87564. // children[i].aabbQuery(aabb, result);
  87565. // }
  87566. var queue = [this];
  87567. while (queue.length) {
  87568. var node = queue.pop();
  87569. if (node.aabb.overlaps(aabb)){
  87570. Array.prototype.push.apply(result, node.data);
  87571. }
  87572. Array.prototype.push.apply(queue, node.children);
  87573. }
  87574. return result;
  87575. };
  87576. var tmpAABB = new AABB();
  87577. /**
  87578. * Get all data, potentially intersected by a ray.
  87579. * @method rayQuery
  87580. * @param {Ray} ray
  87581. * @param {Transform} treeTransform
  87582. * @param {array} result
  87583. * @return {array} The "result" object
  87584. */
  87585. OctreeNode.prototype.rayQuery = function(ray, treeTransform, result) {
  87586. // Use aabb query for now.
  87587. // @todo implement real ray query which needs less lookups
  87588. ray.getAABB(tmpAABB);
  87589. tmpAABB.toLocalFrame(treeTransform, tmpAABB);
  87590. this.aabbQuery(tmpAABB, result);
  87591. return result;
  87592. };
  87593. /**
  87594. * @method removeEmptyNodes
  87595. */
  87596. OctreeNode.prototype.removeEmptyNodes = function() {
  87597. var queue = [this];
  87598. while (queue.length) {
  87599. var node = queue.pop();
  87600. for (var i = node.children.length - 1; i >= 0; i--) {
  87601. if(!node.children[i].data.length){
  87602. node.children.splice(i, 1);
  87603. }
  87604. }
  87605. Array.prototype.push.apply(queue, node.children);
  87606. }
  87607. };
  87608. },{"../collision/AABB":3,"../math/Vec3":30}],51:[function(_dereq_,module,exports){
  87609. module.exports = Pool;
  87610. /**
  87611. * For pooling objects that can be reused.
  87612. * @class Pool
  87613. * @constructor
  87614. */
  87615. function Pool(){
  87616. /**
  87617. * The pooled objects
  87618. * @property {Array} objects
  87619. */
  87620. this.objects = [];
  87621. /**
  87622. * Constructor of the objects
  87623. * @property {mixed} type
  87624. */
  87625. this.type = Object;
  87626. }
  87627. /**
  87628. * Release an object after use
  87629. * @method release
  87630. * @param {Object} obj
  87631. */
  87632. Pool.prototype.release = function(){
  87633. var Nargs = arguments.length;
  87634. for(var i=0; i!==Nargs; i++){
  87635. this.objects.push(arguments[i]);
  87636. }
  87637. };
  87638. /**
  87639. * Get an object
  87640. * @method get
  87641. * @return {mixed}
  87642. */
  87643. Pool.prototype.get = function(){
  87644. if(this.objects.length===0){
  87645. return this.constructObject();
  87646. } else {
  87647. return this.objects.pop();
  87648. }
  87649. };
  87650. /**
  87651. * Construct an object. Should be implmented in each subclass.
  87652. * @method constructObject
  87653. * @return {mixed}
  87654. */
  87655. Pool.prototype.constructObject = function(){
  87656. throw new Error("constructObject() not implemented in this Pool subclass yet!");
  87657. };
  87658. },{}],52:[function(_dereq_,module,exports){
  87659. module.exports = TupleDictionary;
  87660. /**
  87661. * @class TupleDictionary
  87662. * @constructor
  87663. */
  87664. function TupleDictionary() {
  87665. /**
  87666. * The data storage
  87667. * @property data
  87668. * @type {Object}
  87669. */
  87670. this.data = { keys:[] };
  87671. }
  87672. /**
  87673. * @method get
  87674. * @param {Number} i
  87675. * @param {Number} j
  87676. * @return {Number}
  87677. */
  87678. TupleDictionary.prototype.get = function(i, j) {
  87679. if (i > j) {
  87680. // swap
  87681. var temp = j;
  87682. j = i;
  87683. i = temp;
  87684. }
  87685. return this.data[i+'-'+j];
  87686. };
  87687. /**
  87688. * @method set
  87689. * @param {Number} i
  87690. * @param {Number} j
  87691. * @param {Number} value
  87692. */
  87693. TupleDictionary.prototype.set = function(i, j, value) {
  87694. if (i > j) {
  87695. var temp = j;
  87696. j = i;
  87697. i = temp;
  87698. }
  87699. var key = i+'-'+j;
  87700. // Check if key already exists
  87701. if(!this.get(i,j)){
  87702. this.data.keys.push(key);
  87703. }
  87704. this.data[key] = value;
  87705. };
  87706. /**
  87707. * @method reset
  87708. */
  87709. TupleDictionary.prototype.reset = function() {
  87710. var data = this.data,
  87711. keys = data.keys;
  87712. while(keys.length > 0){
  87713. var key = keys.pop();
  87714. delete data[key];
  87715. }
  87716. };
  87717. },{}],53:[function(_dereq_,module,exports){
  87718. function Utils(){}
  87719. module.exports = Utils;
  87720. /**
  87721. * Extend an options object with default values.
  87722. * @static
  87723. * @method defaults
  87724. * @param {object} options The options object. May be falsy: in this case, a new object is created and returned.
  87725. * @param {object} defaults An object containing default values.
  87726. * @return {object} The modified options object.
  87727. */
  87728. Utils.defaults = function(options, defaults){
  87729. options = options || {};
  87730. for(var key in defaults){
  87731. if(!(key in options)){
  87732. options[key] = defaults[key];
  87733. }
  87734. }
  87735. return options;
  87736. };
  87737. },{}],54:[function(_dereq_,module,exports){
  87738. module.exports = Vec3Pool;
  87739. var Vec3 = _dereq_('../math/Vec3');
  87740. var Pool = _dereq_('./Pool');
  87741. /**
  87742. * @class Vec3Pool
  87743. * @constructor
  87744. * @extends Pool
  87745. */
  87746. function Vec3Pool(){
  87747. Pool.call(this);
  87748. this.type = Vec3;
  87749. }
  87750. Vec3Pool.prototype = new Pool();
  87751. /**
  87752. * Construct a vector
  87753. * @method constructObject
  87754. * @return {Vec3}
  87755. */
  87756. Vec3Pool.prototype.constructObject = function(){
  87757. return new Vec3();
  87758. };
  87759. },{"../math/Vec3":30,"./Pool":51}],55:[function(_dereq_,module,exports){
  87760. module.exports = Narrowphase;
  87761. var AABB = _dereq_('../collision/AABB');
  87762. var Shape = _dereq_('../shapes/Shape');
  87763. var Ray = _dereq_('../collision/Ray');
  87764. var Vec3 = _dereq_('../math/Vec3');
  87765. var Transform = _dereq_('../math/Transform');
  87766. var ConvexPolyhedron = _dereq_('../shapes/ConvexPolyhedron');
  87767. var Quaternion = _dereq_('../math/Quaternion');
  87768. var Solver = _dereq_('../solver/Solver');
  87769. var Vec3Pool = _dereq_('../utils/Vec3Pool');
  87770. var ContactEquation = _dereq_('../equations/ContactEquation');
  87771. var FrictionEquation = _dereq_('../equations/FrictionEquation');
  87772. /**
  87773. * Helper class for the World. Generates ContactEquations.
  87774. * @class Narrowphase
  87775. * @constructor
  87776. * @todo Sphere-ConvexPolyhedron contacts
  87777. * @todo Contact reduction
  87778. * @todo should move methods to prototype
  87779. */
  87780. function Narrowphase(world){
  87781. /**
  87782. * Internal storage of pooled contact points.
  87783. * @property {Array} contactPointPool
  87784. */
  87785. this.contactPointPool = [];
  87786. this.frictionEquationPool = [];
  87787. this.result = [];
  87788. this.frictionResult = [];
  87789. /**
  87790. * Pooled vectors.
  87791. * @property {Vec3Pool} v3pool
  87792. */
  87793. this.v3pool = new Vec3Pool();
  87794. this.world = world;
  87795. this.currentContactMaterial = null;
  87796. /**
  87797. * @property {Boolean} enableFrictionReduction
  87798. */
  87799. this.enableFrictionReduction = false;
  87800. }
  87801. /**
  87802. * Make a contact object, by using the internal pool or creating a new one.
  87803. * @method createContactEquation
  87804. * @return {ContactEquation}
  87805. */
  87806. Narrowphase.prototype.createContactEquation = function(bi, bj, si, sj, rsi, rsj){
  87807. var c;
  87808. if(this.contactPointPool.length){
  87809. c = this.contactPointPool.pop();
  87810. c.bi = bi;
  87811. c.bj = bj;
  87812. } else {
  87813. c = new ContactEquation(bi, bj);
  87814. }
  87815. c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  87816. var cm = this.currentContactMaterial;
  87817. c.restitution = cm.restitution;
  87818. c.setSpookParams(
  87819. cm.contactEquationStiffness,
  87820. cm.contactEquationRelaxation,
  87821. this.world.dt
  87822. );
  87823. var matA = si.material || bi.material;
  87824. var matB = sj.material || bj.material;
  87825. if(matA && matB && matA.restitution >= 0 && matB.restitution >= 0){
  87826. c.restitution = matA.restitution * matB.restitution;
  87827. }
  87828. c.si = rsi || si;
  87829. c.sj = rsj || sj;
  87830. return c;
  87831. };
  87832. Narrowphase.prototype.createFrictionEquationsFromContact = function(contactEquation, outArray){
  87833. var bodyA = contactEquation.bi;
  87834. var bodyB = contactEquation.bj;
  87835. var shapeA = contactEquation.si;
  87836. var shapeB = contactEquation.sj;
  87837. var world = this.world;
  87838. var cm = this.currentContactMaterial;
  87839. // If friction or restitution were specified in the material, use them
  87840. var friction = cm.friction;
  87841. var matA = shapeA.material || bodyA.material;
  87842. var matB = shapeB.material || bodyB.material;
  87843. if(matA && matB && matA.friction >= 0 && matB.friction >= 0){
  87844. friction = matA.friction * matB.friction;
  87845. }
  87846. if(friction > 0){
  87847. // Create 2 tangent equations
  87848. var mug = friction * world.gravity.length();
  87849. var reducedMass = (bodyA.invMass + bodyB.invMass);
  87850. if(reducedMass > 0){
  87851. reducedMass = 1/reducedMass;
  87852. }
  87853. var pool = this.frictionEquationPool;
  87854. var c1 = pool.length ? pool.pop() : new FrictionEquation(bodyA,bodyB,mug*reducedMass);
  87855. var c2 = pool.length ? pool.pop() : new FrictionEquation(bodyA,bodyB,mug*reducedMass);
  87856. c1.bi = c2.bi = bodyA;
  87857. c1.bj = c2.bj = bodyB;
  87858. c1.minForce = c2.minForce = -mug*reducedMass;
  87859. c1.maxForce = c2.maxForce = mug*reducedMass;
  87860. // Copy over the relative vectors
  87861. c1.ri.copy(contactEquation.ri);
  87862. c1.rj.copy(contactEquation.rj);
  87863. c2.ri.copy(contactEquation.ri);
  87864. c2.rj.copy(contactEquation.rj);
  87865. // Construct tangents
  87866. contactEquation.ni.tangents(c1.t, c2.t);
  87867. // Set spook params
  87868. c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
  87869. c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
  87870. c1.enabled = c2.enabled = contactEquation.enabled;
  87871. outArray.push(c1, c2);
  87872. return true;
  87873. }
  87874. return false;
  87875. };
  87876. var averageNormal = new Vec3();
  87877. var averageContactPointA = new Vec3();
  87878. var averageContactPointB = new Vec3();
  87879. // Take the average N latest contact point on the plane.
  87880. Narrowphase.prototype.createFrictionFromAverage = function(numContacts){
  87881. // The last contactEquation
  87882. var c = this.result[this.result.length - 1];
  87883. // Create the result: two "average" friction equations
  87884. if (!this.createFrictionEquationsFromContact(c, this.frictionResult) || numContacts === 1) {
  87885. return;
  87886. }
  87887. var f1 = this.frictionResult[this.frictionResult.length - 2];
  87888. var f2 = this.frictionResult[this.frictionResult.length - 1];
  87889. averageNormal.setZero();
  87890. averageContactPointA.setZero();
  87891. averageContactPointB.setZero();
  87892. var bodyA = c.bi;
  87893. var bodyB = c.bj;
  87894. for(var i=0; i!==numContacts; i++){
  87895. c = this.result[this.result.length - 1 - i];
  87896. if(c.bodyA !== bodyA){
  87897. averageNormal.vadd(c.ni, averageNormal); // vec2.add(eq.t, eq.t, c.normalA);
  87898. averageContactPointA.vadd(c.ri, averageContactPointA); // vec2.add(eq.contactPointA, eq.contactPointA, c.contactPointA);
  87899. averageContactPointB.vadd(c.rj, averageContactPointB);
  87900. } else {
  87901. averageNormal.vsub(c.ni, averageNormal); // vec2.sub(eq.t, eq.t, c.normalA);
  87902. averageContactPointA.vadd(c.rj, averageContactPointA); // vec2.add(eq.contactPointA, eq.contactPointA, c.contactPointA);
  87903. averageContactPointB.vadd(c.ri, averageContactPointB);
  87904. }
  87905. }
  87906. var invNumContacts = 1 / numContacts;
  87907. averageContactPointA.scale(invNumContacts, f1.ri); // vec2.scale(eq.contactPointA, eq.contactPointA, invNumContacts);
  87908. averageContactPointB.scale(invNumContacts, f1.rj); // vec2.scale(eq.contactPointB, eq.contactPointB, invNumContacts);
  87909. f2.ri.copy(f1.ri); // Should be the same
  87910. f2.rj.copy(f1.rj);
  87911. averageNormal.normalize();
  87912. averageNormal.tangents(f1.t, f2.t);
  87913. // return eq;
  87914. };
  87915. var tmpVec1 = new Vec3();
  87916. var tmpVec2 = new Vec3();
  87917. var tmpQuat1 = new Quaternion();
  87918. var tmpQuat2 = new Quaternion();
  87919. /**
  87920. * Generate all contacts between a list of body pairs
  87921. * @method getContacts
  87922. * @param {array} p1 Array of body indices
  87923. * @param {array} p2 Array of body indices
  87924. * @param {World} world
  87925. * @param {array} result Array to store generated contacts
  87926. * @param {array} oldcontacts Optional. Array of reusable contact objects
  87927. */
  87928. Narrowphase.prototype.getContacts = function(p1, p2, world, result, oldcontacts, frictionResult, frictionPool){
  87929. // Save old contact objects
  87930. this.contactPointPool = oldcontacts;
  87931. this.frictionEquationPool = frictionPool;
  87932. this.result = result;
  87933. this.frictionResult = frictionResult;
  87934. var qi = tmpQuat1;
  87935. var qj = tmpQuat2;
  87936. var xi = tmpVec1;
  87937. var xj = tmpVec2;
  87938. for(var k=0, N=p1.length; k!==N; k++){
  87939. // Get current collision bodies
  87940. var bi = p1[k],
  87941. bj = p2[k];
  87942. // Get contact material
  87943. var bodyContactMaterial = null;
  87944. if(bi.material && bj.material){
  87945. bodyContactMaterial = world.getContactMaterial(bi.material,bj.material) || null;
  87946. }
  87947. for (var i = 0; i < bi.shapes.length; i++) {
  87948. bi.quaternion.mult(bi.shapeOrientations[i], qi);
  87949. bi.quaternion.vmult(bi.shapeOffsets[i], xi);
  87950. xi.vadd(bi.position, xi);
  87951. var si = bi.shapes[i];
  87952. for (var j = 0; j < bj.shapes.length; j++) {
  87953. // Compute world transform of shapes
  87954. bj.quaternion.mult(bj.shapeOrientations[j], qj);
  87955. bj.quaternion.vmult(bj.shapeOffsets[j], xj);
  87956. xj.vadd(bj.position, xj);
  87957. var sj = bj.shapes[j];
  87958. if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  87959. continue;
  87960. }
  87961. // Get collision material
  87962. var shapeContactMaterial = null;
  87963. if(si.material && sj.material){
  87964. shapeContactMaterial = world.getContactMaterial(si.material,sj.material) || null;
  87965. }
  87966. this.currentContactMaterial = shapeContactMaterial || bodyContactMaterial || world.defaultContactMaterial;
  87967. // Get contacts
  87968. var resolver = this[si.type | sj.type];
  87969. if(resolver){
  87970. if (si.type < sj.type) {
  87971. resolver.call(this, si, sj, xi, xj, qi, qj, bi, bj, si, sj);
  87972. } else {
  87973. resolver.call(this, sj, si, xj, xi, qj, qi, bj, bi, si, sj);
  87974. }
  87975. }
  87976. }
  87977. }
  87978. }
  87979. };
  87980. var numWarnings = 0;
  87981. var maxWarnings = 10;
  87982. function warn(msg){
  87983. if(numWarnings > maxWarnings){
  87984. return;
  87985. }
  87986. numWarnings++;
  87987. console.warn(msg);
  87988. }
  87989. Narrowphase.prototype[Shape.types.BOX | Shape.types.BOX] =
  87990. Narrowphase.prototype.boxBox = function(si,sj,xi,xj,qi,qj,bi,bj){
  87991. si.convexPolyhedronRepresentation.material = si.material;
  87992. sj.convexPolyhedronRepresentation.material = sj.material;
  87993. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  87994. sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
  87995. this.convexConvex(si.convexPolyhedronRepresentation,sj.convexPolyhedronRepresentation,xi,xj,qi,qj,bi,bj,si,sj);
  87996. };
  87997. Narrowphase.prototype[Shape.types.BOX | Shape.types.CONVEXPOLYHEDRON] =
  87998. Narrowphase.prototype.boxConvex = function(si,sj,xi,xj,qi,qj,bi,bj){
  87999. si.convexPolyhedronRepresentation.material = si.material;
  88000. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  88001. this.convexConvex(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj);
  88002. };
  88003. Narrowphase.prototype[Shape.types.BOX | Shape.types.PARTICLE] =
  88004. Narrowphase.prototype.boxParticle = function(si,sj,xi,xj,qi,qj,bi,bj){
  88005. si.convexPolyhedronRepresentation.material = si.material;
  88006. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  88007. this.convexParticle(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj);
  88008. };
  88009. /**
  88010. * @method sphereSphere
  88011. * @param {Shape} si
  88012. * @param {Shape} sj
  88013. * @param {Vec3} xi
  88014. * @param {Vec3} xj
  88015. * @param {Quaternion} qi
  88016. * @param {Quaternion} qj
  88017. * @param {Body} bi
  88018. * @param {Body} bj
  88019. */
  88020. Narrowphase.prototype[Shape.types.SPHERE] =
  88021. Narrowphase.prototype.sphereSphere = function(si,sj,xi,xj,qi,qj,bi,bj){
  88022. // We will have only one contact in this case
  88023. var r = this.createContactEquation(bi,bj,si,sj);
  88024. // Contact normal
  88025. xj.vsub(xi, r.ni);
  88026. r.ni.normalize();
  88027. // Contact point locations
  88028. r.ri.copy(r.ni);
  88029. r.rj.copy(r.ni);
  88030. r.ri.mult(si.radius, r.ri);
  88031. r.rj.mult(-sj.radius, r.rj);
  88032. r.ri.vadd(xi, r.ri);
  88033. r.ri.vsub(bi.position, r.ri);
  88034. r.rj.vadd(xj, r.rj);
  88035. r.rj.vsub(bj.position, r.rj);
  88036. this.result.push(r);
  88037. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88038. };
  88039. /**
  88040. * @method planeTrimesh
  88041. * @param {Shape} si
  88042. * @param {Shape} sj
  88043. * @param {Vec3} xi
  88044. * @param {Vec3} xj
  88045. * @param {Quaternion} qi
  88046. * @param {Quaternion} qj
  88047. * @param {Body} bi
  88048. * @param {Body} bj
  88049. */
  88050. var planeTrimesh_normal = new Vec3();
  88051. var planeTrimesh_relpos = new Vec3();
  88052. var planeTrimesh_projected = new Vec3();
  88053. Narrowphase.prototype[Shape.types.PLANE | Shape.types.TRIMESH] =
  88054. Narrowphase.prototype.planeTrimesh = function(
  88055. planeShape,
  88056. trimeshShape,
  88057. planePos,
  88058. trimeshPos,
  88059. planeQuat,
  88060. trimeshQuat,
  88061. planeBody,
  88062. trimeshBody
  88063. ){
  88064. // Make contacts!
  88065. var v = new Vec3();
  88066. var normal = planeTrimesh_normal;
  88067. normal.set(0,0,1);
  88068. planeQuat.vmult(normal,normal); // Turn normal according to plane
  88069. for(var i=0; i<trimeshShape.vertices.length / 3; i++){
  88070. // Get world vertex from trimesh
  88071. trimeshShape.getVertex(i, v);
  88072. // Safe up
  88073. var v2 = new Vec3();
  88074. v2.copy(v);
  88075. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);
  88076. // Check plane side
  88077. var relpos = planeTrimesh_relpos;
  88078. v.vsub(planePos, relpos);
  88079. var dot = normal.dot(relpos);
  88080. if(dot <= 0.0){
  88081. var r = this.createContactEquation(planeBody,trimeshBody,planeShape,trimeshShape);
  88082. r.ni.copy(normal); // Contact normal is the plane normal
  88083. // Get vertex position projected on plane
  88084. var projected = planeTrimesh_projected;
  88085. normal.scale(relpos.dot(normal), projected);
  88086. v.vsub(projected,projected);
  88087. // ri is the projected world position minus plane position
  88088. r.ri.copy(projected);
  88089. r.ri.vsub(planeBody.position, r.ri);
  88090. r.rj.copy(v);
  88091. r.rj.vsub(trimeshBody.position, r.rj);
  88092. // Store result
  88093. this.result.push(r);
  88094. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88095. }
  88096. }
  88097. };
  88098. /**
  88099. * @method sphereTrimesh
  88100. * @param {Shape} sphereShape
  88101. * @param {Shape} trimeshShape
  88102. * @param {Vec3} spherePos
  88103. * @param {Vec3} trimeshPos
  88104. * @param {Quaternion} sphereQuat
  88105. * @param {Quaternion} trimeshQuat
  88106. * @param {Body} sphereBody
  88107. * @param {Body} trimeshBody
  88108. */
  88109. var sphereTrimesh_normal = new Vec3();
  88110. var sphereTrimesh_relpos = new Vec3();
  88111. var sphereTrimesh_projected = new Vec3();
  88112. var sphereTrimesh_v = new Vec3();
  88113. var sphereTrimesh_v2 = new Vec3();
  88114. var sphereTrimesh_edgeVertexA = new Vec3();
  88115. var sphereTrimesh_edgeVertexB = new Vec3();
  88116. var sphereTrimesh_edgeVector = new Vec3();
  88117. var sphereTrimesh_edgeVectorUnit = new Vec3();
  88118. var sphereTrimesh_localSpherePos = new Vec3();
  88119. var sphereTrimesh_tmp = new Vec3();
  88120. var sphereTrimesh_va = new Vec3();
  88121. var sphereTrimesh_vb = new Vec3();
  88122. var sphereTrimesh_vc = new Vec3();
  88123. var sphereTrimesh_localSphereAABB = new AABB();
  88124. var sphereTrimesh_triangles = [];
  88125. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.TRIMESH] =
  88126. Narrowphase.prototype.sphereTrimesh = function (
  88127. sphereShape,
  88128. trimeshShape,
  88129. spherePos,
  88130. trimeshPos,
  88131. sphereQuat,
  88132. trimeshQuat,
  88133. sphereBody,
  88134. trimeshBody
  88135. ) {
  88136. var edgeVertexA = sphereTrimesh_edgeVertexA;
  88137. var edgeVertexB = sphereTrimesh_edgeVertexB;
  88138. var edgeVector = sphereTrimesh_edgeVector;
  88139. var edgeVectorUnit = sphereTrimesh_edgeVectorUnit;
  88140. var localSpherePos = sphereTrimesh_localSpherePos;
  88141. var tmp = sphereTrimesh_tmp;
  88142. var localSphereAABB = sphereTrimesh_localSphereAABB;
  88143. var v2 = sphereTrimesh_v2;
  88144. var relpos = sphereTrimesh_relpos;
  88145. var triangles = sphereTrimesh_triangles;
  88146. // Convert sphere position to local in the trimesh
  88147. Transform.pointToLocalFrame(trimeshPos, trimeshQuat, spherePos, localSpherePos);
  88148. // Get the aabb of the sphere locally in the trimesh
  88149. var sphereRadius = sphereShape.radius;
  88150. localSphereAABB.lowerBound.set(
  88151. localSpherePos.x - sphereRadius,
  88152. localSpherePos.y - sphereRadius,
  88153. localSpherePos.z - sphereRadius
  88154. );
  88155. localSphereAABB.upperBound.set(
  88156. localSpherePos.x + sphereRadius,
  88157. localSpherePos.y + sphereRadius,
  88158. localSpherePos.z + sphereRadius
  88159. );
  88160. trimeshShape.getTrianglesInAABB(localSphereAABB, triangles);
  88161. //for (var i = 0; i < trimeshShape.indices.length / 3; i++) triangles.push(i); // All
  88162. // Vertices
  88163. var v = sphereTrimesh_v;
  88164. var radiusSquared = sphereShape.radius * sphereShape.radius;
  88165. for(var i=0; i<triangles.length; i++){
  88166. for (var j = 0; j < 3; j++) {
  88167. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], v);
  88168. // Check vertex overlap in sphere
  88169. v.vsub(localSpherePos, relpos);
  88170. if(relpos.norm2() <= radiusSquared){
  88171. // Safe up
  88172. v2.copy(v);
  88173. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);
  88174. v.vsub(spherePos, relpos);
  88175. var r = this.createContactEquation(sphereBody,trimeshBody,sphereShape,trimeshShape);
  88176. r.ni.copy(relpos);
  88177. r.ni.normalize();
  88178. // ri is the vector from sphere center to the sphere surface
  88179. r.ri.copy(r.ni);
  88180. r.ri.scale(sphereShape.radius, r.ri);
  88181. r.ri.vadd(spherePos, r.ri);
  88182. r.ri.vsub(sphereBody.position, r.ri);
  88183. r.rj.copy(v);
  88184. r.rj.vsub(trimeshBody.position, r.rj);
  88185. // Store result
  88186. this.result.push(r);
  88187. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88188. }
  88189. }
  88190. }
  88191. // Check all edges
  88192. for(var i=0; i<triangles.length; i++){
  88193. for (var j = 0; j < 3; j++) {
  88194. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], edgeVertexA);
  88195. trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + ((j+1)%3)], edgeVertexB);
  88196. edgeVertexB.vsub(edgeVertexA, edgeVector);
  88197. // Project sphere position to the edge
  88198. localSpherePos.vsub(edgeVertexB, tmp);
  88199. var positionAlongEdgeB = tmp.dot(edgeVector);
  88200. localSpherePos.vsub(edgeVertexA, tmp);
  88201. var positionAlongEdgeA = tmp.dot(edgeVector);
  88202. if(positionAlongEdgeA > 0 && positionAlongEdgeB < 0){
  88203. // Now check the orthogonal distance from edge to sphere center
  88204. localSpherePos.vsub(edgeVertexA, tmp);
  88205. edgeVectorUnit.copy(edgeVector);
  88206. edgeVectorUnit.normalize();
  88207. positionAlongEdgeA = tmp.dot(edgeVectorUnit);
  88208. edgeVectorUnit.scale(positionAlongEdgeA, tmp);
  88209. tmp.vadd(edgeVertexA, tmp);
  88210. // tmp is now the sphere center position projected to the edge, defined locally in the trimesh frame
  88211. var dist = tmp.distanceTo(localSpherePos);
  88212. if(dist < sphereShape.radius){
  88213. var r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape);
  88214. tmp.vsub(localSpherePos, r.ni);
  88215. r.ni.normalize();
  88216. r.ni.scale(sphereShape.radius, r.ri);
  88217. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
  88218. tmp.vsub(trimeshBody.position, r.rj);
  88219. Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
  88220. Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
  88221. this.result.push(r);
  88222. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88223. }
  88224. }
  88225. }
  88226. }
  88227. // Triangle faces
  88228. var va = sphereTrimesh_va;
  88229. var vb = sphereTrimesh_vb;
  88230. var vc = sphereTrimesh_vc;
  88231. var normal = sphereTrimesh_normal;
  88232. for(var i=0, N = triangles.length; i !== N; i++){
  88233. trimeshShape.getTriangleVertices(triangles[i], va, vb, vc);
  88234. trimeshShape.getNormal(triangles[i], normal);
  88235. localSpherePos.vsub(va, tmp);
  88236. var dist = tmp.dot(normal);
  88237. normal.scale(dist, tmp);
  88238. localSpherePos.vsub(tmp, tmp);
  88239. // tmp is now the sphere position projected to the triangle plane
  88240. dist = tmp.distanceTo(localSpherePos);
  88241. if(Ray.pointInTriangle(tmp, va, vb, vc) && dist < sphereShape.radius){
  88242. var r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape);
  88243. tmp.vsub(localSpherePos, r.ni);
  88244. r.ni.normalize();
  88245. r.ni.scale(sphereShape.radius, r.ri);
  88246. Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
  88247. tmp.vsub(trimeshBody.position, r.rj);
  88248. Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
  88249. Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);
  88250. this.result.push(r);
  88251. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88252. }
  88253. }
  88254. triangles.length = 0;
  88255. };
  88256. var point_on_plane_to_sphere = new Vec3();
  88257. var plane_to_sphere_ortho = new Vec3();
  88258. /**
  88259. * @method spherePlane
  88260. * @param {Shape} si
  88261. * @param {Shape} sj
  88262. * @param {Vec3} xi
  88263. * @param {Vec3} xj
  88264. * @param {Quaternion} qi
  88265. * @param {Quaternion} qj
  88266. * @param {Body} bi
  88267. * @param {Body} bj
  88268. */
  88269. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.PLANE] =
  88270. Narrowphase.prototype.spherePlane = function(si,sj,xi,xj,qi,qj,bi,bj){
  88271. // We will have one contact in this case
  88272. var r = this.createContactEquation(bi,bj,si,sj);
  88273. // Contact normal
  88274. r.ni.set(0,0,1);
  88275. qj.vmult(r.ni, r.ni);
  88276. r.ni.negate(r.ni); // body i is the sphere, flip normal
  88277. r.ni.normalize(); // Needed?
  88278. // Vector from sphere center to contact point
  88279. r.ni.mult(si.radius, r.ri);
  88280. // Project down sphere on plane
  88281. xi.vsub(xj, point_on_plane_to_sphere);
  88282. r.ni.mult(r.ni.dot(point_on_plane_to_sphere), plane_to_sphere_ortho);
  88283. point_on_plane_to_sphere.vsub(plane_to_sphere_ortho,r.rj); // The sphere position projected to plane
  88284. if(-point_on_plane_to_sphere.dot(r.ni) <= si.radius){
  88285. // Make it relative to the body
  88286. var ri = r.ri;
  88287. var rj = r.rj;
  88288. ri.vadd(xi, ri);
  88289. ri.vsub(bi.position, ri);
  88290. rj.vadd(xj, rj);
  88291. rj.vsub(bj.position, rj);
  88292. this.result.push(r);
  88293. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88294. }
  88295. };
  88296. // See http://bulletphysics.com/Bullet/BulletFull/SphereTriangleDetector_8cpp_source.html
  88297. var pointInPolygon_edge = new Vec3();
  88298. var pointInPolygon_edge_x_normal = new Vec3();
  88299. var pointInPolygon_vtp = new Vec3();
  88300. function pointInPolygon(verts, normal, p){
  88301. var positiveResult = null;
  88302. var N = verts.length;
  88303. for(var i=0; i!==N; i++){
  88304. var v = verts[i];
  88305. // Get edge to the next vertex
  88306. var edge = pointInPolygon_edge;
  88307. verts[(i+1) % (N)].vsub(v,edge);
  88308. // Get cross product between polygon normal and the edge
  88309. var edge_x_normal = pointInPolygon_edge_x_normal;
  88310. //var edge_x_normal = new Vec3();
  88311. edge.cross(normal,edge_x_normal);
  88312. // Get vector between point and current vertex
  88313. var vertex_to_p = pointInPolygon_vtp;
  88314. p.vsub(v,vertex_to_p);
  88315. // This dot product determines which side of the edge the point is
  88316. var r = edge_x_normal.dot(vertex_to_p);
  88317. // If all such dot products have same sign, we are inside the polygon.
  88318. if(positiveResult===null || (r>0 && positiveResult===true) || (r<=0 && positiveResult===false)){
  88319. if(positiveResult===null){
  88320. positiveResult = r>0;
  88321. }
  88322. continue;
  88323. } else {
  88324. return false; // Encountered some other sign. Exit.
  88325. }
  88326. }
  88327. // If we got here, all dot products were of the same sign.
  88328. return true;
  88329. }
  88330. var box_to_sphere = new Vec3();
  88331. var sphereBox_ns = new Vec3();
  88332. var sphereBox_ns1 = new Vec3();
  88333. var sphereBox_ns2 = new Vec3();
  88334. var sphereBox_sides = [new Vec3(),new Vec3(),new Vec3(),new Vec3(),new Vec3(),new Vec3()];
  88335. var sphereBox_sphere_to_corner = new Vec3();
  88336. var sphereBox_side_ns = new Vec3();
  88337. var sphereBox_side_ns1 = new Vec3();
  88338. var sphereBox_side_ns2 = new Vec3();
  88339. /**
  88340. * @method sphereBox
  88341. * @param {Shape} si
  88342. * @param {Shape} sj
  88343. * @param {Vec3} xi
  88344. * @param {Vec3} xj
  88345. * @param {Quaternion} qi
  88346. * @param {Quaternion} qj
  88347. * @param {Body} bi
  88348. * @param {Body} bj
  88349. */
  88350. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.BOX] =
  88351. Narrowphase.prototype.sphereBox = function(si,sj,xi,xj,qi,qj,bi,bj){
  88352. var v3pool = this.v3pool;
  88353. // we refer to the box as body j
  88354. var sides = sphereBox_sides;
  88355. xi.vsub(xj,box_to_sphere);
  88356. sj.getSideNormals(sides,qj);
  88357. var R = si.radius;
  88358. var penetrating_sides = [];
  88359. // Check side (plane) intersections
  88360. var found = false;
  88361. // Store the resulting side penetration info
  88362. var side_ns = sphereBox_side_ns;
  88363. var side_ns1 = sphereBox_side_ns1;
  88364. var side_ns2 = sphereBox_side_ns2;
  88365. var side_h = null;
  88366. var side_penetrations = 0;
  88367. var side_dot1 = 0;
  88368. var side_dot2 = 0;
  88369. var side_distance = null;
  88370. for(var idx=0,nsides=sides.length; idx!==nsides && found===false; idx++){
  88371. // Get the plane side normal (ns)
  88372. var ns = sphereBox_ns;
  88373. ns.copy(sides[idx]);
  88374. var h = ns.norm();
  88375. ns.normalize();
  88376. // The normal/distance dot product tells which side of the plane we are
  88377. var dot = box_to_sphere.dot(ns);
  88378. if(dot<h+R && dot>0){
  88379. // Intersects plane. Now check the other two dimensions
  88380. var ns1 = sphereBox_ns1;
  88381. var ns2 = sphereBox_ns2;
  88382. ns1.copy(sides[(idx+1)%3]);
  88383. ns2.copy(sides[(idx+2)%3]);
  88384. var h1 = ns1.norm();
  88385. var h2 = ns2.norm();
  88386. ns1.normalize();
  88387. ns2.normalize();
  88388. var dot1 = box_to_sphere.dot(ns1);
  88389. var dot2 = box_to_sphere.dot(ns2);
  88390. if(dot1<h1 && dot1>-h1 && dot2<h2 && dot2>-h2){
  88391. var dist = Math.abs(dot-h-R);
  88392. if(side_distance===null || dist < side_distance){
  88393. side_distance = dist;
  88394. side_dot1 = dot1;
  88395. side_dot2 = dot2;
  88396. side_h = h;
  88397. side_ns.copy(ns);
  88398. side_ns1.copy(ns1);
  88399. side_ns2.copy(ns2);
  88400. side_penetrations++;
  88401. }
  88402. }
  88403. }
  88404. }
  88405. if(side_penetrations){
  88406. found = true;
  88407. var r = this.createContactEquation(bi,bj,si,sj);
  88408. side_ns.mult(-R,r.ri); // Sphere r
  88409. r.ni.copy(side_ns);
  88410. r.ni.negate(r.ni); // Normal should be out of sphere
  88411. side_ns.mult(side_h,side_ns);
  88412. side_ns1.mult(side_dot1,side_ns1);
  88413. side_ns.vadd(side_ns1,side_ns);
  88414. side_ns2.mult(side_dot2,side_ns2);
  88415. side_ns.vadd(side_ns2,r.rj);
  88416. // Make relative to bodies
  88417. r.ri.vadd(xi, r.ri);
  88418. r.ri.vsub(bi.position, r.ri);
  88419. r.rj.vadd(xj, r.rj);
  88420. r.rj.vsub(bj.position, r.rj);
  88421. this.result.push(r);
  88422. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88423. }
  88424. // Check corners
  88425. var rj = v3pool.get();
  88426. var sphere_to_corner = sphereBox_sphere_to_corner;
  88427. for(var j=0; j!==2 && !found; j++){
  88428. for(var k=0; k!==2 && !found; k++){
  88429. for(var l=0; l!==2 && !found; l++){
  88430. rj.set(0,0,0);
  88431. if(j){
  88432. rj.vadd(sides[0],rj);
  88433. } else {
  88434. rj.vsub(sides[0],rj);
  88435. }
  88436. if(k){
  88437. rj.vadd(sides[1],rj);
  88438. } else {
  88439. rj.vsub(sides[1],rj);
  88440. }
  88441. if(l){
  88442. rj.vadd(sides[2],rj);
  88443. } else {
  88444. rj.vsub(sides[2],rj);
  88445. }
  88446. // World position of corner
  88447. xj.vadd(rj,sphere_to_corner);
  88448. sphere_to_corner.vsub(xi,sphere_to_corner);
  88449. if(sphere_to_corner.norm2() < R*R){
  88450. found = true;
  88451. var r = this.createContactEquation(bi,bj,si,sj);
  88452. r.ri.copy(sphere_to_corner);
  88453. r.ri.normalize();
  88454. r.ni.copy(r.ri);
  88455. r.ri.mult(R,r.ri);
  88456. r.rj.copy(rj);
  88457. // Make relative to bodies
  88458. r.ri.vadd(xi, r.ri);
  88459. r.ri.vsub(bi.position, r.ri);
  88460. r.rj.vadd(xj, r.rj);
  88461. r.rj.vsub(bj.position, r.rj);
  88462. this.result.push(r);
  88463. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88464. }
  88465. }
  88466. }
  88467. }
  88468. v3pool.release(rj);
  88469. rj = null;
  88470. // Check edges
  88471. var edgeTangent = v3pool.get();
  88472. var edgeCenter = v3pool.get();
  88473. var r = v3pool.get(); // r = edge center to sphere center
  88474. var orthogonal = v3pool.get();
  88475. var dist = v3pool.get();
  88476. var Nsides = sides.length;
  88477. for(var j=0; j!==Nsides && !found; j++){
  88478. for(var k=0; k!==Nsides && !found; k++){
  88479. if(j%3 !== k%3){
  88480. // Get edge tangent
  88481. sides[k].cross(sides[j],edgeTangent);
  88482. edgeTangent.normalize();
  88483. sides[j].vadd(sides[k], edgeCenter);
  88484. r.copy(xi);
  88485. r.vsub(edgeCenter,r);
  88486. r.vsub(xj,r);
  88487. var orthonorm = r.dot(edgeTangent); // distance from edge center to sphere center in the tangent direction
  88488. edgeTangent.mult(orthonorm,orthogonal); // Vector from edge center to sphere center in the tangent direction
  88489. // Find the third side orthogonal to this one
  88490. var l = 0;
  88491. while(l===j%3 || l===k%3){
  88492. l++;
  88493. }
  88494. // vec from edge center to sphere projected to the plane orthogonal to the edge tangent
  88495. dist.copy(xi);
  88496. dist.vsub(orthogonal,dist);
  88497. dist.vsub(edgeCenter,dist);
  88498. dist.vsub(xj,dist);
  88499. // Distances in tangent direction and distance in the plane orthogonal to it
  88500. var tdist = Math.abs(orthonorm);
  88501. var ndist = dist.norm();
  88502. if(tdist < sides[l].norm() && ndist<R){
  88503. found = true;
  88504. var res = this.createContactEquation(bi,bj,si,sj);
  88505. edgeCenter.vadd(orthogonal,res.rj); // box rj
  88506. res.rj.copy(res.rj);
  88507. dist.negate(res.ni);
  88508. res.ni.normalize();
  88509. res.ri.copy(res.rj);
  88510. res.ri.vadd(xj,res.ri);
  88511. res.ri.vsub(xi,res.ri);
  88512. res.ri.normalize();
  88513. res.ri.mult(R,res.ri);
  88514. // Make relative to bodies
  88515. res.ri.vadd(xi, res.ri);
  88516. res.ri.vsub(bi.position, res.ri);
  88517. res.rj.vadd(xj, res.rj);
  88518. res.rj.vsub(bj.position, res.rj);
  88519. this.result.push(res);
  88520. this.createFrictionEquationsFromContact(res, this.frictionResult);
  88521. }
  88522. }
  88523. }
  88524. }
  88525. v3pool.release(edgeTangent,edgeCenter,r,orthogonal,dist);
  88526. };
  88527. var convex_to_sphere = new Vec3();
  88528. var sphereConvex_edge = new Vec3();
  88529. var sphereConvex_edgeUnit = new Vec3();
  88530. var sphereConvex_sphereToCorner = new Vec3();
  88531. var sphereConvex_worldCorner = new Vec3();
  88532. var sphereConvex_worldNormal = new Vec3();
  88533. var sphereConvex_worldPoint = new Vec3();
  88534. var sphereConvex_worldSpherePointClosestToPlane = new Vec3();
  88535. var sphereConvex_penetrationVec = new Vec3();
  88536. var sphereConvex_sphereToWorldPoint = new Vec3();
  88537. /**
  88538. * @method sphereConvex
  88539. * @param {Shape} si
  88540. * @param {Shape} sj
  88541. * @param {Vec3} xi
  88542. * @param {Vec3} xj
  88543. * @param {Quaternion} qi
  88544. * @param {Quaternion} qj
  88545. * @param {Body} bi
  88546. * @param {Body} bj
  88547. */
  88548. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.CONVEXPOLYHEDRON] =
  88549. Narrowphase.prototype.sphereConvex = function(si,sj,xi,xj,qi,qj,bi,bj){
  88550. var v3pool = this.v3pool;
  88551. xi.vsub(xj,convex_to_sphere);
  88552. var normals = sj.faceNormals;
  88553. var faces = sj.faces;
  88554. var verts = sj.vertices;
  88555. var R = si.radius;
  88556. var penetrating_sides = [];
  88557. // if(convex_to_sphere.norm2() > si.boundingSphereRadius + sj.boundingSphereRadius){
  88558. // return;
  88559. // }
  88560. // Check corners
  88561. for(var i=0; i!==verts.length; i++){
  88562. var v = verts[i];
  88563. // World position of corner
  88564. var worldCorner = sphereConvex_worldCorner;
  88565. qj.vmult(v,worldCorner);
  88566. xj.vadd(worldCorner,worldCorner);
  88567. var sphere_to_corner = sphereConvex_sphereToCorner;
  88568. worldCorner.vsub(xi, sphere_to_corner);
  88569. if(sphere_to_corner.norm2() < R * R){
  88570. found = true;
  88571. var r = this.createContactEquation(bi,bj,si,sj);
  88572. r.ri.copy(sphere_to_corner);
  88573. r.ri.normalize();
  88574. r.ni.copy(r.ri);
  88575. r.ri.mult(R,r.ri);
  88576. worldCorner.vsub(xj,r.rj);
  88577. // Should be relative to the body.
  88578. r.ri.vadd(xi, r.ri);
  88579. r.ri.vsub(bi.position, r.ri);
  88580. // Should be relative to the body.
  88581. r.rj.vadd(xj, r.rj);
  88582. r.rj.vsub(bj.position, r.rj);
  88583. this.result.push(r);
  88584. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88585. return;
  88586. }
  88587. }
  88588. // Check side (plane) intersections
  88589. var found = false;
  88590. for(var i=0, nfaces=faces.length; i!==nfaces && found===false; i++){
  88591. var normal = normals[i];
  88592. var face = faces[i];
  88593. // Get world-transformed normal of the face
  88594. var worldNormal = sphereConvex_worldNormal;
  88595. qj.vmult(normal,worldNormal);
  88596. // Get a world vertex from the face
  88597. var worldPoint = sphereConvex_worldPoint;
  88598. qj.vmult(verts[face[0]],worldPoint);
  88599. worldPoint.vadd(xj,worldPoint);
  88600. // Get a point on the sphere, closest to the face normal
  88601. var worldSpherePointClosestToPlane = sphereConvex_worldSpherePointClosestToPlane;
  88602. worldNormal.mult(-R, worldSpherePointClosestToPlane);
  88603. xi.vadd(worldSpherePointClosestToPlane, worldSpherePointClosestToPlane);
  88604. // Vector from a face point to the closest point on the sphere
  88605. var penetrationVec = sphereConvex_penetrationVec;
  88606. worldSpherePointClosestToPlane.vsub(worldPoint,penetrationVec);
  88607. // The penetration. Negative value means overlap.
  88608. var penetration = penetrationVec.dot(worldNormal);
  88609. var worldPointToSphere = sphereConvex_sphereToWorldPoint;
  88610. xi.vsub(worldPoint, worldPointToSphere);
  88611. if(penetration < 0 && worldPointToSphere.dot(worldNormal)>0){
  88612. // Intersects plane. Now check if the sphere is inside the face polygon
  88613. var faceVerts = []; // Face vertices, in world coords
  88614. for(var j=0, Nverts=face.length; j!==Nverts; j++){
  88615. var worldVertex = v3pool.get();
  88616. qj.vmult(verts[face[j]], worldVertex);
  88617. xj.vadd(worldVertex,worldVertex);
  88618. faceVerts.push(worldVertex);
  88619. }
  88620. if(pointInPolygon(faceVerts,worldNormal,xi)){ // Is the sphere center in the face polygon?
  88621. found = true;
  88622. var r = this.createContactEquation(bi,bj,si,sj);
  88623. worldNormal.mult(-R, r.ri); // Contact offset, from sphere center to contact
  88624. worldNormal.negate(r.ni); // Normal pointing out of sphere
  88625. var penetrationVec2 = v3pool.get();
  88626. worldNormal.mult(-penetration, penetrationVec2);
  88627. var penetrationSpherePoint = v3pool.get();
  88628. worldNormal.mult(-R, penetrationSpherePoint);
  88629. //xi.vsub(xj).vadd(penetrationSpherePoint).vadd(penetrationVec2 , r.rj);
  88630. xi.vsub(xj,r.rj);
  88631. r.rj.vadd(penetrationSpherePoint,r.rj);
  88632. r.rj.vadd(penetrationVec2 , r.rj);
  88633. // Should be relative to the body.
  88634. r.rj.vadd(xj, r.rj);
  88635. r.rj.vsub(bj.position, r.rj);
  88636. // Should be relative to the body.
  88637. r.ri.vadd(xi, r.ri);
  88638. r.ri.vsub(bi.position, r.ri);
  88639. v3pool.release(penetrationVec2);
  88640. v3pool.release(penetrationSpherePoint);
  88641. this.result.push(r);
  88642. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88643. // Release world vertices
  88644. for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
  88645. v3pool.release(faceVerts[j]);
  88646. }
  88647. return; // We only expect *one* face contact
  88648. } else {
  88649. // Edge?
  88650. for(var j=0; j!==face.length; j++){
  88651. // Get two world transformed vertices
  88652. var v1 = v3pool.get();
  88653. var v2 = v3pool.get();
  88654. qj.vmult(verts[face[(j+1)%face.length]], v1);
  88655. qj.vmult(verts[face[(j+2)%face.length]], v2);
  88656. xj.vadd(v1, v1);
  88657. xj.vadd(v2, v2);
  88658. // Construct edge vector
  88659. var edge = sphereConvex_edge;
  88660. v2.vsub(v1,edge);
  88661. // Construct the same vector, but normalized
  88662. var edgeUnit = sphereConvex_edgeUnit;
  88663. edge.unit(edgeUnit);
  88664. // p is xi projected onto the edge
  88665. var p = v3pool.get();
  88666. var v1_to_xi = v3pool.get();
  88667. xi.vsub(v1, v1_to_xi);
  88668. var dot = v1_to_xi.dot(edgeUnit);
  88669. edgeUnit.mult(dot, p);
  88670. p.vadd(v1, p);
  88671. // Compute a vector from p to the center of the sphere
  88672. var xi_to_p = v3pool.get();
  88673. p.vsub(xi, xi_to_p);
  88674. // Collision if the edge-sphere distance is less than the radius
  88675. // AND if p is in between v1 and v2
  88676. if(dot > 0 && dot*dot<edge.norm2() && xi_to_p.norm2() < R*R){ // Collision if the edge-sphere distance is less than the radius
  88677. // Edge contact!
  88678. var r = this.createContactEquation(bi,bj,si,sj);
  88679. p.vsub(xj,r.rj);
  88680. p.vsub(xi,r.ni);
  88681. r.ni.normalize();
  88682. r.ni.mult(R,r.ri);
  88683. // Should be relative to the body.
  88684. r.rj.vadd(xj, r.rj);
  88685. r.rj.vsub(bj.position, r.rj);
  88686. // Should be relative to the body.
  88687. r.ri.vadd(xi, r.ri);
  88688. r.ri.vsub(bi.position, r.ri);
  88689. this.result.push(r);
  88690. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88691. // Release world vertices
  88692. for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
  88693. v3pool.release(faceVerts[j]);
  88694. }
  88695. v3pool.release(v1);
  88696. v3pool.release(v2);
  88697. v3pool.release(p);
  88698. v3pool.release(xi_to_p);
  88699. v3pool.release(v1_to_xi);
  88700. return;
  88701. }
  88702. v3pool.release(v1);
  88703. v3pool.release(v2);
  88704. v3pool.release(p);
  88705. v3pool.release(xi_to_p);
  88706. v3pool.release(v1_to_xi);
  88707. }
  88708. }
  88709. // Release world vertices
  88710. for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
  88711. v3pool.release(faceVerts[j]);
  88712. }
  88713. }
  88714. }
  88715. };
  88716. var planeBox_normal = new Vec3();
  88717. var plane_to_corner = new Vec3();
  88718. /**
  88719. * @method planeBox
  88720. * @param {Array} result
  88721. * @param {Shape} si
  88722. * @param {Shape} sj
  88723. * @param {Vec3} xi
  88724. * @param {Vec3} xj
  88725. * @param {Quaternion} qi
  88726. * @param {Quaternion} qj
  88727. * @param {Body} bi
  88728. * @param {Body} bj
  88729. */
  88730. Narrowphase.prototype[Shape.types.PLANE | Shape.types.BOX] =
  88731. Narrowphase.prototype.planeBox = function(si,sj,xi,xj,qi,qj,bi,bj){
  88732. sj.convexPolyhedronRepresentation.material = sj.material;
  88733. sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
  88734. this.planeConvex(si,sj.convexPolyhedronRepresentation,xi,xj,qi,qj,bi,bj);
  88735. };
  88736. var planeConvex_v = new Vec3();
  88737. var planeConvex_normal = new Vec3();
  88738. var planeConvex_relpos = new Vec3();
  88739. var planeConvex_projected = new Vec3();
  88740. /**
  88741. * @method planeConvex
  88742. * @param {Shape} si
  88743. * @param {Shape} sj
  88744. * @param {Vec3} xi
  88745. * @param {Vec3} xj
  88746. * @param {Quaternion} qi
  88747. * @param {Quaternion} qj
  88748. * @param {Body} bi
  88749. * @param {Body} bj
  88750. */
  88751. Narrowphase.prototype[Shape.types.PLANE | Shape.types.CONVEXPOLYHEDRON] =
  88752. Narrowphase.prototype.planeConvex = function(
  88753. planeShape,
  88754. convexShape,
  88755. planePosition,
  88756. convexPosition,
  88757. planeQuat,
  88758. convexQuat,
  88759. planeBody,
  88760. convexBody
  88761. ){
  88762. // Simply return the points behind the plane.
  88763. var worldVertex = planeConvex_v,
  88764. worldNormal = planeConvex_normal;
  88765. worldNormal.set(0,0,1);
  88766. planeQuat.vmult(worldNormal,worldNormal); // Turn normal according to plane orientation
  88767. var numContacts = 0;
  88768. var relpos = planeConvex_relpos;
  88769. for(var i = 0; i !== convexShape.vertices.length; i++){
  88770. // Get world convex vertex
  88771. worldVertex.copy(convexShape.vertices[i]);
  88772. convexQuat.vmult(worldVertex, worldVertex);
  88773. convexPosition.vadd(worldVertex, worldVertex);
  88774. worldVertex.vsub(planePosition, relpos);
  88775. var dot = worldNormal.dot(relpos);
  88776. if(dot <= 0.0){
  88777. var r = this.createContactEquation(planeBody, convexBody, planeShape, convexShape);
  88778. // Get vertex position projected on plane
  88779. var projected = planeConvex_projected;
  88780. worldNormal.mult(worldNormal.dot(relpos),projected);
  88781. worldVertex.vsub(projected, projected);
  88782. projected.vsub(planePosition, r.ri); // From plane to vertex projected on plane
  88783. r.ni.copy(worldNormal); // Contact normal is the plane normal out from plane
  88784. // rj is now just the vector from the convex center to the vertex
  88785. worldVertex.vsub(convexPosition, r.rj);
  88786. // Make it relative to the body
  88787. r.ri.vadd(planePosition, r.ri);
  88788. r.ri.vsub(planeBody.position, r.ri);
  88789. r.rj.vadd(convexPosition, r.rj);
  88790. r.rj.vsub(convexBody.position, r.rj);
  88791. this.result.push(r);
  88792. numContacts++;
  88793. if(!this.enableFrictionReduction){
  88794. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88795. }
  88796. }
  88797. }
  88798. if(this.enableFrictionReduction && numContacts){
  88799. this.createFrictionFromAverage(numContacts);
  88800. }
  88801. };
  88802. var convexConvex_sepAxis = new Vec3();
  88803. var convexConvex_q = new Vec3();
  88804. /**
  88805. * @method convexConvex
  88806. * @param {Shape} si
  88807. * @param {Shape} sj
  88808. * @param {Vec3} xi
  88809. * @param {Vec3} xj
  88810. * @param {Quaternion} qi
  88811. * @param {Quaternion} qj
  88812. * @param {Body} bi
  88813. * @param {Body} bj
  88814. */
  88815. Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON] =
  88816. Narrowphase.prototype.convexConvex = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,faceListA,faceListB){
  88817. var sepAxis = convexConvex_sepAxis;
  88818. if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  88819. return;
  88820. }
  88821. if(si.findSeparatingAxis(sj,xi,qi,xj,qj,sepAxis,faceListA,faceListB)){
  88822. var res = [];
  88823. var q = convexConvex_q;
  88824. si.clipAgainstHull(xi,qi,sj,xj,qj,sepAxis,-100,100,res);
  88825. var numContacts = 0;
  88826. for(var j = 0; j !== res.length; j++){
  88827. var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),
  88828. ri = r.ri,
  88829. rj = r.rj;
  88830. sepAxis.negate(r.ni);
  88831. res[j].normal.negate(q);
  88832. q.mult(res[j].depth, q);
  88833. res[j].point.vadd(q, ri);
  88834. rj.copy(res[j].point);
  88835. // Contact points are in world coordinates. Transform back to relative
  88836. ri.vsub(xi,ri);
  88837. rj.vsub(xj,rj);
  88838. // Make relative to bodies
  88839. ri.vadd(xi, ri);
  88840. ri.vsub(bi.position, ri);
  88841. rj.vadd(xj, rj);
  88842. rj.vsub(bj.position, rj);
  88843. this.result.push(r);
  88844. numContacts++;
  88845. if(!this.enableFrictionReduction){
  88846. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88847. }
  88848. }
  88849. if(this.enableFrictionReduction && numContacts){
  88850. this.createFrictionFromAverage(numContacts);
  88851. }
  88852. }
  88853. };
  88854. /**
  88855. * @method convexTrimesh
  88856. * @param {Array} result
  88857. * @param {Shape} si
  88858. * @param {Shape} sj
  88859. * @param {Vec3} xi
  88860. * @param {Vec3} xj
  88861. * @param {Quaternion} qi
  88862. * @param {Quaternion} qj
  88863. * @param {Body} bi
  88864. * @param {Body} bj
  88865. */
  88866. // Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON | Shape.types.TRIMESH] =
  88867. // Narrowphase.prototype.convexTrimesh = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,faceListA,faceListB){
  88868. // var sepAxis = convexConvex_sepAxis;
  88869. // if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
  88870. // return;
  88871. // }
  88872. // // Construct a temp hull for each triangle
  88873. // var hullB = new ConvexPolyhedron();
  88874. // hullB.faces = [[0,1,2]];
  88875. // var va = new Vec3();
  88876. // var vb = new Vec3();
  88877. // var vc = new Vec3();
  88878. // hullB.vertices = [
  88879. // va,
  88880. // vb,
  88881. // vc
  88882. // ];
  88883. // for (var i = 0; i < sj.indices.length / 3; i++) {
  88884. // var triangleNormal = new Vec3();
  88885. // sj.getNormal(i, triangleNormal);
  88886. // hullB.faceNormals = [triangleNormal];
  88887. // sj.getTriangleVertices(i, va, vb, vc);
  88888. // var d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  88889. // if(!d){
  88890. // triangleNormal.scale(-1, triangleNormal);
  88891. // d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
  88892. // if(!d){
  88893. // continue;
  88894. // }
  88895. // }
  88896. // var res = [];
  88897. // var q = convexConvex_q;
  88898. // si.clipAgainstHull(xi,qi,hullB,xj,qj,triangleNormal,-100,100,res);
  88899. // for(var j = 0; j !== res.length; j++){
  88900. // var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),
  88901. // ri = r.ri,
  88902. // rj = r.rj;
  88903. // r.ni.copy(triangleNormal);
  88904. // r.ni.negate(r.ni);
  88905. // res[j].normal.negate(q);
  88906. // q.mult(res[j].depth, q);
  88907. // res[j].point.vadd(q, ri);
  88908. // rj.copy(res[j].point);
  88909. // // Contact points are in world coordinates. Transform back to relative
  88910. // ri.vsub(xi,ri);
  88911. // rj.vsub(xj,rj);
  88912. // // Make relative to bodies
  88913. // ri.vadd(xi, ri);
  88914. // ri.vsub(bi.position, ri);
  88915. // rj.vadd(xj, rj);
  88916. // rj.vsub(bj.position, rj);
  88917. // result.push(r);
  88918. // }
  88919. // }
  88920. // };
  88921. var particlePlane_normal = new Vec3();
  88922. var particlePlane_relpos = new Vec3();
  88923. var particlePlane_projected = new Vec3();
  88924. /**
  88925. * @method particlePlane
  88926. * @param {Array} result
  88927. * @param {Shape} si
  88928. * @param {Shape} sj
  88929. * @param {Vec3} xi
  88930. * @param {Vec3} xj
  88931. * @param {Quaternion} qi
  88932. * @param {Quaternion} qj
  88933. * @param {Body} bi
  88934. * @param {Body} bj
  88935. */
  88936. Narrowphase.prototype[Shape.types.PLANE | Shape.types.PARTICLE] =
  88937. Narrowphase.prototype.planeParticle = function(sj,si,xj,xi,qj,qi,bj,bi){
  88938. var normal = particlePlane_normal;
  88939. normal.set(0,0,1);
  88940. bj.quaternion.vmult(normal,normal); // Turn normal according to plane orientation
  88941. var relpos = particlePlane_relpos;
  88942. xi.vsub(bj.position,relpos);
  88943. var dot = normal.dot(relpos);
  88944. if(dot <= 0.0){
  88945. var r = this.createContactEquation(bi,bj,si,sj);
  88946. r.ni.copy(normal); // Contact normal is the plane normal
  88947. r.ni.negate(r.ni);
  88948. r.ri.set(0,0,0); // Center of particle
  88949. // Get particle position projected on plane
  88950. var projected = particlePlane_projected;
  88951. normal.mult(normal.dot(xi),projected);
  88952. xi.vsub(projected,projected);
  88953. //projected.vadd(bj.position,projected);
  88954. // rj is now the projected world position minus plane position
  88955. r.rj.copy(projected);
  88956. this.result.push(r);
  88957. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88958. }
  88959. };
  88960. var particleSphere_normal = new Vec3();
  88961. /**
  88962. * @method particleSphere
  88963. * @param {Array} result
  88964. * @param {Shape} si
  88965. * @param {Shape} sj
  88966. * @param {Vec3} xi
  88967. * @param {Vec3} xj
  88968. * @param {Quaternion} qi
  88969. * @param {Quaternion} qj
  88970. * @param {Body} bi
  88971. * @param {Body} bj
  88972. */
  88973. Narrowphase.prototype[Shape.types.PARTICLE | Shape.types.SPHERE] =
  88974. Narrowphase.prototype.sphereParticle = function(sj,si,xj,xi,qj,qi,bj,bi){
  88975. // The normal is the unit vector from sphere center to particle center
  88976. var normal = particleSphere_normal;
  88977. normal.set(0,0,1);
  88978. xi.vsub(xj,normal);
  88979. var lengthSquared = normal.norm2();
  88980. if(lengthSquared <= sj.radius * sj.radius){
  88981. var r = this.createContactEquation(bi,bj,si,sj);
  88982. normal.normalize();
  88983. r.rj.copy(normal);
  88984. r.rj.mult(sj.radius,r.rj);
  88985. r.ni.copy(normal); // Contact normal
  88986. r.ni.negate(r.ni);
  88987. r.ri.set(0,0,0); // Center of particle
  88988. this.result.push(r);
  88989. this.createFrictionEquationsFromContact(r, this.frictionResult);
  88990. }
  88991. };
  88992. // WIP
  88993. var cqj = new Quaternion();
  88994. var convexParticle_local = new Vec3();
  88995. var convexParticle_normal = new Vec3();
  88996. var convexParticle_penetratedFaceNormal = new Vec3();
  88997. var convexParticle_vertexToParticle = new Vec3();
  88998. var convexParticle_worldPenetrationVec = new Vec3();
  88999. /**
  89000. * @method convexParticle
  89001. * @param {Array} result
  89002. * @param {Shape} si
  89003. * @param {Shape} sj
  89004. * @param {Vec3} xi
  89005. * @param {Vec3} xj
  89006. * @param {Quaternion} qi
  89007. * @param {Quaternion} qj
  89008. * @param {Body} bi
  89009. * @param {Body} bj
  89010. */
  89011. Narrowphase.prototype[Shape.types.PARTICLE | Shape.types.CONVEXPOLYHEDRON] =
  89012. Narrowphase.prototype.convexParticle = function(sj,si,xj,xi,qj,qi,bj,bi){
  89013. var penetratedFaceIndex = -1;
  89014. var penetratedFaceNormal = convexParticle_penetratedFaceNormal;
  89015. var worldPenetrationVec = convexParticle_worldPenetrationVec;
  89016. var minPenetration = null;
  89017. var numDetectedFaces = 0;
  89018. // Convert particle position xi to local coords in the convex
  89019. var local = convexParticle_local;
  89020. local.copy(xi);
  89021. local.vsub(xj,local); // Convert position to relative the convex origin
  89022. qj.conjugate(cqj);
  89023. cqj.vmult(local,local);
  89024. if(sj.pointIsInside(local)){
  89025. if(sj.worldVerticesNeedsUpdate){
  89026. sj.computeWorldVertices(xj,qj);
  89027. }
  89028. if(sj.worldFaceNormalsNeedsUpdate){
  89029. sj.computeWorldFaceNormals(qj);
  89030. }
  89031. // For each world polygon in the polyhedra
  89032. for(var i=0,nfaces=sj.faces.length; i!==nfaces; i++){
  89033. // Construct world face vertices
  89034. var verts = [ sj.worldVertices[ sj.faces[i][0] ] ];
  89035. var normal = sj.worldFaceNormals[i];
  89036. // Check how much the particle penetrates the polygon plane.
  89037. xi.vsub(verts[0],convexParticle_vertexToParticle);
  89038. var penetration = -normal.dot(convexParticle_vertexToParticle);
  89039. if(minPenetration===null || Math.abs(penetration)<Math.abs(minPenetration)){
  89040. minPenetration = penetration;
  89041. penetratedFaceIndex = i;
  89042. penetratedFaceNormal.copy(normal);
  89043. numDetectedFaces++;
  89044. }
  89045. }
  89046. if(penetratedFaceIndex!==-1){
  89047. // Setup contact
  89048. var r = this.createContactEquation(bi,bj,si,sj);
  89049. penetratedFaceNormal.mult(minPenetration, worldPenetrationVec);
  89050. // rj is the particle position projected to the face
  89051. worldPenetrationVec.vadd(xi,worldPenetrationVec);
  89052. worldPenetrationVec.vsub(xj,worldPenetrationVec);
  89053. r.rj.copy(worldPenetrationVec);
  89054. //var projectedToFace = xi.vsub(xj).vadd(worldPenetrationVec);
  89055. //projectedToFace.copy(r.rj);
  89056. //qj.vmult(r.rj,r.rj);
  89057. penetratedFaceNormal.negate( r.ni ); // Contact normal
  89058. r.ri.set(0,0,0); // Center of particle
  89059. var ri = r.ri,
  89060. rj = r.rj;
  89061. // Make relative to bodies
  89062. ri.vadd(xi, ri);
  89063. ri.vsub(bi.position, ri);
  89064. rj.vadd(xj, rj);
  89065. rj.vsub(bj.position, rj);
  89066. this.result.push(r);
  89067. this.createFrictionEquationsFromContact(r, this.frictionResult);
  89068. } else {
  89069. console.warn("Point found inside convex, but did not find penetrating face!");
  89070. }
  89071. }
  89072. };
  89073. Narrowphase.prototype[Shape.types.BOX | Shape.types.HEIGHTFIELD] =
  89074. Narrowphase.prototype.boxHeightfield = function (si,sj,xi,xj,qi,qj,bi,bj){
  89075. si.convexPolyhedronRepresentation.material = si.material;
  89076. si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
  89077. this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj);
  89078. };
  89079. var convexHeightfield_tmp1 = new Vec3();
  89080. var convexHeightfield_tmp2 = new Vec3();
  89081. var convexHeightfield_faceList = [0];
  89082. /**
  89083. * @method convexHeightfield
  89084. */
  89085. Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON | Shape.types.HEIGHTFIELD] =
  89086. Narrowphase.prototype.convexHeightfield = function (
  89087. convexShape,
  89088. hfShape,
  89089. convexPos,
  89090. hfPos,
  89091. convexQuat,
  89092. hfQuat,
  89093. convexBody,
  89094. hfBody
  89095. ){
  89096. var data = hfShape.data,
  89097. w = hfShape.elementSize,
  89098. radius = convexShape.boundingSphereRadius,
  89099. worldPillarOffset = convexHeightfield_tmp2,
  89100. faceList = convexHeightfield_faceList;
  89101. // Get sphere position to heightfield local!
  89102. var localConvexPos = convexHeightfield_tmp1;
  89103. Transform.pointToLocalFrame(hfPos, hfQuat, convexPos, localConvexPos);
  89104. // Get the index of the data points to test against
  89105. var iMinX = Math.floor((localConvexPos.x - radius) / w) - 1,
  89106. iMaxX = Math.ceil((localConvexPos.x + radius) / w) + 1,
  89107. iMinY = Math.floor((localConvexPos.y - radius) / w) - 1,
  89108. iMaxY = Math.ceil((localConvexPos.y + radius) / w) + 1;
  89109. // Bail out if we are out of the terrain
  89110. if(iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length){
  89111. return;
  89112. }
  89113. // Clamp index to edges
  89114. if(iMinX < 0){ iMinX = 0; }
  89115. if(iMaxX < 0){ iMaxX = 0; }
  89116. if(iMinY < 0){ iMinY = 0; }
  89117. if(iMaxY < 0){ iMaxY = 0; }
  89118. if(iMinX >= data.length){ iMinX = data.length - 1; }
  89119. if(iMaxX >= data.length){ iMaxX = data.length - 1; }
  89120. if(iMaxY >= data[0].length){ iMaxY = data[0].length - 1; }
  89121. if(iMinY >= data[0].length){ iMinY = data[0].length - 1; }
  89122. var minMax = [];
  89123. hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  89124. var min = minMax[0];
  89125. var max = minMax[1];
  89126. // Bail out if we're cant touch the bounding height box
  89127. if(localConvexPos.z - radius > max || localConvexPos.z + radius < min){
  89128. return;
  89129. }
  89130. for(var i = iMinX; i < iMaxX; i++){
  89131. for(var j = iMinY; j < iMaxY; j++){
  89132. // Lower triangle
  89133. hfShape.getConvexTrianglePillar(i, j, false);
  89134. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  89135. if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
  89136. this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, faceList, null);
  89137. }
  89138. // Upper triangle
  89139. hfShape.getConvexTrianglePillar(i, j, true);
  89140. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  89141. if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
  89142. this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, null, null, faceList, null);
  89143. }
  89144. }
  89145. }
  89146. };
  89147. var sphereHeightfield_tmp1 = new Vec3();
  89148. var sphereHeightfield_tmp2 = new Vec3();
  89149. /**
  89150. * @method sphereHeightfield
  89151. */
  89152. Narrowphase.prototype[Shape.types.SPHERE | Shape.types.HEIGHTFIELD] =
  89153. Narrowphase.prototype.sphereHeightfield = function (
  89154. sphereShape,
  89155. hfShape,
  89156. spherePos,
  89157. hfPos,
  89158. sphereQuat,
  89159. hfQuat,
  89160. sphereBody,
  89161. hfBody
  89162. ){
  89163. var data = hfShape.data,
  89164. radius = sphereShape.radius,
  89165. w = hfShape.elementSize,
  89166. worldPillarOffset = sphereHeightfield_tmp2;
  89167. // Get sphere position to heightfield local!
  89168. var localSpherePos = sphereHeightfield_tmp1;
  89169. Transform.pointToLocalFrame(hfPos, hfQuat, spherePos, localSpherePos);
  89170. // Get the index of the data points to test against
  89171. var iMinX = Math.floor((localSpherePos.x - radius) / w) - 1,
  89172. iMaxX = Math.ceil((localSpherePos.x + radius) / w) + 1,
  89173. iMinY = Math.floor((localSpherePos.y - radius) / w) - 1,
  89174. iMaxY = Math.ceil((localSpherePos.y + radius) / w) + 1;
  89175. // Bail out if we are out of the terrain
  89176. if(iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMaxY > data[0].length){
  89177. return;
  89178. }
  89179. // Clamp index to edges
  89180. if(iMinX < 0){ iMinX = 0; }
  89181. if(iMaxX < 0){ iMaxX = 0; }
  89182. if(iMinY < 0){ iMinY = 0; }
  89183. if(iMaxY < 0){ iMaxY = 0; }
  89184. if(iMinX >= data.length){ iMinX = data.length - 1; }
  89185. if(iMaxX >= data.length){ iMaxX = data.length - 1; }
  89186. if(iMaxY >= data[0].length){ iMaxY = data[0].length - 1; }
  89187. if(iMinY >= data[0].length){ iMinY = data[0].length - 1; }
  89188. var minMax = [];
  89189. hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
  89190. var min = minMax[0];
  89191. var max = minMax[1];
  89192. // Bail out if we're cant touch the bounding height box
  89193. if(localSpherePos.z - radius > max || localSpherePos.z + radius < min){
  89194. return;
  89195. }
  89196. var result = this.result;
  89197. for(var i = iMinX; i < iMaxX; i++){
  89198. for(var j = iMinY; j < iMaxY; j++){
  89199. var numContactsBefore = result.length;
  89200. // Lower triangle
  89201. hfShape.getConvexTrianglePillar(i, j, false);
  89202. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  89203. if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
  89204. this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody);
  89205. }
  89206. // Upper triangle
  89207. hfShape.getConvexTrianglePillar(i, j, true);
  89208. Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
  89209. if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
  89210. this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody);
  89211. }
  89212. var numContacts = result.length - numContactsBefore;
  89213. if(numContacts > 2){
  89214. return;
  89215. }
  89216. /*
  89217. // Skip all but 1
  89218. for (var k = 0; k < numContacts - 1; k++) {
  89219. result.pop();
  89220. }
  89221. */
  89222. }
  89223. }
  89224. };
  89225. },{"../collision/AABB":3,"../collision/Ray":9,"../equations/ContactEquation":19,"../equations/FrictionEquation":21,"../math/Quaternion":28,"../math/Transform":29,"../math/Vec3":30,"../shapes/ConvexPolyhedron":38,"../shapes/Shape":43,"../solver/Solver":47,"../utils/Vec3Pool":54}],56:[function(_dereq_,module,exports){
  89226. /* global performance */
  89227. module.exports = World;
  89228. var Shape = _dereq_('../shapes/Shape');
  89229. var Vec3 = _dereq_('../math/Vec3');
  89230. var Quaternion = _dereq_('../math/Quaternion');
  89231. var GSSolver = _dereq_('../solver/GSSolver');
  89232. var Vec3Pool = _dereq_('../utils/Vec3Pool');
  89233. var ContactEquation = _dereq_('../equations/ContactEquation');
  89234. var FrictionEquation = _dereq_('../equations/FrictionEquation');
  89235. var Narrowphase = _dereq_('./Narrowphase');
  89236. var EventTarget = _dereq_('../utils/EventTarget');
  89237. var ArrayCollisionMatrix = _dereq_('../collision/ArrayCollisionMatrix');
  89238. var Material = _dereq_('../material/Material');
  89239. var ContactMaterial = _dereq_('../material/ContactMaterial');
  89240. var Body = _dereq_('../objects/Body');
  89241. var TupleDictionary = _dereq_('../utils/TupleDictionary');
  89242. var RaycastResult = _dereq_('../collision/RaycastResult');
  89243. var AABB = _dereq_('../collision/AABB');
  89244. var Ray = _dereq_('../collision/Ray');
  89245. var NaiveBroadphase = _dereq_('../collision/NaiveBroadphase');
  89246. /**
  89247. * The physics world
  89248. * @class World
  89249. * @constructor
  89250. * @extends EventTarget
  89251. */
  89252. function World(){
  89253. EventTarget.apply(this);
  89254. /**
  89255. * Currently / last used timestep. Is set to -1 if not available. This value is updated before each internal step, which means that it is "fresh" inside event callbacks.
  89256. * @property {Number} dt
  89257. */
  89258. this.dt = -1;
  89259. /**
  89260. * Makes bodies go to sleep when they've been inactive
  89261. * @property allowSleep
  89262. * @type {Boolean}
  89263. */
  89264. this.allowSleep = false;
  89265. /**
  89266. * All the current contacts (instances of ContactEquation) in the world.
  89267. * @property contacts
  89268. * @type {Array}
  89269. */
  89270. this.contacts = [];
  89271. this.frictionEquations = [];
  89272. /**
  89273. * How often to normalize quaternions. Set to 0 for every step, 1 for every second etc.. A larger value increases performance. If bodies tend to explode, set to a smaller value (zero to be sure nothing can go wrong).
  89274. * @property quatNormalizeSkip
  89275. * @type {Number}
  89276. */
  89277. this.quatNormalizeSkip = 0;
  89278. /**
  89279. * Set to true to use fast quaternion normalization. It is often enough accurate to use. If bodies tend to explode, set to false.
  89280. * @property quatNormalizeFast
  89281. * @type {Boolean}
  89282. * @see Quaternion.normalizeFast
  89283. * @see Quaternion.normalize
  89284. */
  89285. this.quatNormalizeFast = false;
  89286. /**
  89287. * The wall-clock time since simulation start
  89288. * @property time
  89289. * @type {Number}
  89290. */
  89291. this.time = 0.0;
  89292. /**
  89293. * Number of timesteps taken since start
  89294. * @property stepnumber
  89295. * @type {Number}
  89296. */
  89297. this.stepnumber = 0;
  89298. /// Default and last timestep sizes
  89299. this.default_dt = 1/60;
  89300. this.nextId = 0;
  89301. /**
  89302. * @property gravity
  89303. * @type {Vec3}
  89304. */
  89305. this.gravity = new Vec3();
  89306. /**
  89307. * @property broadphase
  89308. * @type {Broadphase}
  89309. */
  89310. this.broadphase = new NaiveBroadphase();
  89311. /**
  89312. * @property bodies
  89313. * @type {Array}
  89314. */
  89315. this.bodies = [];
  89316. /**
  89317. * @property solver
  89318. * @type {Solver}
  89319. */
  89320. this.solver = new GSSolver();
  89321. /**
  89322. * @property constraints
  89323. * @type {Array}
  89324. */
  89325. this.constraints = [];
  89326. /**
  89327. * @property narrowphase
  89328. * @type {Narrowphase}
  89329. */
  89330. this.narrowphase = new Narrowphase(this);
  89331. /**
  89332. * @property {ArrayCollisionMatrix} collisionMatrix
  89333. * @type {ArrayCollisionMatrix}
  89334. */
  89335. this.collisionMatrix = new ArrayCollisionMatrix();
  89336. /**
  89337. * CollisionMatrix from the previous step.
  89338. * @property {ArrayCollisionMatrix} collisionMatrixPrevious
  89339. * @type {ArrayCollisionMatrix}
  89340. */
  89341. this.collisionMatrixPrevious = new ArrayCollisionMatrix();
  89342. /**
  89343. * All added materials
  89344. * @property materials
  89345. * @type {Array}
  89346. */
  89347. this.materials = [];
  89348. /**
  89349. * @property contactmaterials
  89350. * @type {Array}
  89351. */
  89352. this.contactmaterials = [];
  89353. /**
  89354. * Used to look up a ContactMaterial given two instances of Material.
  89355. * @property {TupleDictionary} contactMaterialTable
  89356. */
  89357. this.contactMaterialTable = new TupleDictionary();
  89358. this.defaultMaterial = new Material("default");
  89359. /**
  89360. * This contact material is used if no suitable contactmaterial is found for a contact.
  89361. * @property defaultContactMaterial
  89362. * @type {ContactMaterial}
  89363. */
  89364. this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial, this.defaultMaterial, { friction: 0.3, restitution: 0.0 });
  89365. /**
  89366. * @property doProfiling
  89367. * @type {Boolean}
  89368. */
  89369. this.doProfiling = false;
  89370. /**
  89371. * @property profile
  89372. * @type {Object}
  89373. */
  89374. this.profile = {
  89375. solve:0,
  89376. makeContactConstraints:0,
  89377. broadphase:0,
  89378. integrate:0,
  89379. narrowphase:0,
  89380. };
  89381. /**
  89382. * @property subsystems
  89383. * @type {Array}
  89384. */
  89385. this.subsystems = [];
  89386. this.addBodyEvent = {
  89387. type:"addBody",
  89388. body : null,
  89389. };
  89390. this.removeBodyEvent = {
  89391. type:"removeBody",
  89392. body : null,
  89393. };
  89394. }
  89395. World.prototype = new EventTarget();
  89396. // Temp stuff
  89397. var tmpAABB1 = new AABB();
  89398. var tmpArray1 = [];
  89399. var tmpRay = new Ray();
  89400. /**
  89401. * Get the contact material between materials m1 and m2
  89402. * @method getContactMaterial
  89403. * @param {Material} m1
  89404. * @param {Material} m2
  89405. * @return {ContactMaterial} The contact material if it was found.
  89406. */
  89407. World.prototype.getContactMaterial = function(m1,m2){
  89408. return this.contactMaterialTable.get(m1.id,m2.id); //this.contactmaterials[this.mats2cmat[i+j*this.materials.length]];
  89409. };
  89410. /**
  89411. * Get number of objects in the world.
  89412. * @method numObjects
  89413. * @return {Number}
  89414. * @deprecated
  89415. */
  89416. World.prototype.numObjects = function(){
  89417. return this.bodies.length;
  89418. };
  89419. /**
  89420. * Store old collision state info
  89421. * @method collisionMatrixTick
  89422. */
  89423. World.prototype.collisionMatrixTick = function(){
  89424. var temp = this.collisionMatrixPrevious;
  89425. this.collisionMatrixPrevious = this.collisionMatrix;
  89426. this.collisionMatrix = temp;
  89427. this.collisionMatrix.reset();
  89428. };
  89429. /**
  89430. * Add a rigid body to the simulation.
  89431. * @method add
  89432. * @param {Body} body
  89433. * @todo If the simulation has not yet started, why recrete and copy arrays for each body? Accumulate in dynamic arrays in this case.
  89434. * @todo Adding an array of bodies should be possible. This would save some loops too
  89435. * @deprecated Use .addBody instead
  89436. */
  89437. World.prototype.add = World.prototype.addBody = function(body){
  89438. if(this.bodies.indexOf(body) !== -1){
  89439. return;
  89440. }
  89441. body.index = this.bodies.length;
  89442. this.bodies.push(body);
  89443. body.world = this;
  89444. body.initPosition.copy(body.position);
  89445. body.initVelocity.copy(body.velocity);
  89446. body.timeLastSleepy = this.time;
  89447. if(body instanceof Body){
  89448. body.initAngularVelocity.copy(body.angularVelocity);
  89449. body.initQuaternion.copy(body.quaternion);
  89450. }
  89451. this.collisionMatrix.setNumObjects(this.bodies.length);
  89452. this.addBodyEvent.body = body;
  89453. this.dispatchEvent(this.addBodyEvent);
  89454. };
  89455. /**
  89456. * Add a constraint to the simulation.
  89457. * @method addConstraint
  89458. * @param {Constraint} c
  89459. */
  89460. World.prototype.addConstraint = function(c){
  89461. this.constraints.push(c);
  89462. };
  89463. /**
  89464. * Removes a constraint
  89465. * @method removeConstraint
  89466. * @param {Constraint} c
  89467. */
  89468. World.prototype.removeConstraint = function(c){
  89469. var idx = this.constraints.indexOf(c);
  89470. if(idx!==-1){
  89471. this.constraints.splice(idx,1);
  89472. }
  89473. };
  89474. /**
  89475. * Raycast test
  89476. * @method rayTest
  89477. * @param {Vec3} from
  89478. * @param {Vec3} to
  89479. * @param {Function|RaycastResult} result
  89480. * @deprecated Use .raycastAll, .raycastClosest or .raycastAny instead.
  89481. */
  89482. World.prototype.rayTest = function(from, to, result){
  89483. if(result instanceof RaycastResult){
  89484. // Do raycastclosest
  89485. this.raycastClosest(from, to, {
  89486. skipBackfaces: true
  89487. }, result);
  89488. } else {
  89489. // Do raycastAll
  89490. this.raycastAll(from, to, {
  89491. skipBackfaces: true
  89492. }, result);
  89493. }
  89494. };
  89495. /**
  89496. * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument.
  89497. * @method raycastAll
  89498. * @param {Vec3} from
  89499. * @param {Vec3} to
  89500. * @param {Object} options
  89501. * @param {number} [options.collisionFilterMask=-1]
  89502. * @param {number} [options.collisionFilterGroup=-1]
  89503. * @param {boolean} [options.skipBackfaces=false]
  89504. * @param {boolean} [options.checkCollisionResponse=true]
  89505. * @param {Function} callback
  89506. * @return {boolean} True if any body was hit.
  89507. */
  89508. World.prototype.raycastAll = function(from, to, options, callback){
  89509. options.mode = Ray.ALL;
  89510. options.from = from;
  89511. options.to = to;
  89512. options.callback = callback;
  89513. return tmpRay.intersectWorld(this, options);
  89514. };
  89515. /**
  89516. * Ray cast, and stop at the first result. Note that the order is random - but the method is fast.
  89517. * @method raycastAny
  89518. * @param {Vec3} from
  89519. * @param {Vec3} to
  89520. * @param {Object} options
  89521. * @param {number} [options.collisionFilterMask=-1]
  89522. * @param {number} [options.collisionFilterGroup=-1]
  89523. * @param {boolean} [options.skipBackfaces=false]
  89524. * @param {boolean} [options.checkCollisionResponse=true]
  89525. * @param {RaycastResult} result
  89526. * @return {boolean} True if any body was hit.
  89527. */
  89528. World.prototype.raycastAny = function(from, to, options, result){
  89529. options.mode = Ray.ANY;
  89530. options.from = from;
  89531. options.to = to;
  89532. options.result = result;
  89533. return tmpRay.intersectWorld(this, options);
  89534. };
  89535. /**
  89536. * Ray cast, and return information of the closest hit.
  89537. * @method raycastClosest
  89538. * @param {Vec3} from
  89539. * @param {Vec3} to
  89540. * @param {Object} options
  89541. * @param {number} [options.collisionFilterMask=-1]
  89542. * @param {number} [options.collisionFilterGroup=-1]
  89543. * @param {boolean} [options.skipBackfaces=false]
  89544. * @param {boolean} [options.checkCollisionResponse=true]
  89545. * @param {RaycastResult} result
  89546. * @return {boolean} True if any body was hit.
  89547. */
  89548. World.prototype.raycastClosest = function(from, to, options, result){
  89549. options.mode = Ray.CLOSEST;
  89550. options.from = from;
  89551. options.to = to;
  89552. options.result = result;
  89553. return tmpRay.intersectWorld(this, options);
  89554. };
  89555. /**
  89556. * Remove a rigid body from the simulation.
  89557. * @method remove
  89558. * @param {Body} body
  89559. * @deprecated Use .removeBody instead
  89560. */
  89561. World.prototype.remove = function(body){
  89562. body.world = null;
  89563. var n = this.bodies.length-1,
  89564. bodies = this.bodies,
  89565. idx = bodies.indexOf(body);
  89566. if(idx !== -1){
  89567. bodies.splice(idx, 1); // Todo: should use a garbage free method
  89568. // Recompute index
  89569. for(var i=0; i!==bodies.length; i++){
  89570. bodies[i].index = i;
  89571. }
  89572. this.collisionMatrix.setNumObjects(n);
  89573. this.removeBodyEvent.body = body;
  89574. this.dispatchEvent(this.removeBodyEvent);
  89575. }
  89576. };
  89577. /**
  89578. * Remove a rigid body from the simulation.
  89579. * @method removeBody
  89580. * @param {Body} body
  89581. */
  89582. World.prototype.removeBody = World.prototype.remove;
  89583. /**
  89584. * Adds a material to the World.
  89585. * @method addMaterial
  89586. * @param {Material} m
  89587. * @todo Necessary?
  89588. */
  89589. World.prototype.addMaterial = function(m){
  89590. this.materials.push(m);
  89591. };
  89592. /**
  89593. * Adds a contact material to the World
  89594. * @method addContactMaterial
  89595. * @param {ContactMaterial} cmat
  89596. */
  89597. World.prototype.addContactMaterial = function(cmat) {
  89598. // Add contact material
  89599. this.contactmaterials.push(cmat);
  89600. // Add current contact material to the material table
  89601. this.contactMaterialTable.set(cmat.materials[0].id,cmat.materials[1].id,cmat);
  89602. };
  89603. // performance.now()
  89604. if(typeof performance === 'undefined'){
  89605. performance = {};
  89606. }
  89607. if(!performance.now){
  89608. var nowOffset = Date.now();
  89609. if (performance.timing && performance.timing.navigationStart){
  89610. nowOffset = performance.timing.navigationStart;
  89611. }
  89612. performance.now = function(){
  89613. return Date.now() - nowOffset;
  89614. };
  89615. }
  89616. var step_tmp1 = new Vec3();
  89617. /**
  89618. * Step the physics world forward in time.
  89619. *
  89620. * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take.
  89621. *
  89622. * @method step
  89623. * @param {Number} dt The fixed time step size to use.
  89624. * @param {Number} [timeSinceLastCalled] The time elapsed since the function was last called.
  89625. * @param {Number} [maxSubSteps=10] Maximum number of fixed steps to take per function call.
  89626. *
  89627. * @example
  89628. * // fixed timestepping without interpolation
  89629. * world.step(1/60);
  89630. *
  89631. * @see http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World
  89632. */
  89633. World.prototype.step = function(dt, timeSinceLastCalled, maxSubSteps){
  89634. maxSubSteps = maxSubSteps || 10;
  89635. timeSinceLastCalled = timeSinceLastCalled || 0;
  89636. if(timeSinceLastCalled === 0){ // Fixed, simple stepping
  89637. this.internalStep(dt);
  89638. // Increment time
  89639. this.time += dt;
  89640. } else {
  89641. // Compute the number of fixed steps we should have taken since the last step
  89642. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  89643. internalSteps = Math.min(internalSteps,maxSubSteps);
  89644. // Do some fixed steps to catch up
  89645. var t0 = performance.now();
  89646. for(var i=0; i!==internalSteps; i++){
  89647. this.internalStep(dt);
  89648. if(performance.now() - t0 > dt * 1000){
  89649. // We are slower than real-time. Better bail out.
  89650. break;
  89651. }
  89652. }
  89653. // Increment internal clock
  89654. this.time += timeSinceLastCalled;
  89655. // Compute "Left over" time step
  89656. var h = this.time % dt;
  89657. var h_div_dt = h / dt;
  89658. var interpvelo = step_tmp1;
  89659. var bodies = this.bodies;
  89660. for(var j=0; j !== bodies.length; j++){
  89661. var b = bodies[j];
  89662. if(b.type !== Body.STATIC && b.sleepState !== Body.SLEEPING){
  89663. // Interpolate
  89664. b.position.vsub(b.previousPosition, interpvelo);
  89665. interpvelo.scale(h_div_dt, interpvelo);
  89666. b.position.vadd(interpvelo, b.interpolatedPosition);
  89667. // TODO: interpolate quaternion
  89668. // b.interpolatedAngle = b.angle + (b.angle - b.previousAngle) * h_div_dt;
  89669. } else {
  89670. // For static bodies, just copy. Who else will do it?
  89671. b.interpolatedPosition.copy(b.position);
  89672. b.interpolatedQuaternion.copy(b.quaternion);
  89673. }
  89674. }
  89675. }
  89676. };
  89677. /**
  89678. * Step the simulation
  89679. * @method step
  89680. * @param {Number} dt
  89681. */
  89682. var World_step_postStepEvent = {type:"postStep"}, // Reusable event objects to save memory
  89683. World_step_preStepEvent = {type:"preStep"},
  89684. World_step_collideEvent = {type:"collide", body:null, contact:null },
  89685. World_step_oldContacts = [], // Pools for unused objects
  89686. World_step_frictionEquationPool = [],
  89687. World_step_p1 = [], // Reusable arrays for collision pairs
  89688. World_step_p2 = [],
  89689. World_step_gvec = new Vec3(), // Temporary vectors and quats
  89690. World_step_vi = new Vec3(),
  89691. World_step_vj = new Vec3(),
  89692. World_step_wi = new Vec3(),
  89693. World_step_wj = new Vec3(),
  89694. World_step_t1 = new Vec3(),
  89695. World_step_t2 = new Vec3(),
  89696. World_step_rixn = new Vec3(),
  89697. World_step_rjxn = new Vec3(),
  89698. World_step_step_q = new Quaternion(),
  89699. World_step_step_w = new Quaternion(),
  89700. World_step_step_wq = new Quaternion(),
  89701. invI_tau_dt = new Vec3();
  89702. World.prototype.internalStep = function(dt){
  89703. this.dt = dt;
  89704. var world = this,
  89705. that = this,
  89706. contacts = this.contacts,
  89707. p1 = World_step_p1,
  89708. p2 = World_step_p2,
  89709. N = this.numObjects(),
  89710. bodies = this.bodies,
  89711. solver = this.solver,
  89712. gravity = this.gravity,
  89713. doProfiling = this.doProfiling,
  89714. profile = this.profile,
  89715. DYNAMIC = Body.DYNAMIC,
  89716. profilingStart,
  89717. constraints = this.constraints,
  89718. frictionEquationPool = World_step_frictionEquationPool,
  89719. gnorm = gravity.norm(),
  89720. gx = gravity.x,
  89721. gy = gravity.y,
  89722. gz = gravity.z,
  89723. i=0;
  89724. if(doProfiling){
  89725. profilingStart = performance.now();
  89726. }
  89727. // Add gravity to all objects
  89728. for(i=0; i!==N; i++){
  89729. var bi = bodies[i];
  89730. if(bi.type & DYNAMIC){ // Only for dynamic bodies
  89731. var f = bi.force, m = bi.mass;
  89732. f.x += m*gx;
  89733. f.y += m*gy;
  89734. f.z += m*gz;
  89735. }
  89736. }
  89737. // Update subsystems
  89738. for(var i=0, Nsubsystems=this.subsystems.length; i!==Nsubsystems; i++){
  89739. this.subsystems[i].update();
  89740. }
  89741. // Collision detection
  89742. if(doProfiling){ profilingStart = performance.now(); }
  89743. p1.length = 0; // Clean up pair arrays from last step
  89744. p2.length = 0;
  89745. this.broadphase.collisionPairs(this,p1,p2);
  89746. if(doProfiling){ profile.broadphase = performance.now() - profilingStart; }
  89747. // Remove constrained pairs with collideConnected == false
  89748. var Nconstraints = constraints.length;
  89749. for(i=0; i!==Nconstraints; i++){
  89750. var c = constraints[i];
  89751. if(!c.collideConnected){
  89752. for(var j = p1.length-1; j>=0; j-=1){
  89753. if( (c.bodyA === p1[j] && c.bodyB === p2[j]) ||
  89754. (c.bodyB === p1[j] && c.bodyA === p2[j])){
  89755. p1.splice(j, 1);
  89756. p2.splice(j, 1);
  89757. }
  89758. }
  89759. }
  89760. }
  89761. this.collisionMatrixTick();
  89762. // Generate contacts
  89763. if(doProfiling){ profilingStart = performance.now(); }
  89764. var oldcontacts = World_step_oldContacts;
  89765. var NoldContacts = contacts.length;
  89766. for(i=0; i!==NoldContacts; i++){
  89767. oldcontacts.push(contacts[i]);
  89768. }
  89769. contacts.length = 0;
  89770. // Transfer FrictionEquation from current list to the pool for reuse
  89771. var NoldFrictionEquations = this.frictionEquations.length;
  89772. for(i=0; i!==NoldFrictionEquations; i++){
  89773. frictionEquationPool.push(this.frictionEquations[i]);
  89774. }
  89775. this.frictionEquations.length = 0;
  89776. this.narrowphase.getContacts(
  89777. p1,
  89778. p2,
  89779. this,
  89780. contacts,
  89781. oldcontacts, // To be reused
  89782. this.frictionEquations,
  89783. frictionEquationPool
  89784. );
  89785. if(doProfiling){
  89786. profile.narrowphase = performance.now() - profilingStart;
  89787. }
  89788. // Loop over all collisions
  89789. if(doProfiling){
  89790. profilingStart = performance.now();
  89791. }
  89792. // Add all friction eqs
  89793. for (var i = 0; i < this.frictionEquations.length; i++) {
  89794. solver.addEquation(this.frictionEquations[i]);
  89795. }
  89796. var ncontacts = contacts.length;
  89797. for(var k=0; k!==ncontacts; k++){
  89798. // Current contact
  89799. var c = contacts[k];
  89800. // Get current collision indeces
  89801. var bi = c.bi,
  89802. bj = c.bj,
  89803. si = c.si,
  89804. sj = c.sj;
  89805. // Get collision properties
  89806. var cm;
  89807. if(bi.material && bj.material){
  89808. cm = this.getContactMaterial(bi.material,bj.material) || this.defaultContactMaterial;
  89809. } else {
  89810. cm = this.defaultContactMaterial;
  89811. }
  89812. // c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  89813. var mu = cm.friction;
  89814. // c.restitution = cm.restitution;
  89815. // If friction or restitution were specified in the material, use them
  89816. if(bi.material && bj.material){
  89817. if(bi.material.friction >= 0 && bj.material.friction >= 0){
  89818. mu = bi.material.friction * bj.material.friction;
  89819. }
  89820. if(bi.material.restitution >= 0 && bj.material.restitution >= 0){
  89821. c.restitution = bi.material.restitution * bj.material.restitution;
  89822. }
  89823. }
  89824. // c.setSpookParams(
  89825. // cm.contactEquationStiffness,
  89826. // cm.contactEquationRelaxation,
  89827. // dt
  89828. // );
  89829. solver.addEquation(c);
  89830. // // Add friction constraint equation
  89831. // if(mu > 0){
  89832. // // Create 2 tangent equations
  89833. // var mug = mu * gnorm;
  89834. // var reducedMass = (bi.invMass + bj.invMass);
  89835. // if(reducedMass > 0){
  89836. // reducedMass = 1/reducedMass;
  89837. // }
  89838. // var pool = frictionEquationPool;
  89839. // var c1 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
  89840. // var c2 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
  89841. // this.frictionEquations.push(c1, c2);
  89842. // c1.bi = c2.bi = bi;
  89843. // c1.bj = c2.bj = bj;
  89844. // c1.minForce = c2.minForce = -mug*reducedMass;
  89845. // c1.maxForce = c2.maxForce = mug*reducedMass;
  89846. // // Copy over the relative vectors
  89847. // c1.ri.copy(c.ri);
  89848. // c1.rj.copy(c.rj);
  89849. // c2.ri.copy(c.ri);
  89850. // c2.rj.copy(c.rj);
  89851. // // Construct tangents
  89852. // c.ni.tangents(c1.t, c2.t);
  89853. // // Set spook params
  89854. // c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
  89855. // c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
  89856. // c1.enabled = c2.enabled = c.enabled;
  89857. // // Add equations to solver
  89858. // solver.addEquation(c1);
  89859. // solver.addEquation(c2);
  89860. // }
  89861. if( bi.allowSleep &&
  89862. bi.type === Body.DYNAMIC &&
  89863. bi.sleepState === Body.SLEEPING &&
  89864. bj.sleepState === Body.AWAKE &&
  89865. bj.type !== Body.STATIC
  89866. ){
  89867. var speedSquaredB = bj.velocity.norm2() + bj.angularVelocity.norm2();
  89868. var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2);
  89869. if(speedSquaredB >= speedLimitSquaredB*2){
  89870. bi._wakeUpAfterNarrowphase = true;
  89871. }
  89872. }
  89873. if( bj.allowSleep &&
  89874. bj.type === Body.DYNAMIC &&
  89875. bj.sleepState === Body.SLEEPING &&
  89876. bi.sleepState === Body.AWAKE &&
  89877. bi.type !== Body.STATIC
  89878. ){
  89879. var speedSquaredA = bi.velocity.norm2() + bi.angularVelocity.norm2();
  89880. var speedLimitSquaredA = Math.pow(bi.sleepSpeedLimit,2);
  89881. if(speedSquaredA >= speedLimitSquaredA*2){
  89882. bj._wakeUpAfterNarrowphase = true;
  89883. }
  89884. }
  89885. // Now we know that i and j are in contact. Set collision matrix state
  89886. this.collisionMatrix.set(bi, bj, true);
  89887. if (!this.collisionMatrixPrevious.get(bi, bj)) {
  89888. // First contact!
  89889. // We reuse the collideEvent object, otherwise we will end up creating new objects for each new contact, even if there's no event listener attached.
  89890. World_step_collideEvent.body = bj;
  89891. World_step_collideEvent.contact = c;
  89892. bi.dispatchEvent(World_step_collideEvent);
  89893. World_step_collideEvent.body = bi;
  89894. bj.dispatchEvent(World_step_collideEvent);
  89895. }
  89896. }
  89897. if(doProfiling){
  89898. profile.makeContactConstraints = performance.now() - profilingStart;
  89899. profilingStart = performance.now();
  89900. }
  89901. // Wake up bodies
  89902. for(i=0; i!==N; i++){
  89903. var bi = bodies[i];
  89904. if(bi._wakeUpAfterNarrowphase){
  89905. bi.wakeUp();
  89906. bi._wakeUpAfterNarrowphase = false;
  89907. }
  89908. }
  89909. // Add user-added constraints
  89910. var Nconstraints = constraints.length;
  89911. for(i=0; i!==Nconstraints; i++){
  89912. var c = constraints[i];
  89913. c.update();
  89914. for(var j=0, Neq=c.equations.length; j!==Neq; j++){
  89915. var eq = c.equations[j];
  89916. solver.addEquation(eq);
  89917. }
  89918. }
  89919. // Solve the constrained system
  89920. solver.solve(dt,this);
  89921. if(doProfiling){
  89922. profile.solve = performance.now() - profilingStart;
  89923. }
  89924. // Remove all contacts from solver
  89925. solver.removeAllEquations();
  89926. // Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details
  89927. var pow = Math.pow;
  89928. for(i=0; i!==N; i++){
  89929. var bi = bodies[i];
  89930. if(bi.type & DYNAMIC){ // Only for dynamic bodies
  89931. var ld = pow(1.0 - bi.linearDamping,dt);
  89932. var v = bi.velocity;
  89933. v.mult(ld,v);
  89934. var av = bi.angularVelocity;
  89935. if(av){
  89936. var ad = pow(1.0 - bi.angularDamping,dt);
  89937. av.mult(ad,av);
  89938. }
  89939. }
  89940. }
  89941. this.dispatchEvent(World_step_preStepEvent);
  89942. // Invoke pre-step callbacks
  89943. for(i=0; i!==N; i++){
  89944. var bi = bodies[i];
  89945. if(bi.preStep){
  89946. bi.preStep.call(bi);
  89947. }
  89948. }
  89949. // Leap frog
  89950. // vnew = v + h*f/m
  89951. // xnew = x + h*vnew
  89952. if(doProfiling){
  89953. profilingStart = performance.now();
  89954. }
  89955. var q = World_step_step_q;
  89956. var w = World_step_step_w;
  89957. var wq = World_step_step_wq;
  89958. var stepnumber = this.stepnumber;
  89959. var DYNAMIC_OR_KINEMATIC = Body.DYNAMIC | Body.KINEMATIC;
  89960. var quatNormalize = stepnumber % (this.quatNormalizeSkip+1) === 0;
  89961. var quatNormalizeFast = this.quatNormalizeFast;
  89962. var half_dt = dt * 0.5;
  89963. var PLANE = Shape.types.PLANE,
  89964. CONVEX = Shape.types.CONVEXPOLYHEDRON;
  89965. for(i=0; i!==N; i++){
  89966. var b = bodies[i],
  89967. force = b.force,
  89968. tau = b.torque;
  89969. if((b.type & DYNAMIC_OR_KINEMATIC) && b.sleepState !== Body.SLEEPING){ // Only for dynamic
  89970. var velo = b.velocity,
  89971. angularVelo = b.angularVelocity,
  89972. pos = b.position,
  89973. quat = b.quaternion,
  89974. invMass = b.invMass,
  89975. invInertia = b.invInertiaWorld;
  89976. velo.x += force.x * invMass * dt;
  89977. velo.y += force.y * invMass * dt;
  89978. velo.z += force.z * invMass * dt;
  89979. if(b.angularVelocity){
  89980. invInertia.vmult(tau,invI_tau_dt);
  89981. invI_tau_dt.mult(dt,invI_tau_dt);
  89982. invI_tau_dt.vadd(angularVelo,angularVelo);
  89983. }
  89984. // Use new velocity - leap frog
  89985. pos.x += velo.x * dt;
  89986. pos.y += velo.y * dt;
  89987. pos.z += velo.z * dt;
  89988. if(b.angularVelocity){
  89989. w.set(angularVelo.x, angularVelo.y, angularVelo.z, 0);
  89990. w.mult(quat,wq);
  89991. quat.x += half_dt * wq.x;
  89992. quat.y += half_dt * wq.y;
  89993. quat.z += half_dt * wq.z;
  89994. quat.w += half_dt * wq.w;
  89995. if(quatNormalize){
  89996. if(quatNormalizeFast){
  89997. quat.normalizeFast();
  89998. } else {
  89999. quat.normalize();
  90000. }
  90001. }
  90002. }
  90003. if(b.aabb){
  90004. b.aabbNeedsUpdate = true;
  90005. }
  90006. // Update world inertia
  90007. if(b.updateInertiaWorld){
  90008. b.updateInertiaWorld();
  90009. }
  90010. }
  90011. }
  90012. this.clearForces();
  90013. this.broadphase.dirty = true;
  90014. if(doProfiling){
  90015. profile.integrate = performance.now() - profilingStart;
  90016. }
  90017. // Update world time
  90018. this.time += dt;
  90019. this.stepnumber += 1;
  90020. this.dispatchEvent(World_step_postStepEvent);
  90021. // Invoke post-step callbacks
  90022. for(i=0; i!==N; i++){
  90023. var bi = bodies[i];
  90024. var postStep = bi.postStep;
  90025. if(postStep){
  90026. postStep.call(bi);
  90027. }
  90028. }
  90029. // Sleeping update
  90030. if(this.allowSleep){
  90031. for(i=0; i!==N; i++){
  90032. bodies[i].sleepTick(this.time);
  90033. }
  90034. }
  90035. };
  90036. /**
  90037. * Sets all body forces in the world to zero.
  90038. * @method clearForces
  90039. */
  90040. World.prototype.clearForces = function(){
  90041. var bodies = this.bodies;
  90042. var N = bodies.length;
  90043. for(var i=0; i !== N; i++){
  90044. var b = bodies[i],
  90045. force = b.force,
  90046. tau = b.torque;
  90047. b.force.set(0,0,0);
  90048. b.torque.set(0,0,0);
  90049. }
  90050. };
  90051. },{"../collision/AABB":3,"../collision/ArrayCollisionMatrix":4,"../collision/NaiveBroadphase":7,"../collision/Ray":9,"../collision/RaycastResult":10,"../equations/ContactEquation":19,"../equations/FrictionEquation":21,"../material/ContactMaterial":24,"../material/Material":25,"../math/Quaternion":28,"../math/Vec3":30,"../objects/Body":31,"../shapes/Shape":43,"../solver/GSSolver":46,"../utils/EventTarget":49,"../utils/TupleDictionary":52,"../utils/Vec3Pool":54,"./Narrowphase":55}]},{},[2])
  90052. (2)
  90053. });
  90054. /***/ }),
  90055. /* 16 */
  90056. /***/ (function(module, exports, __webpack_require__) {
  90057. /**
  90058. * from OimoPhysics DEV 1.1.0a AS3
  90059. * @author Saharan / http://el-ement.com/
  90060. *
  90061. * to Oimo.js 2015 JAVASCRIPT
  90062. * @author LoTh / http://lo-th.github.io/labs/
  90063. */
  90064. var OIMO = {
  90065. REVISION: "1.2",
  90066. // Global identification of next shape.
  90067. // This will be incremented every time a shape is created.
  90068. nextID: 0,
  90069. proxyID: 0,
  90070. // BroadPhase
  90071. BR_NULL: 0,
  90072. BR_BRUTE_FORCE: 1,
  90073. BR_SWEEP_AND_PRUNE: 2,
  90074. BR_BOUNDING_VOLUME_TREE: 3,
  90075. // body type
  90076. BODY_NULL: 0,
  90077. BODY_DYNAMIC: 1,
  90078. BODY_STATIC: 2,
  90079. // shape type
  90080. SHAPE_NULL: 0,
  90081. SHAPE_SPHERE: 1,
  90082. SHAPE_BOX: 2,
  90083. SHAPE_CYLINDER: 3,
  90084. SHAPE_TETRA: 4,
  90085. // joint type
  90086. JOINT_NULL: 0,
  90087. JOINT_DISTANCE: 1,
  90088. JOINT_BALL_AND_SOCKET: 2,
  90089. JOINT_HINGE: 3,
  90090. JOINT_WHEEL: 4,
  90091. JOINT_SLIDER: 5,
  90092. JOINT_PRISMATIC: 6,
  90093. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  90094. // scale all by 100 so object is between 10 to 10000 three unit.
  90095. WORLD_SCALE: 100,
  90096. INV_SCALE: 0.01,
  90097. // AABB aproximation
  90098. AABB_PROX: 0.005,
  90099. // Math function
  90100. sqrt: Math.sqrt,
  90101. abs: Math.abs,
  90102. floor: Math.floor,
  90103. cos: Math.cos,
  90104. sin: Math.sin,
  90105. acos: Math.acos,
  90106. asin: Math.asin,
  90107. atan2: Math.atan2,
  90108. round: Math.round,
  90109. pow: Math.pow,
  90110. max: Math.max,
  90111. min: Math.min,
  90112. random: Math.random,
  90113. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  90114. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  90115. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  90116. int: function (x) { return ~~x; },
  90117. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  90118. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  90119. degtorad: 0.0174532925199432957,
  90120. radtodeg: 57.295779513082320876,
  90121. PI: 3.141592653589793,
  90122. TwoPI: 6.283185307179586,
  90123. PI90: 1.570796326794896,
  90124. PI270: 4.712388980384689,
  90125. CustomError: null,
  90126. Error: function (Class, Msg) {
  90127. if (OIMO.CustomError == null) console.error(Class, Msg);
  90128. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  90129. }
  90130. };
  90131. var OIMO_ARRAY_TYPE;
  90132. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  90133. try {
  90134. (function (w) {
  90135. var perfNow;
  90136. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  90137. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  90138. var n = perfNowNames[i];
  90139. if (!!w['performance'][n]) {
  90140. perfNow = function () { return w['performance'][n]() };
  90141. break;
  90142. }
  90143. }
  90144. if (!perfNow) perfNow = Date.now;
  90145. //w.perfNow = perfNow;
  90146. OIMO.now = perfNow;
  90147. })(window);
  90148. } catch (e) { OIMO.now = function () { return 0; }; }
  90149. /**
  90150. * The class of physical computing world.
  90151. * You must be added to the world physical all computing objects
  90152. * @author saharan
  90153. * @author lo-th
  90154. */
  90155. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  90156. // The time between each step
  90157. this.timeStep = TimeStep || 0.01666; // 1/60;
  90158. // The number of iterations for constraint solvers.
  90159. this.numIterations = Iterations || 8;
  90160. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  90161. switch (BroadPhaseType || 2) {
  90162. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  90163. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  90164. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  90165. }
  90166. // This is the detailed information of the performance.
  90167. this.performance = null;
  90168. this.isNoStat = NoStat || false;
  90169. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  90170. // Whether the constraints randomizer is enabled or not.
  90171. this.enableRandomizer = true;
  90172. // The rigid body list
  90173. this.rigidBodies = null;
  90174. // number of rigid body
  90175. this.numRigidBodies = 0;
  90176. // The contact list
  90177. this.contacts = null;
  90178. this.unusedContacts = null;
  90179. // The number of contact
  90180. this.numContacts = 0;
  90181. // The number of contact points
  90182. this.numContactPoints = 0;
  90183. // The joint list
  90184. this.joints = null;
  90185. // The number of joints.
  90186. this.numJoints = 0;
  90187. // The number of simulation islands.
  90188. this.numIslands = 0;
  90189. // The gravity in the world.
  90190. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  90191. var numShapeTypes = 5;//4;//3;
  90192. this.detectors = [];
  90193. this.detectors.length = numShapeTypes;
  90194. var i = numShapeTypes;
  90195. while (i--) {
  90196. this.detectors[i] = [];
  90197. this.detectors[i].length = numShapeTypes;
  90198. }
  90199. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  90200. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  90201. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  90202. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  90203. // CYLINDER add
  90204. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  90205. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  90206. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  90207. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  90208. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  90209. // TETRA add
  90210. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  90211. this.randX = 65535;
  90212. this.randA = 98765;
  90213. this.randB = 123456789;
  90214. //this.maxIslandRigidBodies = 64;
  90215. this.islandRigidBodies = [];
  90216. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  90217. this.islandStack = [];
  90218. //this.islandStack.length = this.maxIslandRigidBodies;
  90219. //this.maxIslandConstraints = 128;
  90220. this.islandConstraints = [];
  90221. //this.islandConstraints.length = this.maxIslandConstraints;
  90222. };
  90223. OIMO.World.prototype = {
  90224. constructor: OIMO.World,
  90225. /**
  90226. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  90227. */
  90228. clear: function () {
  90229. this.randX = 65535;
  90230. while (this.joints !== null) {
  90231. this.removeJoint(this.joints);
  90232. }
  90233. while (this.contacts !== null) {
  90234. this.removeContact(this.contacts);
  90235. }
  90236. while (this.rigidBodies !== null) {
  90237. this.removeRigidBody(this.rigidBodies);
  90238. }
  90239. OIMO.nextID = 0;
  90240. OIMO.proxyID = 0;
  90241. },
  90242. /**
  90243. * I'll add a rigid body to the world.
  90244. * Rigid body that has been added will be the operands of each step.
  90245. * @param rigidBody Rigid body that you want to add
  90246. */
  90247. addRigidBody: function (rigidBody) {
  90248. if (rigidBody.parent) {
  90249. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  90250. }
  90251. rigidBody.parent = this;
  90252. rigidBody.awake();
  90253. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  90254. this.addShape(shape);
  90255. }
  90256. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  90257. this.rigidBodies = rigidBody;
  90258. this.numRigidBodies++;
  90259. },
  90260. /**
  90261. * I will remove the rigid body from the world.
  90262. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  90263. * @param rigidBody Rigid body to be removed
  90264. */
  90265. removeRigidBody: function (rigidBody) {
  90266. var remove = rigidBody;
  90267. if (remove.parent !== this) return;
  90268. remove.awake();
  90269. var js = remove.jointLink;
  90270. while (js != null) {
  90271. var joint = js.joint;
  90272. js = js.next;
  90273. this.removeJoint(joint);
  90274. }
  90275. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  90276. this.removeShape(shape);
  90277. }
  90278. var prev = remove.prev;
  90279. var next = remove.next;
  90280. if (prev !== null) prev.next = next;
  90281. if (next !== null) next.prev = prev;
  90282. if (this.rigidBodies == remove) this.rigidBodies = next;
  90283. remove.prev = null;
  90284. remove.next = null;
  90285. remove.parent = null;
  90286. this.numRigidBodies--;
  90287. },
  90288. getByName: function (name) {
  90289. var result = null;
  90290. var body = this.rigidBodies;
  90291. while (body !== null) {
  90292. if (body.name !== " " && body.name === name) result = body;
  90293. body = body.next;
  90294. }
  90295. var joint = this.joints;
  90296. while (joint !== null) {
  90297. if (joint.name !== "" && joint.name === name) result = joint;
  90298. joint = joint.next;
  90299. }
  90300. return result;
  90301. },
  90302. /**
  90303. * I'll add a shape to the world..
  90304. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  90305. * Shape will be added to the world automatically, please do not call from outside this method.
  90306. * @param shape Shape you want to add
  90307. */
  90308. addShape: function (shape) {
  90309. if (!shape.parent || !shape.parent.parent) {
  90310. OIMO.Error("World", "It is not possible to be added alone to shape world");
  90311. }
  90312. shape.proxy = this.broadPhase.createProxy(shape);
  90313. shape.updateProxy();
  90314. this.broadPhase.addProxy(shape.proxy);
  90315. },
  90316. /**
  90317. * I will remove the shape from the world.
  90318. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  90319. * Shape will be added to the world automatically, please do not call from outside this method.
  90320. * @param shape Shape you want to delete
  90321. */
  90322. removeShape: function (shape) {
  90323. this.broadPhase.removeProxy(shape.proxy);
  90324. shape.proxy = null;
  90325. },
  90326. /**
  90327. * I'll add a joint to the world.
  90328. * Joint that has been added will be the operands of each step.
  90329. * @param shape Joint to be added
  90330. */
  90331. addJoint: function (joint) {
  90332. if (joint.parent) {
  90333. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  90334. }
  90335. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  90336. this.joints = joint;
  90337. joint.parent = this;
  90338. this.numJoints++;
  90339. joint.awake();
  90340. joint.attach();
  90341. },
  90342. /**
  90343. * I will remove the joint from the world.
  90344. * Joint that has been added will be the operands of each step.
  90345. * @param shape Joint to be deleted
  90346. */
  90347. removeJoint: function (joint) {
  90348. var remove = joint;
  90349. var prev = remove.prev;
  90350. var next = remove.next;
  90351. if (prev !== null) prev.next = next;
  90352. if (next !== null) next.prev = prev;
  90353. if (this.joints == remove) this.joints = next;
  90354. remove.prev = null;
  90355. remove.next = null;
  90356. this.numJoints--;
  90357. remove.awake();
  90358. remove.detach();
  90359. remove.parent = null;
  90360. },
  90361. worldscale: function (scale) {
  90362. OIMO.WORLD_SCALE = scale || 100;
  90363. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  90364. },
  90365. addContact: function (s1, s2) {
  90366. var newContact;
  90367. if (this.unusedContacts !== null) {
  90368. newContact = this.unusedContacts;
  90369. this.unusedContacts = this.unusedContacts.next;
  90370. } else {
  90371. newContact = new OIMO.Contact();
  90372. }
  90373. newContact.attach(s1, s2);
  90374. newContact.detector = this.detectors[s1.type][s2.type];
  90375. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  90376. this.contacts = newContact;
  90377. this.numContacts++;
  90378. },
  90379. removeContact: function (contact) {
  90380. var prev = contact.prev;
  90381. var next = contact.next;
  90382. if (next) next.prev = prev;
  90383. if (prev) prev.next = next;
  90384. if (this.contacts == contact) this.contacts = next;
  90385. contact.prev = null;
  90386. contact.next = null;
  90387. contact.detach();
  90388. contact.next = this.unusedContacts;
  90389. this.unusedContacts = contact;
  90390. this.numContacts--;
  90391. },
  90392. checkContact: function (name1, name2) {
  90393. var n1, n2;
  90394. var contact = this.contacts;
  90395. while (contact !== null) {
  90396. n1 = contact.body1.name || ' ';
  90397. n2 = contact.body2.name || ' ';
  90398. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  90399. else contact = contact.next;
  90400. }
  90401. return false;
  90402. },
  90403. callSleep: function (body) {
  90404. if (!body.allowSleep) return false;
  90405. if (body.linearVelocity.lengthSq() > 0.04) return false;
  90406. if (body.angularVelocity.lengthSq() > 0.25) return false;
  90407. return true;
  90408. },
  90409. /**
  90410. * I will proceed only time step seconds time of World.
  90411. */
  90412. step: function () {
  90413. var time0, time1, time2, time3;
  90414. var stat = !this.isNoStat ? true : false;
  90415. if (stat) time0 = OIMO.now();
  90416. var body = this.rigidBodies;
  90417. while (body !== null) {
  90418. body.addedToIsland = false;
  90419. if (body.sleeping) {
  90420. if (
  90421. body.linearVelocity.testZero() ||
  90422. body.angularVelocity.testZero() ||
  90423. body.position.testDiff(body.sleepPosition) ||
  90424. body.orientation.testDiff(body.sleepOrientation)
  90425. ) body.awake(); // awake the body
  90426. }
  90427. body = body.next;
  90428. }
  90429. //------------------------------------------------------
  90430. // UPDATE CONTACT
  90431. //------------------------------------------------------
  90432. // broad phase
  90433. if (stat) time1 = OIMO.now();
  90434. this.broadPhase.detectPairs();
  90435. var pairs = this.broadPhase.pairs;
  90436. var i = this.broadPhase.numPairs;
  90437. //do{
  90438. while (i--) {
  90439. //for(var i=0, l=numPairs; i<l; i++){
  90440. var pair = pairs[i];
  90441. var s1;
  90442. var s2;
  90443. if (pair.shape1.id < pair.shape2.id) {
  90444. s1 = pair.shape1;
  90445. s2 = pair.shape2;
  90446. } else {
  90447. s1 = pair.shape2;
  90448. s2 = pair.shape1;
  90449. }
  90450. var link;
  90451. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  90452. else link = s2.contactLink;
  90453. var exists = false;
  90454. while (link) {
  90455. var contact = link.contact;
  90456. if (contact.shape1 == s1 && contact.shape2 == s2) {
  90457. contact.persisting = true;
  90458. exists = true;// contact already exists
  90459. break;
  90460. }
  90461. link = link.next;
  90462. }
  90463. if (!exists) {
  90464. this.addContact(s1, s2);
  90465. }
  90466. }// while(i-- >0);
  90467. if (stat) {
  90468. time2 = OIMO.now();
  90469. this.performance.broadPhaseTime = time2 - time1;
  90470. }
  90471. // update & narrow phase
  90472. this.numContactPoints = 0;
  90473. contact = this.contacts;
  90474. while (contact !== null) {
  90475. if (!contact.persisting) {
  90476. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  90477. /*var aabb1=contact.shape1.aabb;
  90478. var aabb2=contact.shape2.aabb;
  90479. if(
  90480. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  90481. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  90482. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  90483. ){*/
  90484. var next = contact.next;
  90485. this.removeContact(contact);
  90486. contact = next;
  90487. continue;
  90488. }
  90489. }
  90490. var b1 = contact.body1;
  90491. var b2 = contact.body2;
  90492. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  90493. contact.updateManifold();
  90494. }
  90495. this.numContactPoints += contact.manifold.numPoints;
  90496. contact.persisting = false;
  90497. contact.constraint.addedToIsland = false;
  90498. contact = contact.next;
  90499. }
  90500. if (stat) {
  90501. time3 = OIMO.now();
  90502. this.performance.narrowPhaseTime = time3 - time2;
  90503. }
  90504. //------------------------------------------------------
  90505. // SOLVE ISLANDS
  90506. //------------------------------------------------------
  90507. var invTimeStep = 1 / this.timeStep;
  90508. //var body;
  90509. var joint;
  90510. var constraint;
  90511. //var num;
  90512. for (joint = this.joints; joint !== null; joint = joint.next) {
  90513. joint.addedToIsland = false;
  90514. }
  90515. // clear old island array
  90516. this.islandRigidBodies = [];
  90517. this.islandConstraints = [];
  90518. this.islandStack = [];
  90519. // expand island buffers
  90520. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  90521. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  90522. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  90523. this.islandRigidBodies=[];
  90524. this.islandStack=[];
  90525. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  90526. this.islandStack.length = this.maxIslandRigidBodies;
  90527. }
  90528. var numConstraints=this.numJoints+this.numContacts;
  90529. if(this.maxIslandConstraints<numConstraints){
  90530. this.maxIslandConstraints=numConstraints<<1;
  90531. //this.maxIslandConstraints=numConstraints*2;
  90532. this.islandConstraints=[];
  90533. this.islandConstraints.length = this.maxIslandConstraints;
  90534. }*/
  90535. time1 = OIMO.now();
  90536. this.numIslands = 0;
  90537. // build and solve simulation islands
  90538. for (var base = this.rigidBodies; base !== null; base = base.next) {
  90539. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  90540. if (base.isLonely()) {// update single body
  90541. if (base.isDynamic) {
  90542. base.linearVelocity.addTime(this.gravity, this.timeStep);
  90543. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  90544. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  90545. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  90546. }
  90547. if (this.callSleep(base)) {
  90548. base.sleepTime += this.timeStep;
  90549. if (base.sleepTime > 0.5) base.sleep();
  90550. else base.updatePosition(this.timeStep);
  90551. } else {
  90552. base.sleepTime = 0;
  90553. base.updatePosition(this.timeStep);
  90554. }
  90555. this.numIslands++;
  90556. continue;
  90557. }
  90558. var islandNumRigidBodies = 0;
  90559. var islandNumConstraints = 0;
  90560. var stackCount = 1;
  90561. // add rigid body to stack
  90562. this.islandStack[0] = base;
  90563. base.addedToIsland = true;
  90564. // build an island
  90565. do {
  90566. // get rigid body from stack
  90567. body = this.islandStack[--stackCount];
  90568. this.islandStack[stackCount] = null;
  90569. body.sleeping = false;
  90570. // add rigid body to the island
  90571. this.islandRigidBodies[islandNumRigidBodies++] = body;
  90572. if (body.isStatic) continue;
  90573. // search connections
  90574. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  90575. var contact = cs.contact;
  90576. constraint = contact.constraint;
  90577. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  90578. // add constraint to the island
  90579. this.islandConstraints[islandNumConstraints++] = constraint;
  90580. constraint.addedToIsland = true;
  90581. var next = cs.body;
  90582. if (next.addedToIsland) continue;
  90583. // add rigid body to stack
  90584. this.islandStack[stackCount++] = next;
  90585. next.addedToIsland = true;
  90586. }
  90587. for (var js = body.jointLink; js !== null; js = js.next) {
  90588. constraint = js.joint;
  90589. if (constraint.addedToIsland) continue;// ignore
  90590. // add constraint to the island
  90591. this.islandConstraints[islandNumConstraints++] = constraint;
  90592. constraint.addedToIsland = true;
  90593. next = js.body;
  90594. if (next.addedToIsland || !next.isDynamic) continue;
  90595. // add rigid body to stack
  90596. this.islandStack[stackCount++] = next;
  90597. next.addedToIsland = true;
  90598. }
  90599. } while (stackCount != 0);
  90600. // update velocities
  90601. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  90602. /*var gx=this.gravity.x*this.timeStep;
  90603. var gy=this.gravity.y*this.timeStep;
  90604. var gz=this.gravity.z*this.timeStep;*/
  90605. var j = islandNumRigidBodies;
  90606. while (j--) {
  90607. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  90608. body = this.islandRigidBodies[j];
  90609. if (body.isDynamic) {
  90610. body.linearVelocity.addEqual(gVel);
  90611. /*body.linearVelocity.x+=gx;
  90612. body.linearVelocity.y+=gy;
  90613. body.linearVelocity.z+=gz;*/
  90614. }
  90615. }
  90616. // randomizing order
  90617. if (this.enableRandomizer) {
  90618. //for(var j=1, l=islandNumConstraints; j<l; j++){
  90619. j = islandNumConstraints;
  90620. while (j--) {
  90621. if (j !== 0) {
  90622. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  90623. constraint = this.islandConstraints[j];
  90624. this.islandConstraints[j] = this.islandConstraints[swap];
  90625. this.islandConstraints[swap] = constraint;
  90626. }
  90627. }
  90628. }
  90629. // solve contraints
  90630. j = islandNumConstraints;
  90631. while (j--) {
  90632. //for(j=0, l=islandNumConstraints; j<l; j++){
  90633. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  90634. }
  90635. var k = this.numIterations;
  90636. while (k--) {
  90637. //for(var k=0, l=this.numIterations; k<l; k++){
  90638. j = islandNumConstraints;
  90639. while (j--) {
  90640. //for(j=0, m=islandNumConstraints; j<m; j++){
  90641. this.islandConstraints[j].solve();// main-solve
  90642. }
  90643. }
  90644. j = islandNumConstraints;
  90645. while (j--) {
  90646. //for(j=0, l=islandNumConstraints; j<l; j++){
  90647. this.islandConstraints[j].postSolve();// post-solve
  90648. this.islandConstraints[j] = null;// gc
  90649. }
  90650. // sleeping check
  90651. var sleepTime = 10;
  90652. j = islandNumRigidBodies;
  90653. while (j--) {
  90654. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  90655. body = this.islandRigidBodies[j];
  90656. if (this.callSleep(body)) {
  90657. body.sleepTime += this.timeStep;
  90658. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  90659. } else {
  90660. body.sleepTime = 0;
  90661. sleepTime = 0;
  90662. continue;
  90663. }
  90664. }
  90665. if (sleepTime > 0.5) {
  90666. // sleep the island
  90667. j = islandNumRigidBodies;
  90668. while (j--) {
  90669. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  90670. this.islandRigidBodies[j].sleep();
  90671. this.islandRigidBodies[j] = null;// gc
  90672. }
  90673. } else {
  90674. // update positions
  90675. j = islandNumRigidBodies;
  90676. while (j--) {
  90677. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  90678. this.islandRigidBodies[j].updatePosition(this.timeStep);
  90679. this.islandRigidBodies[j] = null;// gc
  90680. }
  90681. }
  90682. this.numIslands++;
  90683. }
  90684. if (stat) {
  90685. time2 = OIMO.now();
  90686. this.performance.solvingTime = time2 - time1;
  90687. //------------------------------------------------------
  90688. // END SIMULATION
  90689. //------------------------------------------------------
  90690. time2 = OIMO.now();
  90691. // fps update
  90692. this.performance.upfps();
  90693. this.performance.totalTime = time2 - time0;
  90694. }
  90695. }
  90696. }
  90697. /**
  90698. * The class of rigid body.
  90699. * Rigid body has the shape of a single or multiple collision processing,
  90700. * I can set the parameters individually.
  90701. * @author saharan
  90702. */
  90703. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  90704. this.name = " ";
  90705. // The maximum number of shapes that can be added to a one rigid.
  90706. this.MAX_SHAPES = 64;//64;
  90707. this.prev = null;
  90708. this.next = null;
  90709. // I represent the kind of rigid body.
  90710. // Please do not change from the outside this variable.
  90711. // If you want to change the type of rigid body, always
  90712. // Please specify the type you want to set the arguments of setupMass method.
  90713. this.type = OIMO.BODY_NULL;
  90714. this.massInfo = new OIMO.MassInfo();
  90715. // It is the world coordinate of the center of gravity.
  90716. this.position = new OIMO.Vec3(x, y, z);
  90717. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  90718. this.newPosition = new OIMO.Vec3();
  90719. this.controlPos = false;
  90720. this.newOrientation = new OIMO.Quat();
  90721. this.newRotation = new OIMO.Vec3();
  90722. this.currentRotation = new OIMO.Vec3();
  90723. this.controlRot = false;
  90724. this.controlRotInTime = false;
  90725. // Is the translational velocity.
  90726. this.linearVelocity = new OIMO.Vec3();
  90727. // Is the angular velocity.
  90728. this.angularVelocity = new OIMO.Vec3();
  90729. // return matrix for three.js
  90730. this.matrix = new OIMO.Mat44();
  90731. //--------------------------------------------
  90732. // Please do not change from the outside this variables.
  90733. //--------------------------------------------
  90734. // It is a world that rigid body has been added.
  90735. this.parent = null;
  90736. this.contactLink = null;
  90737. this.numContacts = 0;
  90738. // An array of shapes that are included in the rigid body.
  90739. this.shapes = null;
  90740. // The number of shapes that are included in the rigid body.
  90741. this.numShapes = 0;
  90742. // It is the link array of joint that is connected to the rigid body.
  90743. this.jointLink = null;
  90744. // The number of joints that are connected to the rigid body.
  90745. this.numJoints = 0;
  90746. // It is the world coordinate of the center of gravity in the sleep just before.
  90747. this.sleepPosition = new OIMO.Vec3();
  90748. // It is a quaternion that represents the attitude of sleep just before.
  90749. this.sleepOrientation = new OIMO.Quat();
  90750. // I will show this rigid body to determine whether it is a rigid body static.
  90751. this.isStatic = false;
  90752. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  90753. this.isDynamic = false;
  90754. // It is a rotation matrix representing the orientation.
  90755. this.rotation = new OIMO.Mat33();
  90756. //--------------------------------------------
  90757. // It will be recalculated automatically from the shape, which is included.
  90758. //--------------------------------------------
  90759. // This is the weight.
  90760. this.mass = NaN;
  90761. // It is the reciprocal of the mass.
  90762. this.inverseMass = NaN;
  90763. // It is the inverse of the inertia tensor in the world system.
  90764. this.inverseInertia = new OIMO.Mat33();
  90765. // It is the inertia tensor in the initial state.
  90766. this.localInertia = new OIMO.Mat33();
  90767. // It is the inverse of the inertia tensor in the initial state.
  90768. this.inverseLocalInertia = new OIMO.Mat33();
  90769. // I indicates rigid body whether it has been added to the simulation Island.
  90770. this.addedToIsland = false;
  90771. // It shows how to sleep rigid body.
  90772. this.allowSleep = true;
  90773. // This is the time from when the rigid body at rest.
  90774. this.sleepTime = 0;
  90775. // I shows rigid body to determine whether it is a sleep state.
  90776. this.sleeping = false;
  90777. };
  90778. OIMO.RigidBody.prototype = {
  90779. constructor: OIMO.RigidBody,
  90780. /**
  90781. * I'll add a shape to rigid body.
  90782. * If you add a shape, please call the setupMass method to step up to the start of the next.
  90783. * @param shape shape to Add
  90784. */
  90785. addShape: function (shape) {
  90786. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  90787. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  90788. this.shapes = shape;
  90789. shape.parent = this;
  90790. if (this.parent) this.parent.addShape(shape);
  90791. this.numShapes++;
  90792. },
  90793. /**
  90794. * I will delete the shape from the rigid body.
  90795. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  90796. * @param shape shape to Delete
  90797. */
  90798. removeShape: function (shape) {
  90799. var remove = shape;
  90800. if (remove.parent != this) return;
  90801. var prev = remove.prev;
  90802. var next = remove.next;
  90803. if (prev != null) prev.next = next;
  90804. if (next != null) next.prev = prev;
  90805. if (this.shapes == remove) this.shapes = next;
  90806. remove.prev = null;
  90807. remove.next = null;
  90808. remove.parent = null;
  90809. if (this.parent) this.parent.removeShape(remove);
  90810. this.numShapes--;
  90811. },
  90812. remove: function () {
  90813. this.dispose();
  90814. },
  90815. dispose: function () {
  90816. this.parent.removeRigidBody(this);
  90817. },
  90818. checkContact: function (name) {
  90819. this.parent.checkContact(this.name, name);
  90820. },
  90821. /**
  90822. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  90823. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  90824. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  90825. * the rigid body's position will be adjusted to the center of gravity.
  90826. * @param type
  90827. * @param adjustPosition
  90828. */
  90829. setupMass: function (type, AdjustPosition) {
  90830. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  90831. this.type = type || OIMO.BODY_DYNAMIC;
  90832. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  90833. this.isStatic = this.type == OIMO.BODY_STATIC;
  90834. this.mass = 0;
  90835. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  90836. var te = this.localInertia.elements;
  90837. //
  90838. var tmpM = new OIMO.Mat33();
  90839. var tmpV = new OIMO.Vec3();
  90840. for (var shape = this.shapes; shape != null; shape = shape.next) {
  90841. shape.calculateMassInfo(this.massInfo);
  90842. var shapeMass = this.massInfo.mass;
  90843. var relX = shape.relativePosition.x;
  90844. var relY = shape.relativePosition.y;
  90845. var relZ = shape.relativePosition.z;
  90846. /*tmpV.x+=relX*shapeMass;
  90847. tmpV.y+=relY*shapeMass;
  90848. tmpV.z+=relZ*shapeMass;*/
  90849. tmpV.addScale(shape.relativePosition, shapeMass);
  90850. this.mass += shapeMass;
  90851. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  90852. this.localInertia.addEqual(tmpM);
  90853. // add offset inertia
  90854. te[0] += shapeMass * (relY * relY + relZ * relZ);
  90855. te[4] += shapeMass * (relX * relX + relZ * relZ);
  90856. te[8] += shapeMass * (relX * relX + relY * relY);
  90857. var xy = shapeMass * relX * relY;
  90858. var yz = shapeMass * relY * relZ;
  90859. var zx = shapeMass * relZ * relX;
  90860. te[1] -= xy;
  90861. te[3] -= xy;
  90862. te[2] -= yz;
  90863. te[6] -= yz;
  90864. te[5] -= zx;
  90865. te[7] -= zx;
  90866. }
  90867. this.inverseMass = 1 / this.mass;
  90868. tmpV.scaleEqual(this.inverseMass);
  90869. if (adjustPosition) {
  90870. this.position.addEqual(tmpV);
  90871. for (shape = this.shapes; shape != null; shape = shape.next) {
  90872. shape.relativePosition.subEqual(tmpV);
  90873. }
  90874. // subtract offset inertia
  90875. relX = tmpV.x;
  90876. relY = tmpV.y;
  90877. relZ = tmpV.z;
  90878. //var te = this.localInertia.elements;
  90879. te[0] -= this.mass * (relY * relY + relZ * relZ);
  90880. te[4] -= this.mass * (relX * relX + relZ * relZ);
  90881. te[8] -= this.mass * (relX * relX + relY * relY);
  90882. xy = this.mass * relX * relY;
  90883. yz = this.mass * relY * relZ;
  90884. zx = this.mass * relZ * relX;
  90885. te[1] += xy;
  90886. te[3] += xy;
  90887. te[2] += yz;
  90888. te[6] += yz;
  90889. te[5] += zx;
  90890. te[7] += zx;
  90891. }
  90892. this.inverseLocalInertia.invert(this.localInertia);
  90893. if (this.type == OIMO.BODY_STATIC) {
  90894. this.inverseMass = 0;
  90895. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  90896. }
  90897. this.syncShapes();
  90898. this.awake();
  90899. },
  90900. /**
  90901. * Awake the rigid body.
  90902. */
  90903. awake: function () {
  90904. if (!this.allowSleep || !this.sleeping) return;
  90905. this.sleeping = false;
  90906. this.sleepTime = 0;
  90907. // awake connected constraints
  90908. var cs = this.contactLink;
  90909. while (cs != null) {
  90910. cs.body.sleepTime = 0;
  90911. cs.body.sleeping = false;
  90912. cs = cs.next;
  90913. }
  90914. var js = this.jointLink;
  90915. while (js != null) {
  90916. js.body.sleepTime = 0;
  90917. js.body.sleeping = false;
  90918. js = js.next;
  90919. }
  90920. for (var shape = this.shapes; shape != null; shape = shape.next) {
  90921. shape.updateProxy();
  90922. }
  90923. },
  90924. /**
  90925. * Sleep the rigid body.
  90926. */
  90927. sleep: function () {
  90928. if (!this.allowSleep || this.sleeping) return;
  90929. this.linearVelocity.set(0, 0, 0);
  90930. this.angularVelocity.set(0, 0, 0);
  90931. this.sleepPosition.copy(this.position);
  90932. this.sleepOrientation.copy(this.orientation);
  90933. /*this.linearVelocity.x=0;
  90934. this.linearVelocity.y=0;
  90935. this.linearVelocity.z=0;
  90936. this.angularVelocity.x=0;
  90937. this.angularVelocity.y=0;
  90938. this.angularVelocity.z=0;
  90939. this.sleepPosition.x=this.position.x;
  90940. this.sleepPosition.y=this.position.y;
  90941. this.sleepPosition.z=this.position.z;*/
  90942. /*this.sleepOrientation.s=this.orientation.s;
  90943. this.sleepOrientation.x=this.orientation.x;
  90944. this.sleepOrientation.y=this.orientation.y;
  90945. this.sleepOrientation.z=this.orientation.z;*/
  90946. this.sleepTime = 0;
  90947. this.sleeping = true;
  90948. for (var shape = this.shapes; shape != null; shape = shape.next) {
  90949. shape.updateProxy();
  90950. }
  90951. },
  90952. /**
  90953. * Get whether the rigid body has not any connection with others.
  90954. * @return
  90955. */
  90956. isLonely: function () {
  90957. return this.numJoints == 0 && this.numContacts == 0;
  90958. },
  90959. /**
  90960. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  90961. * This method is invoked automatically when calling the step of the World,
  90962. * There is no need to call from outside usually.
  90963. * @param timeStep time
  90964. */
  90965. updatePosition: function (timeStep) {
  90966. switch (this.type) {
  90967. case OIMO.BODY_STATIC:
  90968. this.linearVelocity.set(0, 0, 0);
  90969. this.angularVelocity.set(0, 0, 0);
  90970. // ONLY FOR TEST
  90971. if (this.controlPos) {
  90972. this.position.copy(this.newPosition);
  90973. this.controlPos = false;
  90974. }
  90975. if (this.controlRot) {
  90976. this.orientation.copy(this.newOrientation);
  90977. this.controlRot = false;
  90978. }
  90979. /*this.linearVelocity.x=0;
  90980. this.linearVelocity.y=0;
  90981. this.linearVelocity.z=0;
  90982. this.angularVelocity.x=0;
  90983. this.angularVelocity.y=0;
  90984. this.angularVelocity.z=0;*/
  90985. break;
  90986. case OIMO.BODY_DYNAMIC:
  90987. if (this.controlPos) {
  90988. this.angularVelocity.set(0, 0, 0);
  90989. this.linearVelocity.set(0, 0, 0);
  90990. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  90991. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  90992. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  90993. this.controlPos = false;
  90994. }
  90995. if (this.controlRot) {
  90996. this.angularVelocity.set(0, 0, 0);
  90997. this.orientation.copy(this.newOrientation);
  90998. //var t=timeStep//*0.5;
  90999. //var q = new OIMO.Quat();
  91000. //q.sub(this.newOrientation, this.orientation);
  91001. //q.normalize(q);
  91002. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  91003. q.x = (this.newOrientation.x - this.orientation.x)/t;
  91004. q.y = (this.newOrientation.y - this.orientation.y)/t;
  91005. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  91006. //this.angularVelocity.applyQuaternion(q);
  91007. //this.angularVelocity.x = this.angularVelocity.x/t;
  91008. //this.angularVelocity.y = this.angularVelocity.y/t;
  91009. //this.angularVelocity.z = this.angularVelocity.z/t;
  91010. this.controlRot = false;
  91011. }
  91012. this.position.addTime(this.linearVelocity, timeStep);
  91013. this.orientation.addTime(this.angularVelocity, timeStep);
  91014. break;
  91015. default: OIMO.Error("RigidBody", "Invalid type.");
  91016. }
  91017. this.syncShapes();
  91018. },
  91019. rotateInertia: function (rot, inertia, out) {
  91020. var tm1 = rot.elements;
  91021. var tm2 = inertia.elements;
  91022. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  91023. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  91024. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  91025. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  91026. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  91027. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  91028. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  91029. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  91030. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  91031. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  91032. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  91033. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  91034. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  91035. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  91036. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  91037. var oe = out.elements;
  91038. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  91039. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  91040. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  91041. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  91042. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  91043. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  91044. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  91045. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  91046. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  91047. },
  91048. syncShapes: function () {
  91049. var s = this.orientation.s;
  91050. var x = this.orientation.x;
  91051. var y = this.orientation.y;
  91052. var z = this.orientation.z;
  91053. var x2 = 2 * x;
  91054. var y2 = 2 * y;
  91055. var z2 = 2 * z;
  91056. var xx = x * x2;
  91057. var yy = y * y2;
  91058. var zz = z * z2;
  91059. var xy = x * y2;
  91060. var yz = y * z2;
  91061. var xz = x * z2;
  91062. var sx = s * x2;
  91063. var sy = s * y2;
  91064. var sz = s * z2;
  91065. var tr = this.rotation.elements;
  91066. tr[0] = 1 - yy - zz;
  91067. tr[1] = xy - sz;
  91068. tr[2] = xz + sy;
  91069. tr[3] = xy + sz;
  91070. tr[4] = 1 - xx - zz;
  91071. tr[5] = yz - sx;
  91072. tr[6] = xz - sy;
  91073. tr[7] = yz + sx;
  91074. tr[8] = 1 - xx - yy;
  91075. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  91076. for (var shape = this.shapes; shape != null; shape = shape.next) {
  91077. //var relPos=shape.relativePosition;
  91078. //var relRot=shape.relativeRotation;
  91079. //var rot=shape.rotation;
  91080. /*var lx=relPos.x;
  91081. var ly=relPos.y;
  91082. var lz=relPos.z;
  91083. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  91084. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  91085. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  91086. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  91087. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  91088. // add by QuaziKb
  91089. shape.rotation.mul(this.rotation, shape.relativeRotation);
  91090. shape.updateProxy();
  91091. }
  91092. },
  91093. applyImpulse: function (position, force) {
  91094. this.linearVelocity.addScale(force, this.inverseMass);
  91095. /*this.linearVelocity.x+=force.x*this.inverseMass;
  91096. this.linearVelocity.y+=force.y*this.inverseMass;
  91097. this.linearVelocity.z+=force.z*this.inverseMass;*/
  91098. var rel = new OIMO.Vec3();
  91099. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  91100. this.angularVelocity.addEqual(rel);
  91101. /*this.angularVelocity.x+=rel.x;
  91102. this.angularVelocity.y+=rel.y;
  91103. this.angularVelocity.z+=rel.z;*/
  91104. },
  91105. //---------------------------------------------
  91106. //
  91107. // FOR THREE JS
  91108. //
  91109. //---------------------------------------------
  91110. rotationVectToQuad: function (rot) {
  91111. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  91112. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  91113. },
  91114. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  91115. var len = ax * ax + ay * ay + az * az;
  91116. if (len > 0) {
  91117. len = 1 / OIMO.sqrt(len);
  91118. ax *= len;
  91119. ay *= len;
  91120. az *= len;
  91121. }
  91122. var sin = OIMO.sin(rad * 0.5);
  91123. var cos = OIMO.cos(rad * 0.5);
  91124. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  91125. },
  91126. //---------------------------------------------
  91127. // SET DYNAMIQUE POSITION AND ROTATION
  91128. //---------------------------------------------
  91129. setPosition: function (pos) {
  91130. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  91131. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  91132. this.controlPos = true;
  91133. },
  91134. setQuaternion: function (q) {
  91135. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  91136. this.newOrientation.set(q.x, q.y, q.z, q.w);
  91137. this.controlRot = true;
  91138. },
  91139. setRotation: function (rot) {
  91140. this.newOrientation = this.rotationVectToQuad(rot);
  91141. this.controlRot = true;
  91142. },
  91143. //---------------------------------------------
  91144. // RESET DYNAMIQUE POSITION AND ROTATION
  91145. //---------------------------------------------
  91146. resetPosition: function (x, y, z) {
  91147. this.linearVelocity.set(0, 0, 0);
  91148. this.angularVelocity.set(0, 0, 0);
  91149. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  91150. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  91151. this.awake();
  91152. },
  91153. resetQuaternion: function (q) {
  91154. this.angularVelocity.set(0, 0, 0);
  91155. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  91156. this.awake();
  91157. },
  91158. resetRotation: function (x, y, z) {
  91159. this.angularVelocity.set(0, 0, 0);
  91160. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  91161. this.awake();
  91162. },
  91163. //---------------------------------------------
  91164. // GET POSITION AND ROTATION
  91165. //---------------------------------------------
  91166. getPosition: function () {
  91167. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  91168. },
  91169. getRotation: function () {
  91170. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  91171. },
  91172. getQuaternion: function () {
  91173. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  91174. },
  91175. getMatrix: function () {
  91176. var m = this.matrix.elements;
  91177. var r, p;
  91178. if (!this.sleeping) {
  91179. // rotation matrix
  91180. r = this.rotation.elements;
  91181. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  91182. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  91183. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  91184. // position matrix
  91185. p = this.position;
  91186. m[12] = p.x * OIMO.WORLD_SCALE;
  91187. m[13] = p.y * OIMO.WORLD_SCALE;
  91188. m[14] = p.z * OIMO.WORLD_SCALE;
  91189. // sleep or not ?
  91190. m[15] = 0;
  91191. } else {
  91192. m[15] = 1;
  91193. }
  91194. return m;
  91195. }
  91196. };
  91197. /**
  91198. * The main class of body.
  91199. * is for simplify creation process and data access of rigidRody
  91200. * Rigid body has the shape of a single or multiple collision processing,
  91201. * all setting in object
  91202. *
  91203. * @author loth
  91204. */
  91205. OIMO.Body = function (Obj) {
  91206. var obj = Obj || {};
  91207. if (!obj.world) return;
  91208. if (obj.type === undefined) obj.type = "box";
  91209. this.name = obj.name || '';
  91210. // obsolete use world.add(obj)
  91211. this.body = obj.world.add(obj);
  91212. /*
  91213. // the world where i am
  91214. this.parent = obj.world;
  91215. // Yep my name
  91216. this.name = obj.name || '';
  91217. // I'm dynamique or not
  91218. var move = obj.move || false;
  91219. // I can sleep or not
  91220. var noSleep = obj.noSleep || false;
  91221. // My start position
  91222. var p = obj.pos || [0,0,0];
  91223. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  91224. // My size
  91225. var s = obj.size || [1,1,1];
  91226. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  91227. // My rotation in degre
  91228. var rot = obj.rot || [0,0,0];
  91229. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  91230. var r = [];
  91231. for (var i=0; i<rot.length/3; i++){
  91232. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  91233. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  91234. }
  91235. // My physics setting
  91236. var sc = obj.sc || new OIMO.ShapeConfig();
  91237. if(obj.config){
  91238. // The density of the shape.
  91239. sc.density = obj.config[0] || 1;
  91240. // The coefficient of friction of the shape.
  91241. sc.friction = obj.config[1] || 0.4;
  91242. // The coefficient of restitution of the shape.
  91243. sc.restitution = obj.config[2] || 0.2;
  91244. // The bits of the collision groups to which the shape belongs.
  91245. sc.belongsTo = obj.config[3] || 1;
  91246. // The bits of the collision groups with which the shape collides.
  91247. sc.collidesWith = obj.config[4] || 0xffffffff;
  91248. }
  91249. if(obj.massPos){
  91250. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  91251. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  91252. }
  91253. if(obj.massRot){
  91254. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  91255. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  91256. }
  91257. // My rigidbody
  91258. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  91259. // My shapes
  91260. var shapes = [];
  91261. var type = obj.type || "box";
  91262. if( typeof type === 'string' ) type = [type];// single shape
  91263. var n, n2;
  91264. for(var i=0; i<type.length; i++){
  91265. n = i*3;
  91266. n2 = i*4;
  91267. switch(type[i]){
  91268. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  91269. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  91270. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  91271. }
  91272. this.body.addShape(shapes[i]);
  91273. if(i>0){
  91274. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  91275. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  91276. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  91277. }
  91278. }
  91279. // I'm static or i move
  91280. if(move){
  91281. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  91282. else this.body.setupMass(0x1, true);
  91283. if(noSleep) this.body.allowSleep = false;
  91284. else this.body.allowSleep = true;
  91285. } else {
  91286. this.body.setupMass(0x2);
  91287. }
  91288. this.body.name = this.name;
  91289. this.sleeping = this.body.sleeping;
  91290. // finaly add to physics world
  91291. this.parent.addRigidBody(this.body);*/
  91292. }
  91293. OIMO.Body.prototype = {
  91294. constructor: OIMO.Body,
  91295. // SET
  91296. setPosition: function (pos) {
  91297. this.body.setPosition(pos);
  91298. },
  91299. setQuaternion: function (q) {
  91300. this.body.setQuaternion(q);
  91301. },
  91302. setRotation: function (rot) {
  91303. this.body.setRotation(rot);
  91304. },
  91305. // GET
  91306. getPosition: function () {
  91307. return this.body.getPosition();
  91308. },
  91309. getRotation: function () {
  91310. return this.body.getRotation();
  91311. },
  91312. getQuaternion: function () {
  91313. return this.body.getQuaternion();
  91314. },
  91315. getMatrix: function () {
  91316. return this.body.getMatrix();
  91317. },
  91318. getSleep: function () {
  91319. return this.body.sleeping;
  91320. },
  91321. // RESET
  91322. resetPosition: function (x, y, z) {
  91323. this.body.resetPosition(x, y, z);
  91324. },
  91325. resetRotation: function (x, y, z) {
  91326. this.body.resetRotation(x, y, z);
  91327. },
  91328. // force wakeup
  91329. awake: function () {
  91330. this.body.awake();
  91331. },
  91332. // remove rigidbody
  91333. remove: function () {
  91334. this.body.dispose();
  91335. //this.parent.removeRigidBody(this.body);
  91336. },
  91337. // test if this object hit another
  91338. checkContact: function (name) {
  91339. this.body.checkContact(name);
  91340. //this.parent.checkContact(this.name, name);
  91341. }
  91342. }
  91343. /**
  91344. * The main class of link.
  91345. * is for simplify creation process and data access of Joint
  91346. * all setting in object
  91347. *
  91348. * @author loth
  91349. */
  91350. OIMO.Link = function (Obj) {
  91351. var obj = Obj || {};
  91352. if (!obj.world) return;
  91353. if (obj.type === undefined) obj.type = "jointHinge";
  91354. this.name = obj.name || '';
  91355. // obsolete use world.add(obj)
  91356. this.joint = obj.world.add(obj);
  91357. // the world where i am
  91358. /*this.parent = obj.world;
  91359. this.name = obj.name || '';
  91360. var type = obj.type || "jointHinge";
  91361. var axe1 = obj.axe1 || [1,0,0];
  91362. var axe2 = obj.axe2 || [1,0,0];
  91363. var pos1 = obj.pos1 || [0,0,0];
  91364. var pos2 = obj.pos2 || [0,0,0];
  91365. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  91366. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  91367. var min, max;
  91368. if(type==="jointDistance"){
  91369. min = obj.min || 0;
  91370. max = obj.max || 10;
  91371. min = min*OIMO.INV_SCALE;
  91372. max = max*OIMO.INV_SCALE;
  91373. }else{
  91374. min = obj.min || 57.29578;
  91375. max = obj.max || 0;
  91376. min = min*OIMO.TO_RAD;
  91377. max = max*OIMO.TO_RAD;
  91378. }
  91379. var limit = obj.limit || null;
  91380. var spring = obj.spring || null;
  91381. var motor = obj.motor || null;
  91382. // joint setting
  91383. var jc = new OIMO.JointConfig();
  91384. jc.allowCollision = obj.collision || false;;
  91385. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  91386. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  91387. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  91388. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  91389. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  91390. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  91391. jc.body1 = obj.body1;
  91392. jc.body2 = obj.body2;
  91393. switch(type){
  91394. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  91395. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  91396. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  91397. break;
  91398. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  91399. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  91400. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  91401. break;
  91402. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  91403. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  91404. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  91405. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  91406. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  91407. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  91408. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  91409. break;
  91410. }
  91411. this.joint.name = this.name;
  91412. // finaly add to physics world
  91413. this.parent.addJoint(this.joint);*/
  91414. }
  91415. OIMO.Link.prototype = {
  91416. constructor: OIMO.Link,
  91417. getPosition: function () {
  91418. // array of two vect3 [point1, point2]
  91419. return this.joint.getPosition();
  91420. },
  91421. getMatrix: function () {
  91422. return this.joint.getMatrix();
  91423. },
  91424. // remove joint
  91425. remove: function () {
  91426. this.joint.dispose();
  91427. //this.parent.removeJoint(this.joint);
  91428. },
  91429. // force wakeup linked body
  91430. awake: function () {
  91431. this.joint.awake();
  91432. }
  91433. }
  91434. /**
  91435. * The Dictionary class for testing
  91436. * @author lo-th
  91437. */
  91438. OIMO.Dictionary = function () {
  91439. this.data = {};
  91440. this.keys = [];
  91441. };
  91442. OIMO.Dictionary.prototype = {
  91443. constructor: OIMO.Dictionary,
  91444. set: function (value) {
  91445. var key = value.id;
  91446. if (!this.get[key]) this.keys.push(key);
  91447. this.data[key] = value;
  91448. },
  91449. get: function (id) {
  91450. return this.data[id];
  91451. },
  91452. del: function (value) {
  91453. var k = this.keys;
  91454. var n = k.indexOf(value.id);
  91455. if (n > -1) {
  91456. delete this.data[k[n]];
  91457. k.splice(n, 1);
  91458. }
  91459. },
  91460. reset: function () {
  91461. var data = this.data, keys = this.keys, key;
  91462. while (keys.length > 0) {
  91463. key = keys.pop();
  91464. delete data[key];
  91465. }
  91466. }
  91467. };
  91468. OIMO.Performance = function (world) {
  91469. this.parent = world;
  91470. this.infos = new OIMO_ARRAY_TYPE(13);
  91471. this.f = [0, 0, 0];
  91472. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  91473. this.broadPhase = this.types[this.parent.broadPhase.types];
  91474. this.version = OIMO.REVISION;
  91475. this.fps = 0;
  91476. this.broadPhaseTime = 0;
  91477. this.narrowPhaseTime = 0;
  91478. this.solvingTime = 0;
  91479. //this.updatingTime = 0;
  91480. this.totalTime = 0;
  91481. };
  91482. OIMO.Performance.prototype = {
  91483. upfps: function () {
  91484. this.f[1] = Date.now();
  91485. 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]++;
  91486. },
  91487. updatingTime: function () {
  91488. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  91489. },
  91490. show: function () {
  91491. var info = [
  91492. "Oimo.js " + this.version + "<br>",
  91493. this.broadPhase + "<br><br>",
  91494. "FPS: " + this.fps + " fps<br><br>",
  91495. "rigidbody " + this.parent.numRigidBodies + "<br>",
  91496. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  91497. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  91498. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  91499. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  91500. "Time in milliseconde<br><br>",
  91501. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  91502. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  91503. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  91504. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  91505. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  91506. ].join("\n");
  91507. return info;
  91508. },
  91509. toArray: function () {
  91510. this.infos[0] = this.parent.broadPhase.types;
  91511. this.infos[1] = this.parent.numRigidBodies;
  91512. this.infos[2] = this.parent.numContacts;
  91513. this.infos[3] = this.parent.broadPhase.numPairChecks;
  91514. this.infos[4] = this.parent.numContactPoints;
  91515. this.infos[5] = this.parent.numIslands;
  91516. this.infos[6] = this.broadPhaseTime;
  91517. this.infos[7] = this.narrowPhaseTime;
  91518. this.infos[8] = this.solvingTime;
  91519. this.infos[9] = this.updatingTime();
  91520. this.infos[10] = this.totalTime;
  91521. this.infos[11] = this.fps;
  91522. return this.infos;
  91523. }
  91524. };
  91525. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  91526. this.elements = new OIMO_ARRAY_TYPE(16);
  91527. var te = this.elements;
  91528. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  91529. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  91530. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  91531. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  91532. };
  91533. OIMO.Mat44.prototype = {
  91534. constructor: OIMO.Mat44,
  91535. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  91536. var te = this.elements;
  91537. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  91538. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  91539. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  91540. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  91541. return this;
  91542. }/*,
  91543. extractRotation: function () {
  91544. var v1 = new THREE.Vector3();
  91545. return function ( m ) {
  91546. var te = this.elements;
  91547. var me = m.elements;
  91548. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  91549. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  91550. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  91551. te[ 0 ] = me[ 0 ] * scaleX;
  91552. te[ 1 ] = me[ 1 ] * scaleX;
  91553. te[ 2 ] = me[ 2 ] * scaleX;
  91554. te[ 4 ] = me[ 4 ] * scaleY;
  91555. te[ 5 ] = me[ 5 ] * scaleY;
  91556. te[ 6 ] = me[ 6 ] * scaleY;
  91557. te[ 8 ] = me[ 8 ] * scaleZ;
  91558. te[ 9 ] = me[ 9 ] * scaleZ;
  91559. te[ 10 ] = me[ 10 ] * scaleZ;
  91560. return this;
  91561. };
  91562. }() */
  91563. }
  91564. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  91565. this.elements = new OIMO_ARRAY_TYPE(9);
  91566. var te = this.elements;
  91567. this.init(
  91568. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  91569. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  91570. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  91571. );
  91572. };
  91573. OIMO.Mat33.prototype = {
  91574. constructor: OIMO.Mat33,
  91575. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  91576. var te = this.elements;
  91577. te[0] = e00; te[1] = e01; te[2] = e02;
  91578. te[3] = e10; te[4] = e11; te[5] = e12;
  91579. te[6] = e20; te[7] = e21; te[8] = e22;
  91580. return this;
  91581. },
  91582. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  91583. var te = this.elements;
  91584. te[0] = e00; te[1] = e01; te[2] = e02;
  91585. te[3] = e10; te[4] = e11; te[5] = e12;
  91586. te[6] = e20; te[7] = e21; te[8] = e22;
  91587. return this;
  91588. },
  91589. multiply: function (s) {
  91590. var te = this.elements;
  91591. te[0] *= s; te[1] *= s; te[2] *= s;
  91592. te[3] *= s; te[4] *= s; te[5] *= s;
  91593. te[6] *= s; te[7] *= s; te[8] *= s;
  91594. return this;
  91595. },
  91596. add: function (m1, m2) {
  91597. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  91598. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  91599. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  91600. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  91601. return this;
  91602. },
  91603. addEqual: function (m) {
  91604. var te = this.elements, tem = m.elements;
  91605. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  91606. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  91607. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  91608. return this;
  91609. },
  91610. sub: function (m1, m2) {
  91611. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  91612. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  91613. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  91614. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  91615. return this;
  91616. },
  91617. subEqual: function (m) {
  91618. var te = this.elements, tem = m.elements;
  91619. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  91620. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  91621. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  91622. return this;
  91623. },
  91624. scale: function (m, s) {
  91625. var te = this.elements, tm = m.elements;
  91626. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  91627. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  91628. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  91629. return this;
  91630. },
  91631. scaleEqual: function (s) {
  91632. var te = this.elements;
  91633. te[0] *= s; te[1] *= s; te[2] *= s;
  91634. te[3] *= s; te[4] *= s; te[5] *= s;
  91635. te[6] *= s; te[7] *= s; te[8] *= s;
  91636. return this;
  91637. },
  91638. mul: function (m1, m2) {
  91639. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  91640. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  91641. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  91642. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  91643. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  91644. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  91645. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  91646. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  91647. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  91648. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  91649. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  91650. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  91651. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  91652. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  91653. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  91654. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  91655. return this;
  91656. },
  91657. mulScale: function (m, sx, sy, sz, Prepend) {
  91658. var prepend = Prepend || false;
  91659. var te = this.elements, tm = m.elements;
  91660. if (prepend) {
  91661. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  91662. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  91663. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  91664. } else {
  91665. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  91666. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  91667. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  91668. }
  91669. return this;
  91670. },
  91671. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  91672. var prepend = Prepend || false;
  91673. var s = OIMO.sin(rad);
  91674. var c = OIMO.cos(rad);
  91675. var c1 = 1 - c;
  91676. var r00 = ax * ax * c1 + c;
  91677. var r01 = ax * ay * c1 - az * s;
  91678. var r02 = ax * az * c1 + ay * s;
  91679. var r10 = ay * ax * c1 + az * s;
  91680. var r11 = ay * ay * c1 + c;
  91681. var r12 = ay * az * c1 - ax * s;
  91682. var r20 = az * ax * c1 - ay * s;
  91683. var r21 = az * ay * c1 + ax * s;
  91684. var r22 = az * az * c1 + c;
  91685. var tm = m.elements;
  91686. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  91687. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  91688. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  91689. var te = this.elements;
  91690. if (prepend) {
  91691. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  91692. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  91693. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  91694. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  91695. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  91696. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  91697. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  91698. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  91699. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  91700. } else {
  91701. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  91702. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  91703. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  91704. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  91705. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  91706. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  91707. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  91708. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  91709. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  91710. }
  91711. return this;
  91712. },
  91713. transpose: function (m) {
  91714. var te = this.elements, tm = m.elements;
  91715. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  91716. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  91717. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  91718. return this;
  91719. },
  91720. setQuat: function (q) {
  91721. var te = this.elements,
  91722. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  91723. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  91724. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  91725. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  91726. te[0] = 1 - yy - zz;
  91727. te[1] = xy - sz;
  91728. te[2] = xz + sy;
  91729. te[3] = xy + sz;
  91730. te[4] = 1 - xx - zz;
  91731. te[5] = yz - sx;
  91732. te[6] = xz - sy;
  91733. te[7] = yz + sx;
  91734. te[8] = 1 - xx - yy;
  91735. return this;
  91736. },
  91737. invert: function (m) {
  91738. var te = this.elements, tm = m.elements,
  91739. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  91740. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  91741. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  91742. b01 = a4 * a8 - a7 * a5,
  91743. b11 = a7 * a2 - a1 * a8,
  91744. b21 = a1 * a5 - a4 * a2,
  91745. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  91746. if (dt != 0) { dt = 1.0 / dt; }
  91747. te[0] = dt * b01;//(a4*a8 - a5*a7);
  91748. te[1] = dt * b11;//(a2*a7 - a1*a8);
  91749. te[2] = dt * b21;//(a1*a5 - a2*a4);
  91750. te[3] = dt * (a5 * a6 - a3 * a8);
  91751. te[4] = dt * (a0 * a8 - a2 * a6);
  91752. te[5] = dt * (a2 * a3 - a0 * a5);
  91753. te[6] = dt * (a3 * a7 - a4 * a6);
  91754. te[7] = dt * (a1 * a6 - a0 * a7);
  91755. te[8] = dt * (a0 * a4 - a1 * a3);
  91756. return this;
  91757. },
  91758. /*copy: function(m){
  91759. var te = this.elements, tem = m.elements;
  91760. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  91761. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  91762. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  91763. return this;
  91764. },*/
  91765. toEuler: function () { // not work !!
  91766. function clamp(x) {
  91767. return OIMO.min(OIMO.max(x, -1), 1);
  91768. }
  91769. var te = this.elements;
  91770. var m11 = te[0], m12 = te[3], m13 = te[6];
  91771. var m21 = te[1], m22 = te[4], m23 = te[7];
  91772. var m31 = te[2], m32 = te[5], m33 = te[8];
  91773. var p = new OIMO.Vec3();
  91774. var d = new OIMO.Quat();
  91775. var s;
  91776. p.y = OIMO.asin(clamp(m13));
  91777. if (OIMO.abs(m13) < 0.99999) {
  91778. p.x = OIMO.atan2(-m23, m33);
  91779. p.z = OIMO.atan2(-m12, m11);
  91780. } else {
  91781. p.x = OIMO.atan2(m32, m22);
  91782. p.z = 0;
  91783. }
  91784. return p;
  91785. },
  91786. /*clone: function(){
  91787. var te = this.elements;
  91788. return new OIMO.Mat33(
  91789. te[0], te[1], te[2],
  91790. te[3], te[4], te[5],
  91791. te[6], te[7], te[8]
  91792. );
  91793. },*/
  91794. toString: function () {
  91795. var te = this.elements;
  91796. var text =
  91797. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  91798. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  91799. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  91800. return text;
  91801. },
  91802. // OK
  91803. multiplyScalar: function (s) {
  91804. var te = this.elements;
  91805. te[0] *= s; te[3] *= s; te[6] *= s;
  91806. te[1] *= s; te[4] *= s; te[7] *= s;
  91807. te[2] *= s; te[5] *= s; te[8] *= s;
  91808. return this;
  91809. },
  91810. identity: function () {
  91811. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  91812. return this;
  91813. },
  91814. clone: function () {
  91815. return new this.constructor().fromArray(this.elements);
  91816. },
  91817. copy: function (m) {
  91818. var me = m.elements;
  91819. this.set(
  91820. me[0], me[3], me[6],
  91821. me[1], me[4], me[7],
  91822. me[2], me[5], me[8]
  91823. );
  91824. return this;
  91825. },
  91826. fromArray: function (array) {
  91827. this.elements.set(array);
  91828. return this;
  91829. },
  91830. toArray: function () {
  91831. var te = this.elements;
  91832. return [
  91833. te[0], te[1], te[2],
  91834. te[3], te[4], te[5],
  91835. te[6], te[7], te[8]
  91836. ];
  91837. }
  91838. };
  91839. OIMO.Quat = function (s, x, y, z) {
  91840. this.s = (s !== undefined) ? s : 1;
  91841. this.x = x || 0;
  91842. this.y = y || 0;
  91843. this.z = z || 0;
  91844. };
  91845. OIMO.Quat.prototype = {
  91846. constructor: OIMO.Quat,
  91847. set: function (x, y, z, w) {
  91848. this.x = x;
  91849. this.y = y;
  91850. this.z = z;
  91851. this.s = w;
  91852. return this;
  91853. },
  91854. init: function (s, x, y, z) {
  91855. this.s = (s !== undefined) ? s : 1;
  91856. this.x = x || 0;
  91857. this.y = y || 0;
  91858. this.z = z || 0;
  91859. return this;
  91860. },
  91861. add: function (q1, q2) {
  91862. this.s = q1.s + q2.s;
  91863. this.x = q1.x + q2.x;
  91864. this.y = q1.y + q2.y;
  91865. this.z = q1.z + q2.z;
  91866. return this;
  91867. },
  91868. addTime: function (v, t) {
  91869. var x = v.x;
  91870. var y = v.y;
  91871. var z = v.z;
  91872. var qs = this.s;
  91873. var qx = this.x;
  91874. var qy = this.y;
  91875. var qz = this.z;
  91876. t *= 0.5;
  91877. var ns = (-x * qx - y * qy - z * qz) * t;
  91878. var nx = (x * qs + y * qz - z * qy) * t;
  91879. var ny = (-x * qz + y * qs + z * qx) * t;
  91880. var nz = (x * qy - y * qx + z * qs) * t;
  91881. qs += ns;
  91882. qx += nx;
  91883. qy += ny;
  91884. qz += nz;
  91885. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  91886. this.s = qs * s;
  91887. this.x = qx * s;
  91888. this.y = qy * s;
  91889. this.z = qz * s;
  91890. return this;
  91891. },
  91892. sub: function (q1, q2) {
  91893. this.s = q1.s - q2.s;
  91894. this.x = q1.x - q2.x;
  91895. this.y = q1.y - q2.y;
  91896. this.z = q1.z - q2.z;
  91897. return this;
  91898. },
  91899. scale: function (q, s) {
  91900. this.s = q.s * s;
  91901. this.x = q.x * s;
  91902. this.y = q.y * s;
  91903. this.z = q.z * s;
  91904. return this;
  91905. },
  91906. mul: function (q1, q2) {
  91907. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  91908. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  91909. this.x = ax * bs + as * bx + ay * bz - az * by;
  91910. this.y = ay * bs + as * by + az * bx - ax * bz;
  91911. this.z = az * bs + as * bz + ax * by - ay * bx;
  91912. this.s = as * bs - ax * bx - ay * by - az * bz;
  91913. return this;
  91914. },
  91915. arc: function (v1, v2) {
  91916. var x1 = v1.x;
  91917. var y1 = v1.y;
  91918. var z1 = v1.z;
  91919. var x2 = v2.x;
  91920. var y2 = v2.y;
  91921. var z2 = v2.z;
  91922. var d = x1 * x2 + y1 * y2 + z1 * z2;
  91923. if (d == -1) {
  91924. x2 = y1 * x1 - z1 * z1;
  91925. y2 = -z1 * y1 - x1 * x1;
  91926. z2 = x1 * z1 + y1 * y1;
  91927. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  91928. this.s = 0;
  91929. this.x = x2 * d;
  91930. this.y = y2 * d;
  91931. this.z = z2 * d;
  91932. return this;
  91933. }
  91934. var cx = y1 * z2 - z1 * y2;
  91935. var cy = z1 * x2 - x1 * z2;
  91936. var cz = x1 * y2 - y1 * x2;
  91937. this.s = OIMO.sqrt((1 + d) * 0.5);
  91938. d = 0.5 / this.s;
  91939. this.x = cx * d;
  91940. this.y = cy * d;
  91941. this.z = cz * d;
  91942. return this;
  91943. },
  91944. normalize: function (q) {
  91945. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  91946. if (len > 0) { len = 1 / len; }
  91947. this.s = q.s * len;
  91948. this.x = q.x * len;
  91949. this.y = q.y * len;
  91950. this.z = q.z * len;
  91951. return this;
  91952. },
  91953. invert: function (q) {
  91954. this.s = q.s;
  91955. this.x = -q.x;
  91956. this.y = -q.y;
  91957. this.z = -q.z;
  91958. return this;
  91959. },
  91960. length: function () {
  91961. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  91962. },
  91963. copy: function (q) {
  91964. this.s = q.s;
  91965. this.x = q.x;
  91966. this.y = q.y;
  91967. this.z = q.z;
  91968. return this;
  91969. },
  91970. testDiff: function (q) {
  91971. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  91972. else return false;
  91973. },
  91974. clone: function (q) {
  91975. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  91976. },
  91977. toString: function () {
  91978. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  91979. }
  91980. }
  91981. // for three easy export
  91982. OIMO.Quaternion = function (x, y, z, w) {
  91983. this.x = x || 0;
  91984. this.y = y || 0;
  91985. this.z = z || 0;
  91986. this.w = (w !== undefined) ? w : 1;
  91987. };
  91988. OIMO.Quaternion.prototype = {
  91989. constructor: OIMO.Quaternion,
  91990. setFromRotationMatrix: function (m) {
  91991. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  91992. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  91993. var te = m.elements,
  91994. m11 = te[0], m12 = te[1], m13 = te[2],
  91995. m21 = te[3], m22 = te[4], m23 = te[5],
  91996. m31 = te[6], m32 = te[7], m33 = te[8],
  91997. trace = m11 + m22 + m33,
  91998. s;
  91999. if (trace > 0) {
  92000. s = 0.5 / OIMO.sqrt(trace + 1.0);
  92001. this.w = 0.25 / s;
  92002. this.x = (m32 - m23) * s;
  92003. this.y = (m13 - m31) * s;
  92004. this.z = (m21 - m12) * s;
  92005. } else if (m11 > m22 && m11 > m33) {
  92006. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  92007. this.w = (m32 - m23) / s;
  92008. this.x = 0.25 * s;
  92009. this.y = (m12 + m21) / s;
  92010. this.z = (m13 + m31) / s;
  92011. } else if (m22 > m33) {
  92012. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  92013. this.w = (m13 - m31) / s;
  92014. this.x = (m12 + m21) / s;
  92015. this.y = 0.25 * s;
  92016. this.z = (m23 + m32) / s;
  92017. } else {
  92018. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  92019. this.w = (m21 - m12) / s;
  92020. this.x = (m13 + m31) / s;
  92021. this.y = (m23 + m32) / s;
  92022. this.z = 0.25 * s;
  92023. }
  92024. //this.onChangeCallback();
  92025. return this;
  92026. }
  92027. }
  92028. OIMO.Vec3 = function (x, y, z) {
  92029. this.x = x || 0;
  92030. this.y = y || 0;
  92031. this.z = z || 0;
  92032. };
  92033. OIMO.Vec3.prototype = {
  92034. constructor: OIMO.Vec3,
  92035. init: function (x, y, z) {
  92036. this.x = x || 0;
  92037. this.y = y || 0;
  92038. this.z = z || 0;
  92039. return this;
  92040. },
  92041. set: function (x, y, z) {
  92042. this.x = x;
  92043. this.y = y;
  92044. this.z = z;
  92045. return this;
  92046. },
  92047. add: function (v1, v2) {
  92048. this.x = v1.x + v2.x;
  92049. this.y = v1.y + v2.y;
  92050. this.z = v1.z + v2.z;
  92051. return this;
  92052. },
  92053. addEqual: function (v) {
  92054. this.x += v.x;
  92055. this.y += v.y;
  92056. this.z += v.z;
  92057. return this;
  92058. },
  92059. addTime: function (v, t) {
  92060. this.x += v.x * t;
  92061. this.y += v.y * t;
  92062. this.z += v.z * t;
  92063. return this;
  92064. },
  92065. sub: function (v1, v2) {
  92066. this.x = v1.x - v2.x;
  92067. this.y = v1.y - v2.y;
  92068. this.z = v1.z - v2.z;
  92069. return this;
  92070. },
  92071. subEqual: function (v) {
  92072. this.x -= v.x;
  92073. this.y -= v.y;
  92074. this.z -= v.z;
  92075. return this;
  92076. },
  92077. addScale: function (v, s) {
  92078. this.x += v.x * s;
  92079. this.y += v.y * s;
  92080. this.z += v.z * s;
  92081. return this;
  92082. },
  92083. scale: function (v, s) {
  92084. this.x = v.x * s;
  92085. this.y = v.y * s;
  92086. this.z = v.z * s;
  92087. return this;
  92088. },
  92089. scaleEqual: function (s) {
  92090. this.x *= s;
  92091. this.y *= s;
  92092. this.z *= s;
  92093. return this;
  92094. },
  92095. /*dot: function(v){
  92096. return this.x*v.x+this.y*v.y+this.z*v.z;
  92097. },*/
  92098. cross: function (v1, v2) {
  92099. var ax = v1.x, ay = v1.y, az = v1.z,
  92100. bx = v2.x, by = v2.y, bz = v2.z;
  92101. this.x = ay * bz - az * by;
  92102. this.y = az * bx - ax * bz;
  92103. this.z = ax * by - ay * bx;
  92104. return this;
  92105. },
  92106. mul: function (o, v, m) {
  92107. var te = m.elements;
  92108. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  92109. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  92110. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  92111. return this;
  92112. },
  92113. mulMat: function (m, v) {
  92114. var te = m.elements;
  92115. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  92116. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  92117. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  92118. return this;
  92119. },
  92120. normalize: function (v) {
  92121. var x = v.x, y = v.y, z = v.z;
  92122. var l = x * x + y * y + z * z;
  92123. if (l > 0) {
  92124. l = 1 / OIMO.sqrt(l);
  92125. this.x = x * l;
  92126. this.y = y * l;
  92127. this.z = z * l;
  92128. }
  92129. return this;
  92130. },
  92131. /*norm: function(){
  92132. var x = this.x, y = this.y, z = this.z;
  92133. var l = x*x + y*y + z*z;
  92134. if (l > 0) {
  92135. l = 1 / OIMO.sqrt(l);
  92136. this.x = x*l;
  92137. this.y = y*l;
  92138. this.z = z*l;
  92139. }
  92140. return this;
  92141. },*/
  92142. invert: function (v) {
  92143. this.x = -v.x;
  92144. this.y = -v.y;
  92145. this.z = -v.z;
  92146. return this;
  92147. },
  92148. /*length: function(){
  92149. var x = this.x, y = this.y, z = this.z;
  92150. return OIMO.sqrt(x*x + y*y + z*z);
  92151. },*/
  92152. negate: function () {
  92153. this.x = -this.x;
  92154. this.y = -this.y;
  92155. this.z = -this.z;
  92156. return this;
  92157. },
  92158. dot: function (v) {
  92159. return this.x * v.x + this.y * v.y + this.z * v.z;
  92160. },
  92161. lengthSq: function () {
  92162. return this.x * this.x + this.y * this.y + this.z * this.z;
  92163. },
  92164. length: function () {
  92165. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  92166. },
  92167. /*len: function(){
  92168. var x = this.x, y = this.y, z = this.z;
  92169. return x*x + y*y + z*z;
  92170. },*/
  92171. copy: function (v) {
  92172. this.x = v.x;
  92173. this.y = v.y;
  92174. this.z = v.z;
  92175. return this;
  92176. },
  92177. applyQuaternion: function (q) {
  92178. var x = this.x;
  92179. var y = this.y;
  92180. var z = this.z;
  92181. var qx = q.x;
  92182. var qy = q.y;
  92183. var qz = q.z;
  92184. var qs = q.s;
  92185. // calculate quat * vector
  92186. var ix = qs * x + qy * z - qz * y;
  92187. var iy = qs * y + qz * x - qx * z;
  92188. var iz = qs * z + qx * y - qy * x;
  92189. var iw = -qx * x - qy * y - qz * z;
  92190. // calculate result * inverse quat
  92191. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  92192. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  92193. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  92194. return this;
  92195. },
  92196. testZero: function () {
  92197. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  92198. else return false;
  92199. },
  92200. testDiff: function (v) {
  92201. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  92202. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  92203. //else return false;
  92204. },
  92205. equals: function (v) {
  92206. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  92207. },
  92208. clone: function () {
  92209. return new this.constructor(this.x, this.y, this.z);
  92210. },
  92211. toString: function () {
  92212. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  92213. },
  92214. multiplyScalar: function (scalar) {
  92215. if (isFinite(scalar)) {
  92216. this.x *= scalar;
  92217. this.y *= scalar;
  92218. this.z *= scalar;
  92219. } else {
  92220. this.x = 0;
  92221. this.y = 0;
  92222. this.z = 0;
  92223. }
  92224. return this;
  92225. },
  92226. divideScalar: function (scalar) {
  92227. return this.multiplyScalar(1 / scalar);
  92228. },
  92229. // TODO rename to normalize
  92230. norm: function () {
  92231. return this.divideScalar(this.length());
  92232. },
  92233. }
  92234. OIMO.Euler = function (x, y, z, order) {
  92235. this._x = x || 0;
  92236. this._y = y || 0;
  92237. this._z = z || 0;
  92238. this._order = order || OIMO.Euler.DefaultOrder;
  92239. };
  92240. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  92241. OIMO.Euler.DefaultOrder = 'XYZ';
  92242. OIMO.clamp = function (x, a, b) {
  92243. return (x < a) ? a : ((x > b) ? b : x);
  92244. }
  92245. OIMO.Euler.prototype = {
  92246. constructor: OIMO.Euler,
  92247. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  92248. get x() {
  92249. return this._x;
  92250. },
  92251. set x(value) {
  92252. this._x = value;
  92253. this.onChangeCallback();
  92254. },
  92255. get y() {
  92256. return this._y;
  92257. },
  92258. set y(value) {
  92259. this._y = value;
  92260. this.onChangeCallback();
  92261. },
  92262. get z() {
  92263. return this._z;
  92264. },
  92265. set z(value) {
  92266. this._z = value;
  92267. this.onChangeCallback();
  92268. },
  92269. get order() {
  92270. return this._order;
  92271. },
  92272. set order(value) {
  92273. this._order = value;
  92274. this.onChangeCallback();
  92275. },
  92276. set: function (x, y, z, order) {
  92277. this._x = x;
  92278. this._y = y;
  92279. this._z = z;
  92280. this._order = order || this._order;
  92281. this.onChangeCallback();
  92282. return this;
  92283. },
  92284. copy: function (euler) {
  92285. this._x = euler._x;
  92286. this._y = euler._y;
  92287. this._z = euler._z;
  92288. this._order = euler._order;
  92289. this.onChangeCallback();
  92290. return this;
  92291. },
  92292. setFromRotationMatrix: function (m, order) {
  92293. var clamp = OIMO.clamp;
  92294. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  92295. var te = m.elements;
  92296. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  92297. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  92298. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  92299. var m11 = te[0], m12 = te[1], m13 = te[2],
  92300. m21 = te[3], m22 = te[4], m23 = te[5],
  92301. m31 = te[6], m32 = te[7], m33 = te[8];
  92302. order = order || this._order;
  92303. if (order === 'XYZ') {
  92304. this._y = OIMO.asin(clamp(m13, -1, 1));
  92305. if (OIMO.abs(m13) < 0.99999) {
  92306. this._x = OIMO.atan2(-m23, m33);
  92307. this._z = OIMO.atan2(-m12, m11);
  92308. } else {
  92309. this._x = OIMO.atan2(m32, m22);
  92310. this._z = 0;
  92311. }
  92312. } else if (order === 'YXZ') {
  92313. this._x = OIMO.asin(-clamp(m23, -1, 1));
  92314. if (OIMO.abs(m23) < 0.99999) {
  92315. this._y = OIMO.atan2(m13, m33);
  92316. this._z = OIMO.atan2(m21, m22);
  92317. } else {
  92318. this._y = OIMO.atan2(-m31, m11);
  92319. this._z = 0;
  92320. }
  92321. } else if (order === 'ZXY') {
  92322. this._x = OIMO.asin(clamp(m32, -1, 1));
  92323. if (OIMO.abs(m32) < 0.99999) {
  92324. this._y = OIMO.atan2(-m31, m33);
  92325. this._z = OIMO.atan2(-m12, m22);
  92326. } else {
  92327. this._y = 0;
  92328. this._z = OIMO.atan2(m21, m11);
  92329. }
  92330. } else if (order === 'ZYX') {
  92331. this._y = OIMO.asin(-clamp(m31, -1, 1));
  92332. if (OIMO.abs(m31) < 0.99999) {
  92333. this._x = OIMO.atan2(m32, m33);
  92334. this._z = OIMO.atan2(m21, m11);
  92335. } else {
  92336. this._x = 0;
  92337. this._z = OIMO.atan2(-m12, m22);
  92338. }
  92339. } else if (order === 'YZX') {
  92340. this._z = OIMO.asin(clamp(m21, -1, 1));
  92341. if (OIMO.abs(m21) < 0.99999) {
  92342. this._x = OIMO.atan2(-m23, m22);
  92343. this._y = OIMO.atan2(-m31, m11);
  92344. } else {
  92345. this._x = 0;
  92346. this._y = OIMO.atan2(m13, m33);
  92347. }
  92348. } else if (order === 'XZY') {
  92349. this._z = OIMO.asin(-clamp(m12, -1, 1));
  92350. if (OIMO.abs(m12) < 0.99999) {
  92351. this._x = OIMO.atan2(m32, m22);
  92352. this._y = OIMO.atan2(m13, m11);
  92353. } else {
  92354. this._x = OIMO.atan2(-m23, m33);
  92355. this._y = 0;
  92356. }
  92357. } else {
  92358. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  92359. }
  92360. this._order = order;
  92361. this.onChangeCallback();
  92362. return this;
  92363. },
  92364. setFromQuaternion: function (q, order, update) {
  92365. var clamp = OIMO.clamp;
  92366. // q is assumed to be normalized
  92367. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  92368. var sqx = q.x * q.x;
  92369. var sqy = q.y * q.y;
  92370. var sqz = q.z * q.z;
  92371. var sqw = q.s * q.s;
  92372. order = order || this._order;
  92373. if (order === 'XYZ') {
  92374. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  92375. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  92376. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  92377. } else if (order === 'YXZ') {
  92378. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  92379. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  92380. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  92381. } else if (order === 'ZXY') {
  92382. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  92383. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  92384. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  92385. } else if (order === 'ZYX') {
  92386. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  92387. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  92388. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  92389. } else if (order === 'YZX') {
  92390. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  92391. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  92392. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  92393. } else if (order === 'XZY') {
  92394. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  92395. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  92396. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  92397. } else {
  92398. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  92399. }
  92400. this._order = order;
  92401. if (update !== false) this.onChangeCallback();
  92402. return this;
  92403. },
  92404. reorder: function () {
  92405. // WARNING: this discards revolution information -bhouston
  92406. var q = new OIMO.Quat();
  92407. return function (newOrder) {
  92408. q.setFromEuler(this);
  92409. this.setFromQuaternion(q, newOrder);
  92410. };
  92411. }(),
  92412. equals: function (euler) {
  92413. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  92414. },
  92415. fromArray: function (array) {
  92416. this._x = array[0];
  92417. this._y = array[1];
  92418. this._z = array[2];
  92419. if (array[3] !== undefined) this._order = array[3];
  92420. this.onChangeCallback();
  92421. return this;
  92422. },
  92423. toArray: function () {
  92424. return [this._x, this._y, this._z, this._order];
  92425. },
  92426. onChange: function (callback) {
  92427. this.onChangeCallback = callback;
  92428. return this;
  92429. },
  92430. onChangeCallback: function () { },
  92431. clone: function () {
  92432. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  92433. }
  92434. };
  92435. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  92436. var c1 = OIMO.cos(oy * 0.5);//heading
  92437. var s1 = OIMO.sin(oy * 0.5);
  92438. var c2 = OIMO.cos(oz * 0.5);//altitude
  92439. var s2 = OIMO.sin(oz * 0.5);
  92440. var c3 = OIMO.cos(ox * 0.5);//bank
  92441. var s3 = OIMO.sin(ox * 0.5);
  92442. var c1c2 = c1 * c2;
  92443. var s1s2 = s1 * s2;
  92444. var w = c1c2 * c3 - s1s2 * s3;
  92445. var x = c1c2 * s3 + s1s2 * c3;
  92446. var y = s1 * c2 * c3 + c1 * s2 * s3;
  92447. var z = c1 * s2 * c3 - s1 * c2 * s3;
  92448. var angle = 2 * OIMO.acos(w);
  92449. var norm = x * x + y * y + z * z;
  92450. if (norm < 0.001) {
  92451. x = 1;
  92452. y = z = 0;
  92453. } else {
  92454. norm = OIMO.sqrt(norm);
  92455. x /= norm;
  92456. y /= norm;
  92457. z /= norm;
  92458. }
  92459. return [angle, x, y, z];
  92460. }
  92461. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  92462. var ch = OIMO.cos(oy);//heading
  92463. var sh = OIMO.sin(oy);
  92464. var ca = OIMO.cos(oz);//altitude
  92465. var sa = OIMO.sin(oz);
  92466. var cb = OIMO.cos(ox);//bank
  92467. var sb = OIMO.sin(ox);
  92468. var mtx = new OIMO.Mat33();
  92469. var te = mtx.elements;
  92470. te[0] = ch * ca;
  92471. te[1] = sh * sb - ch * sa * cb;
  92472. te[2] = ch * sa * sb + sh * cb;
  92473. te[3] = sa;
  92474. te[4] = ca * cb;
  92475. te[5] = -ca * sb;
  92476. te[6] = -sh * ca;
  92477. te[7] = sh * sa * cb + ch * sb;
  92478. te[8] = -sh * sa * sb + ch * cb;
  92479. return mtx;
  92480. }
  92481. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  92482. var te = mtx.elements;
  92483. var x, y, z;
  92484. if (te[3] > 0.998) { // singularity at north pole
  92485. y = OIMO.atan2(te[2], te[8]);
  92486. z = OIMO.PI / 2;
  92487. x = 0;
  92488. } else if (te[3] < -0.998) { // singularity at south pole
  92489. y = OIMO.atan2(te[2], te[8]);
  92490. z = -OIMO.PI / 2;
  92491. x = 0;
  92492. } else {
  92493. y = OIMO.atan2(-te[6], te[0]);
  92494. x = OIMO.atan2(-te[5], te[4]);
  92495. z = OIMO.asin(te[3]);
  92496. }
  92497. return [x, y, z];
  92498. }
  92499. OIMO.unwrapDegrees = function (r) {
  92500. r = r % 360;
  92501. if (r > 180) r -= 360;
  92502. if (r < -180) r += 360;
  92503. return r;
  92504. }
  92505. OIMO.unwrapRadian = function (r) {
  92506. r = r % OIMO.TwoPI;
  92507. if (r > OIMO.PI) r -= OIMO.TwoPI;
  92508. if (r < -OIMO.PI) r += OIMO.TwoPI;
  92509. return r;
  92510. }
  92511. OIMO.Distance3d = function (p1, p2) {
  92512. var xd = p2[0] - p1[0];
  92513. var yd = p2[1] - p1[1];
  92514. var zd = p2[2] - p1[2];
  92515. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  92516. }
  92517. /**
  92518. * The base class of all type of the constraints.
  92519. * @author saharan
  92520. */
  92521. OIMO.Constraint = function () {
  92522. // The parent world of the constraint.
  92523. this.parent = null;
  92524. // The first body of the constraint.
  92525. this.body1 = null;
  92526. // The second body of the constraint.
  92527. this.body2 = null;
  92528. // Internal
  92529. this.addedToIsland = false;
  92530. }
  92531. OIMO.Constraint.prototype = {
  92532. constructor: OIMO.Constraint,
  92533. /**
  92534. * Prepare for solving the constraint.
  92535. * @param timeStep
  92536. * @param invTimeStep
  92537. */
  92538. preSolve: function (timeStep, invTimeStep) {
  92539. OIMO.Error("Constraint", "Inheritance error.");
  92540. },
  92541. /**
  92542. * Solve the constraint.
  92543. * This is usually called iteratively.
  92544. */
  92545. solve: function () {
  92546. OIMO.Error("Constraint", "Inheritance error.");
  92547. },
  92548. /**
  92549. * Do the post-processing.
  92550. */
  92551. postSolve: function () {
  92552. OIMO.Error("Constraint", "Inheritance error.");
  92553. }
  92554. }
  92555. /**
  92556. * Joints are used to constrain the motion between two rigid bodies.
  92557. * @author saharan
  92558. * @author lo-th
  92559. */
  92560. OIMO.Joint = function (config) {
  92561. OIMO.Constraint.call(this);
  92562. // joint name
  92563. this.name = "";
  92564. // The type of the joint.
  92565. this.type = OIMO.JOINT_NULL;
  92566. // The previous joint in the world.
  92567. this.prev = null;
  92568. // The next joint in the world.
  92569. this.next = null;
  92570. this.body1 = config.body1;
  92571. this.body2 = config.body2;
  92572. // The anchor point on the first rigid body in local coordinate system.
  92573. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  92574. // The anchor point on the second rigid body in local coordinate system.
  92575. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  92576. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  92577. this.relativeAnchorPoint1 = new OIMO.Vec3();
  92578. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  92579. this.relativeAnchorPoint2 = new OIMO.Vec3();
  92580. // The anchor point on the first rigid body in world coordinate system.
  92581. this.anchorPoint1 = new OIMO.Vec3();
  92582. // The anchor point on the second rigid body in world coordinate system.
  92583. this.anchorPoint2 = new OIMO.Vec3();
  92584. // Whether allow collision between connected rigid bodies or not.
  92585. this.allowCollision = config.allowCollision;
  92586. this.b1Link = new OIMO.JointLink(this);
  92587. this.b2Link = new OIMO.JointLink(this);
  92588. this.matrix = new OIMO.Mat44();
  92589. };
  92590. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  92591. OIMO.Joint.prototype.constructor = OIMO.Joint;
  92592. // Update all the anchor points.
  92593. OIMO.Joint.prototype.updateAnchorPoints = function () {
  92594. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  92595. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  92596. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  92597. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  92598. };
  92599. // Attach the joint from the bodies.
  92600. OIMO.Joint.prototype.attach = function () {
  92601. this.b1Link.body = this.body2;
  92602. this.b2Link.body = this.body1;
  92603. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  92604. else this.b1Link.next = null;
  92605. this.body1.jointLink = this.b1Link;
  92606. this.body1.numJoints++;
  92607. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  92608. else this.b2Link.next = null;
  92609. this.body2.jointLink = this.b2Link;
  92610. this.body2.numJoints++;
  92611. };
  92612. // Detach the joint from the bodies.
  92613. OIMO.Joint.prototype.detach = function () {
  92614. var prev = this.b1Link.prev;
  92615. var next = this.b1Link.next;
  92616. if (prev != null) prev.next = next;
  92617. if (next != null) next.prev = prev;
  92618. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  92619. this.b1Link.prev = null;
  92620. this.b1Link.next = null;
  92621. this.b1Link.body = null;
  92622. this.body1.numJoints--;
  92623. prev = this.b2Link.prev;
  92624. next = this.b2Link.next;
  92625. if (prev != null) prev.next = next;
  92626. if (next != null) next.prev = prev;
  92627. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  92628. this.b2Link.prev = null;
  92629. this.b2Link.next = null;
  92630. this.b2Link.body = null;
  92631. this.body2.numJoints--;
  92632. this.b1Link.body = null;
  92633. this.b2Link.body = null;
  92634. };
  92635. // Awake the bodies.
  92636. OIMO.Joint.prototype.awake = function () {
  92637. this.body1.awake();
  92638. this.body2.awake();
  92639. };
  92640. // calculation function
  92641. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  92642. };
  92643. OIMO.Joint.prototype.solve = function () {
  92644. };
  92645. OIMO.Joint.prototype.postSolve = function () {
  92646. };
  92647. // Delete process
  92648. OIMO.Joint.prototype.remove = function () {
  92649. this.dispose();
  92650. };
  92651. OIMO.Joint.prototype.dispose = function () {
  92652. this.parent.removeJoint(this);
  92653. };
  92654. // Three js add
  92655. OIMO.Joint.prototype.getPosition = function () {
  92656. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  92657. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  92658. return [p1, p2];
  92659. };
  92660. OIMO.Joint.prototype.getMatrix = function () {
  92661. var m = this.matrix.elements;
  92662. var p1 = this.anchorPoint1;
  92663. var p2 = this.anchorPoint2;
  92664. m[0] = p1.x * OIMO.WORLD_SCALE;
  92665. m[1] = p1.y * OIMO.WORLD_SCALE;
  92666. m[2] = p1.z * OIMO.WORLD_SCALE;
  92667. m[3] = 0;
  92668. m[4] = p2.x * OIMO.WORLD_SCALE;
  92669. m[5] = p2.y * OIMO.WORLD_SCALE;
  92670. m[6] = p2.z * OIMO.WORLD_SCALE;
  92671. m[7] = 0;
  92672. return m;
  92673. };
  92674. /**
  92675. * A joint configuration holds all configuration data for constructing a joint.
  92676. * Joint configurations can be reused safely.
  92677. * @author saharan
  92678. */
  92679. OIMO.JointConfig = function () {
  92680. // The first rigid body of the joint.
  92681. this.body1 = null;
  92682. // The second rigid body of the joint.
  92683. this.body2 = null;
  92684. // The anchor point on the first rigid body in local coordinate system.
  92685. this.localAnchorPoint1 = new OIMO.Vec3();
  92686. // The anchor point on the second rigid body in local coordinate system.
  92687. this.localAnchorPoint2 = new OIMO.Vec3();
  92688. // The axis in the first body's coordinate system.
  92689. // his property is available in some joints.
  92690. this.localAxis1 = new OIMO.Vec3();
  92691. // The axis in the second body's coordinate system.
  92692. // This property is available in some joints.
  92693. this.localAxis2 = new OIMO.Vec3();
  92694. // Whether allow collision between connected rigid bodies or not.
  92695. this.allowCollision = false;
  92696. };
  92697. /**
  92698. * A link list of joints.
  92699. * @author saharan
  92700. */
  92701. OIMO.JointLink = function (joint) {
  92702. // The previous joint link.
  92703. this.prev = null;
  92704. // The next joint link.
  92705. this.next = null;
  92706. // The other rigid body connected to the joint.
  92707. this.body = null;
  92708. // The joint of the link.
  92709. this.joint = joint;
  92710. };
  92711. /**
  92712. * An information of limit and motor.
  92713. * @author saharan
  92714. */
  92715. OIMO.LimitMotor = function (axis, fixed) {
  92716. fixed = fixed || false;
  92717. // The axis of the constraint.
  92718. this.axis = axis;
  92719. // The current angle for rotational constraints.
  92720. this.angle = 0;
  92721. // The lower limit. Set lower > upper to disable
  92722. this.lowerLimit = fixed ? 0 : 1;
  92723. //if(fixed)this.lowerLimit = 0;
  92724. //else this.lowerLimit = 1;
  92725. // The upper limit. Set lower > upper to disable.
  92726. this.upperLimit = 0;
  92727. // The target motor speed.
  92728. this.motorSpeed = 0;
  92729. // The maximum motor force or torque. Set 0 to disable.
  92730. this.maxMotorForce = 0;
  92731. // The frequency of the spring. Set 0 to disable.
  92732. this.frequency = 0;
  92733. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  92734. this.dampingRatio = 0;
  92735. };
  92736. OIMO.LimitMotor.prototype = {
  92737. constructor: OIMO.LimitMotor,
  92738. /**
  92739. * Set limit data into this constraint.
  92740. * @param lowerLimit
  92741. * @param upperLimit
  92742. */
  92743. setLimit: function (lowerLimit, upperLimit) {
  92744. this.lowerLimit = lowerLimit;
  92745. this.upperLimit = upperLimit;
  92746. },
  92747. /**
  92748. * Set motor data into this constraint.
  92749. * @param motorSpeed
  92750. * @param maxMotorForce
  92751. */
  92752. setMotor: function (motorSpeed, maxMotorForce) {
  92753. this.motorSpeed = motorSpeed;
  92754. this.maxMotorForce = maxMotorForce;
  92755. },
  92756. /**
  92757. * Set spring data into this constraint.
  92758. * @param frequency
  92759. * @param dampingRatio
  92760. */
  92761. setSpring: function (frequency, dampingRatio) {
  92762. this.frequency = frequency;
  92763. this.dampingRatio = dampingRatio;
  92764. }
  92765. };
  92766. /**
  92767. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  92768. * @author saharan
  92769. * @author lo-th
  92770. */
  92771. OIMO.BallAndSocketJoint = function (config) {
  92772. OIMO.Joint.call(this, config);
  92773. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  92774. this.lc = new OIMO.LinearConstraint(this);
  92775. };
  92776. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  92777. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  92778. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  92779. this.updateAnchorPoints();
  92780. this.lc.preSolve(timeStep, invTimeStep);
  92781. };
  92782. OIMO.BallAndSocketJoint.prototype.solve = function () {
  92783. this.lc.solve();
  92784. };
  92785. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  92786. };
  92787. /**
  92788. * A distance joint limits the distance between two anchor points on rigid bodies.
  92789. * @author saharan
  92790. * @author lo-th
  92791. */
  92792. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  92793. OIMO.Joint.call(this, config);
  92794. this.type = OIMO.JOINT_DISTANCE;
  92795. this.normal = new OIMO.Vec3();
  92796. this.nr = new OIMO.Vec3();
  92797. // The limit and motor information of the joint.
  92798. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  92799. this.limitMotor.lowerLimit = minDistance;
  92800. this.limitMotor.upperLimit = maxDistance;
  92801. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  92802. };
  92803. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  92804. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  92805. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  92806. this.updateAnchorPoints();
  92807. //var nr = this.nr;
  92808. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  92809. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  92810. //if(len>0) len = 1/len;
  92811. //this.normal.scale( nr, len );
  92812. this.normal.normalize(this.nr);
  92813. this.t.preSolve(timeStep, invTimeStep);
  92814. };
  92815. OIMO.DistanceJoint.prototype.solve = function () {
  92816. this.t.solve();
  92817. };
  92818. OIMO.DistanceJoint.prototype.postSolve = function () {
  92819. };
  92820. /**
  92821. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  92822. * @author saharan
  92823. * @author lo-th
  92824. */
  92825. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  92826. OIMO.Joint.call(this, config);
  92827. this.type = OIMO.JOINT_HINGE;
  92828. // The axis in the first body's coordinate system.
  92829. this.localAxis1 = config.localAxis1.clone().norm();
  92830. // The axis in the second body's coordinate system.
  92831. this.localAxis2 = config.localAxis2.clone().norm();
  92832. // make angle axis 1
  92833. this.localAngle1 = new OIMO.Vec3(
  92834. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  92835. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  92836. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  92837. ).norm();
  92838. // make angle axis 2
  92839. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  92840. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  92841. this.nor = new OIMO.Vec3();
  92842. this.tan = new OIMO.Vec3();
  92843. this.bin = new OIMO.Vec3();
  92844. this.ax1 = new OIMO.Vec3();
  92845. this.ax2 = new OIMO.Vec3();
  92846. this.an1 = new OIMO.Vec3();
  92847. this.an2 = new OIMO.Vec3();
  92848. // The rotational limit and motor information of the joint.
  92849. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  92850. this.limitMotor.lowerLimit = lowerAngleLimit;
  92851. this.limitMotor.upperLimit = upperAngleLimit;
  92852. this.lc = new OIMO.LinearConstraint(this);
  92853. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  92854. };
  92855. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  92856. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  92857. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  92858. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  92859. this.updateAnchorPoints();
  92860. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  92861. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  92862. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  92863. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  92864. this.nor.set(
  92865. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  92866. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  92867. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  92868. ).norm();
  92869. this.tan.set(
  92870. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  92871. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  92872. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  92873. ).norm();
  92874. this.bin.set(
  92875. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  92876. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  92877. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  92878. );
  92879. // calculate hinge angle
  92880. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  92881. if (
  92882. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  92883. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  92884. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  92885. ) {
  92886. this.limitMotor.angle = -limite;
  92887. } else {
  92888. this.limitMotor.angle = limite;
  92889. }
  92890. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  92891. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  92892. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  92893. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  92894. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  92895. this.r3.preSolve(timeStep, invTimeStep);
  92896. this.lc.preSolve(timeStep, invTimeStep);
  92897. };
  92898. OIMO.HingeJoint.prototype.solve = function () {
  92899. this.r3.solve();
  92900. this.lc.solve();
  92901. };
  92902. OIMO.HingeJoint.prototype.postSolve = function () {
  92903. };
  92904. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  92905. if (cos > 1) return 0;
  92906. else if (cos < -1) return OIMO.PI;
  92907. else return OIMO.acos(cos);
  92908. };
  92909. /**
  92910. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  92911. * @author saharan
  92912. * @author lo-th
  92913. */
  92914. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  92915. OIMO.Joint.call(this, config);
  92916. this.type = OIMO.JOINT_PRISMATIC;
  92917. // The axis in the first body's coordinate system.
  92918. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  92919. // The axis in the second body's coordinate system.
  92920. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  92921. this.localAxis1X = this.localAxis1.x;
  92922. this.localAxis1Y = this.localAxis1.y;
  92923. this.localAxis1Z = this.localAxis1.z;
  92924. this.localAxis2X = this.localAxis2.x;
  92925. this.localAxis2Y = this.localAxis2.y;
  92926. this.localAxis2Z = this.localAxis2.z;
  92927. this.nor = new OIMO.Vec3();
  92928. this.tan = new OIMO.Vec3();
  92929. this.bin = new OIMO.Vec3();
  92930. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  92931. // The translational limit and motor information of the joint.
  92932. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  92933. this.limitMotor.lowerLimit = lowerTranslation;
  92934. this.limitMotor.upperLimit = upperTranslation;
  92935. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  92936. };
  92937. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  92938. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  92939. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  92940. var tmpM;
  92941. var tmp1X;
  92942. var tmp1Y;
  92943. var tmp1Z;
  92944. this.updateAnchorPoints();
  92945. tmpM = this.body1.rotation.elements;
  92946. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  92947. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  92948. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  92949. tmpM = this.body2.rotation.elements;
  92950. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  92951. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  92952. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  92953. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  92954. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  92955. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  92956. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  92957. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  92958. nx *= tmp1X;
  92959. ny *= tmp1X;
  92960. nz *= tmp1X;
  92961. var tx = ny * nx - nz * nz;
  92962. var ty = -nz * ny - nx * nx;
  92963. var tz = nx * nz + ny * ny;
  92964. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  92965. tx *= tmp1X;
  92966. ty *= tmp1X;
  92967. tz *= tmp1X;
  92968. var bx = ny * tz - nz * ty;
  92969. var by = nz * tx - nx * tz;
  92970. var bz = nx * ty - ny * tx;
  92971. this.nor.init(nx, ny, nz);
  92972. this.tan.init(tx, ty, tz);
  92973. this.bin.init(bx, by, bz);
  92974. this.ac.preSolve(timeStep, invTimeStep);
  92975. this.t3.preSolve(timeStep, invTimeStep);
  92976. };
  92977. OIMO.PrismaticJoint.prototype.solve = function () {
  92978. this.ac.solve();
  92979. this.t3.solve();
  92980. };
  92981. OIMO.PrismaticJoint.prototype.postSolve = function () {
  92982. };
  92983. /**
  92984. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  92985. * @author saharan
  92986. * @author lo-th
  92987. */
  92988. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  92989. OIMO.Joint.call(this, config);
  92990. this.type = OIMO.JOINT_SLIDER;
  92991. // The first axis in local coordinate system.
  92992. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  92993. // The second axis in local coordinate system.
  92994. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  92995. var len;
  92996. this.localAxis1X = this.localAxis1.x;
  92997. this.localAxis1Y = this.localAxis1.y;
  92998. this.localAxis1Z = this.localAxis1.z;
  92999. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  93000. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  93001. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  93002. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  93003. this.localAngAxis1X *= len;
  93004. this.localAngAxis1Y *= len;
  93005. this.localAngAxis1Z *= len;
  93006. this.localAxis2X = this.localAxis2.x;
  93007. this.localAxis2Y = this.localAxis2.y;
  93008. this.localAxis2Z = this.localAxis2.z;
  93009. // make angle axis 2
  93010. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  93011. var tarc = arc.elements;
  93012. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  93013. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  93014. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  93015. this.nor = new OIMO.Vec3();
  93016. this.tan = new OIMO.Vec3();
  93017. this.bin = new OIMO.Vec3();
  93018. // The limit and motor for the rotation
  93019. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  93020. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  93021. // The limit and motor for the translation.
  93022. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  93023. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  93024. this.translationalLimitMotor.upperLimit = upperTranslation;
  93025. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  93026. };
  93027. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  93028. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  93029. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  93030. var tmpM;
  93031. var tmp1X;
  93032. var tmp1Y;
  93033. var tmp1Z;
  93034. this.updateAnchorPoints();
  93035. tmpM = this.body1.rotation.elements;
  93036. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  93037. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  93038. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  93039. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  93040. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  93041. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  93042. tmpM = this.body2.rotation.elements;
  93043. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  93044. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  93045. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  93046. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  93047. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  93048. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  93049. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  93050. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  93051. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  93052. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  93053. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  93054. nx *= tmp1X;
  93055. ny *= tmp1X;
  93056. nz *= tmp1X;
  93057. var tx = ny * nx - nz * nz;
  93058. var ty = -nz * ny - nx * nx;
  93059. var tz = nx * nz + ny * ny;
  93060. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  93061. tx *= tmp1X;
  93062. ty *= tmp1X;
  93063. tz *= tmp1X;
  93064. var bx = ny * tz - nz * ty;
  93065. var by = nz * tx - nx * tz;
  93066. var bz = nx * ty - ny * tx;
  93067. this.nor.init(nx, ny, nz);
  93068. this.tan.init(tx, ty, tz);
  93069. this.bin.init(bx, by, bz);
  93070. // ----------------------------------------------
  93071. // calculate hinge angle
  93072. // ----------------------------------------------
  93073. if (
  93074. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  93075. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  93076. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  93077. ) {
  93078. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  93079. } else {
  93080. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  93081. }
  93082. // angular error
  93083. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  93084. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  93085. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  93086. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  93087. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  93088. this.r3.preSolve(timeStep, invTimeStep);
  93089. this.t3.preSolve(timeStep, invTimeStep);
  93090. };
  93091. OIMO.SliderJoint.prototype.solve = function () {
  93092. this.r3.solve();
  93093. this.t3.solve();
  93094. };
  93095. OIMO.SliderJoint.prototype.postSolve = function () {
  93096. };
  93097. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  93098. if (cos > 1) return 0;
  93099. else if (cos < -1) return OIMO.PI;
  93100. else return OIMO.acos(cos);
  93101. };
  93102. /**
  93103. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  93104. * The wheel joint also allows for relative translation for the suspension.
  93105. * @author saharan
  93106. * @author lo-th
  93107. */
  93108. OIMO.WheelJoint = function (config) {
  93109. OIMO.Joint.call(this, config);
  93110. this.type = OIMO.JOINT_WHEEL;
  93111. // The first axis in local coordinate system.
  93112. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  93113. // The second axis in local coordinate system.
  93114. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  93115. var len;
  93116. this.localAxis1X = this.localAxis1.x;
  93117. this.localAxis1Y = this.localAxis1.y;
  93118. this.localAxis1Z = this.localAxis1.z;
  93119. this.localAxis2X = this.localAxis2.x;
  93120. this.localAxis2Y = this.localAxis2.y;
  93121. this.localAxis2Z = this.localAxis2.z;
  93122. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  93123. if (dot > -1 && dot < 1) {
  93124. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  93125. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  93126. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  93127. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  93128. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  93129. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  93130. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  93131. this.localAngAxis1X *= len;
  93132. this.localAngAxis1Y *= len;
  93133. this.localAngAxis1Z *= len;
  93134. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  93135. this.localAngAxis2X *= len;
  93136. this.localAngAxis2Y *= len;
  93137. this.localAngAxis2Z *= len;
  93138. } else {
  93139. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  93140. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  93141. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  93142. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  93143. this.localAngAxis1X *= len;
  93144. this.localAngAxis1Y *= len;
  93145. this.localAngAxis1Z *= len;
  93146. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  93147. var tarc = arc.elements;
  93148. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  93149. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  93150. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  93151. }
  93152. this.nor = new OIMO.Vec3();
  93153. this.tan = new OIMO.Vec3();
  93154. this.bin = new OIMO.Vec3();
  93155. // The translational limit and motor information of the joint.
  93156. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  93157. this.translationalLimitMotor.frequency = 8;
  93158. this.translationalLimitMotor.dampingRatio = 1;
  93159. // The first rotational limit and motor information of the joint.
  93160. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  93161. // The second rotational limit and motor information of the joint.
  93162. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  93163. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  93164. this.t3.weight = 1;
  93165. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  93166. };
  93167. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  93168. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  93169. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  93170. var tmpM;
  93171. var tmp1X;
  93172. var tmp1Y;
  93173. var tmp1Z;
  93174. this.updateAnchorPoints();
  93175. tmpM = this.body1.rotation.elements;
  93176. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  93177. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  93178. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  93179. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  93180. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  93181. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  93182. tmpM = this.body2.rotation.elements;
  93183. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  93184. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  93185. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  93186. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  93187. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  93188. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  93189. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  93190. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  93191. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  93192. } else {
  93193. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  93194. }
  93195. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  93196. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  93197. } else {
  93198. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  93199. }
  93200. var nx = y2 * z1 - z2 * y1;
  93201. var ny = z2 * x1 - x2 * z1;
  93202. var nz = x2 * y1 - y2 * x1;
  93203. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  93204. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  93205. nx *= tmp1X;
  93206. ny *= tmp1X;
  93207. nz *= tmp1X;
  93208. var tx = ny * z2 - nz * y2;
  93209. var ty = nz * x2 - nx * z2;
  93210. var tz = nx * y2 - ny * x2;
  93211. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  93212. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  93213. tx *= tmp1X;
  93214. ty *= tmp1X;
  93215. tz *= tmp1X;
  93216. var bx = y1 * nz - z1 * ny;
  93217. var by = z1 * nx - x1 * nz;
  93218. var bz = x1 * ny - y1 * nx;
  93219. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  93220. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  93221. bx *= tmp1X;
  93222. by *= tmp1X;
  93223. bz *= tmp1X;
  93224. this.nor.init(nx, ny, nz);
  93225. this.tan.init(tx, ty, tz);
  93226. this.bin.init(bx, by, bz);
  93227. this.r3.preSolve(timeStep, invTimeStep);
  93228. this.t3.preSolve(timeStep, invTimeStep);
  93229. };
  93230. OIMO.WheelJoint.prototype.solve = function () {
  93231. this.r3.solve();
  93232. this.t3.solve();
  93233. };
  93234. OIMO.WheelJoint.prototype.postSolve = function () {
  93235. };
  93236. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  93237. if (cos > 1) return 0;
  93238. else if (cos < -1) return OIMO.PI;
  93239. else return OIMO.acos(cos);
  93240. };
  93241. /**
  93242. * An angular constraint for all axes for various joints.
  93243. * @author saharan
  93244. */
  93245. OIMO.AngularConstraint = function (joint, targetOrientation) {
  93246. this.joint = joint;
  93247. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  93248. this.relativeOrientation = new OIMO.Quat();
  93249. this.ii1 = null;
  93250. this.ii2 = null;
  93251. this.dd = null;
  93252. this.vel = new OIMO.Vec3();
  93253. this.imp = new OIMO.Vec3();
  93254. this.rn0 = new OIMO.Vec3();
  93255. this.rn1 = new OIMO.Vec3();
  93256. this.rn2 = new OIMO.Vec3();
  93257. this.b1 = joint.body1;
  93258. this.b2 = joint.body2;
  93259. this.a1 = this.b1.angularVelocity;
  93260. this.a2 = this.b2.angularVelocity;
  93261. this.i1 = this.b1.inverseInertia;
  93262. this.i2 = this.b2.inverseInertia;
  93263. };
  93264. OIMO.AngularConstraint.prototype = {
  93265. constructor: OIMO.AngularConstraint,
  93266. preSolve: function (timeStep, invTimeStep) {
  93267. var inv, len, v, vv;
  93268. this.ii1 = this.i1.clone();
  93269. this.ii2 = this.i2.clone();
  93270. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  93271. 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]));
  93272. this.dd = new OIMO.Mat33(
  93273. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  93274. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  93275. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  93276. ).multiply(inv);
  93277. this.relativeOrientation.invert(this.b1.orientation);
  93278. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  93279. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  93280. inv = this.relativeOrientation.s * 2;
  93281. this.vel.scale(this.relativeOrientation, inv);
  93282. len = this.vel.length();
  93283. if (len > 0.02) {
  93284. len = (0.02 - len) / len * invTimeStep * 0.05;
  93285. this.vel.scaleEqual(len);
  93286. } else {
  93287. this.vel.init();
  93288. }
  93289. this.rn1.mulMat(this.ii1, this.imp);
  93290. this.rn2.mulMat(this.ii2, this.imp);
  93291. this.a1.addEqual(this.rn1);
  93292. this.a2.subEqual(this.rn2);
  93293. },
  93294. solve: function () {
  93295. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  93296. this.rn0.mulMat(this.dd, r);
  93297. this.rn1.mulMat(this.ii1, this.rn0);
  93298. this.rn2.mulMat(this.ii2, this.rn0);
  93299. this.imp.addEqual(this.rn0);
  93300. this.a1.addEqual(this.rn1);
  93301. this.a2.subEqual(this.rn2);
  93302. }
  93303. };
  93304. /**
  93305. * A linear constraint for all axes for various joints.
  93306. * @author saharan
  93307. */
  93308. OIMO.LinearConstraint = function (joint) {
  93309. this.m1 = NaN;
  93310. this.m2 = NaN;
  93311. this.ii1 = null;
  93312. this.ii2 = null;
  93313. this.dd = null;
  93314. this.r1x = NaN;
  93315. this.r1y = NaN;
  93316. this.r1z = NaN;
  93317. this.r2x = NaN;
  93318. this.r2y = NaN;
  93319. this.r2z = NaN;
  93320. this.ax1x = NaN;
  93321. this.ax1y = NaN;
  93322. this.ax1z = NaN;
  93323. this.ay1x = NaN;
  93324. this.ay1y = NaN;
  93325. this.ay1z = NaN;
  93326. this.az1x = NaN;
  93327. this.az1y = NaN;
  93328. this.az1z = NaN;
  93329. this.ax2x = NaN;
  93330. this.ax2y = NaN;
  93331. this.ax2z = NaN;
  93332. this.ay2x = NaN;
  93333. this.ay2y = NaN;
  93334. this.ay2z = NaN;
  93335. this.az2x = NaN;
  93336. this.az2y = NaN;
  93337. this.az2z = NaN;
  93338. this.vel = NaN;
  93339. this.velx = NaN;
  93340. this.vely = NaN;
  93341. this.velz = NaN;
  93342. this.joint = joint;
  93343. this.r1 = joint.relativeAnchorPoint1;
  93344. this.r2 = joint.relativeAnchorPoint2;
  93345. this.p1 = joint.anchorPoint1;
  93346. this.p2 = joint.anchorPoint2;
  93347. this.b1 = joint.body1;
  93348. this.b2 = joint.body2;
  93349. this.l1 = this.b1.linearVelocity;
  93350. this.l2 = this.b2.linearVelocity;
  93351. this.a1 = this.b1.angularVelocity;
  93352. this.a2 = this.b2.angularVelocity;
  93353. this.i1 = this.b1.inverseInertia;
  93354. this.i2 = this.b2.inverseInertia;
  93355. this.impx = 0;
  93356. this.impy = 0;
  93357. this.impz = 0;
  93358. }
  93359. OIMO.LinearConstraint.prototype = {
  93360. constructor: OIMO.LinearConstraint,
  93361. preSolve: function (timeStep, invTimeStep) {
  93362. this.r1x = this.r1.x;
  93363. this.r1y = this.r1.y;
  93364. this.r1z = this.r1.z;
  93365. this.r2x = this.r2.x;
  93366. this.r2y = this.r2.y;
  93367. this.r2z = this.r2.z;
  93368. this.m1 = this.b1.inverseMass;
  93369. this.m2 = this.b2.inverseMass;
  93370. this.ii1 = this.i1.clone();
  93371. this.ii2 = this.i2.clone();
  93372. var ii1 = this.ii1.elements;
  93373. var ii2 = this.ii2.elements;
  93374. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  93375. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  93376. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  93377. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  93378. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  93379. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  93380. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  93381. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  93382. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  93383. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  93384. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  93385. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  93386. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  93387. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  93388. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  93389. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  93390. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  93391. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  93392. // calculate point-to-point mass matrix
  93393. // from impulse equation
  93394. //
  93395. // M = ([/m] - [r^][/I][r^]) ^ -1
  93396. //
  93397. // where
  93398. //
  93399. // [/m] = |1/m, 0, 0|
  93400. // |0, 1/m, 0|
  93401. // |0, 0, 1/m|
  93402. //
  93403. // [r^] = |0, -rz, ry|
  93404. // |rz, 0, -rx|
  93405. // |-ry, rx, 0|
  93406. //
  93407. // [/I] = Inverted moment inertia
  93408. var rxx = this.m1 + this.m2;
  93409. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  93410. var k = kk.elements;
  93411. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  93412. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  93413. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  93414. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  93415. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  93416. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  93417. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  93418. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  93419. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  93420. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  93421. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  93422. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  93423. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  93424. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  93425. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  93426. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  93427. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  93428. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  93429. 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]));
  93430. this.dd = new OIMO.Mat33(
  93431. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  93432. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  93433. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  93434. ).multiply(inv);
  93435. this.velx = this.p2.x - this.p1.x;
  93436. this.vely = this.p2.y - this.p1.y;
  93437. this.velz = this.p2.z - this.p1.z;
  93438. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  93439. if (len > 0.005) {
  93440. len = (0.005 - len) / len * invTimeStep * 0.05;
  93441. this.velx *= len;
  93442. this.vely *= len;
  93443. this.velz *= len;
  93444. } else {
  93445. this.velx = 0;
  93446. this.vely = 0;
  93447. this.velz = 0;
  93448. }
  93449. this.impx *= 0.95;
  93450. this.impy *= 0.95;
  93451. this.impz *= 0.95;
  93452. this.l1.x += this.impx * this.m1;
  93453. this.l1.y += this.impy * this.m1;
  93454. this.l1.z += this.impz * this.m1;
  93455. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  93456. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  93457. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  93458. this.l2.x -= this.impx * this.m2;
  93459. this.l2.y -= this.impy * this.m2;
  93460. this.l2.z -= this.impz * this.m2;
  93461. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  93462. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  93463. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  93464. },
  93465. solve: function () {
  93466. var d = this.dd.elements;
  93467. 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;
  93468. 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;
  93469. 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;
  93470. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  93471. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  93472. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  93473. this.impx += nimpx;
  93474. this.impy += nimpy;
  93475. this.impz += nimpz;
  93476. this.l1.x += nimpx * this.m1;
  93477. this.l1.y += nimpy * this.m1;
  93478. this.l1.z += nimpz * this.m1;
  93479. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  93480. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  93481. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  93482. this.l2.x -= nimpx * this.m2;
  93483. this.l2.y -= nimpy * this.m2;
  93484. this.l2.z -= nimpz * this.m2;
  93485. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  93486. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  93487. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  93488. }
  93489. }
  93490. /**
  93491. * A three-axis rotational constraint for various joints.
  93492. * @author saharan
  93493. */
  93494. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  93495. this.cfm1 = NaN;
  93496. this.cfm2 = NaN;
  93497. this.cfm3 = NaN;
  93498. this.i1e00 = NaN;
  93499. this.i1e01 = NaN;
  93500. this.i1e02 = NaN;
  93501. this.i1e10 = NaN;
  93502. this.i1e11 = NaN;
  93503. this.i1e12 = NaN;
  93504. this.i1e20 = NaN;
  93505. this.i1e21 = NaN;
  93506. this.i1e22 = NaN;
  93507. this.i2e00 = NaN;
  93508. this.i2e01 = NaN;
  93509. this.i2e02 = NaN;
  93510. this.i2e10 = NaN;
  93511. this.i2e11 = NaN;
  93512. this.i2e12 = NaN;
  93513. this.i2e20 = NaN;
  93514. this.i2e21 = NaN;
  93515. this.i2e22 = NaN;
  93516. this.ax1 = NaN;
  93517. this.ay1 = NaN;
  93518. this.az1 = NaN;
  93519. this.ax2 = NaN;
  93520. this.ay2 = NaN;
  93521. this.az2 = NaN;
  93522. this.ax3 = NaN;
  93523. this.ay3 = NaN;
  93524. this.az3 = NaN;
  93525. this.a1x1 = NaN; // jacoians
  93526. this.a1y1 = NaN;
  93527. this.a1z1 = NaN;
  93528. this.a2x1 = NaN;
  93529. this.a2y1 = NaN;
  93530. this.a2z1 = NaN;
  93531. this.a1x2 = NaN;
  93532. this.a1y2 = NaN;
  93533. this.a1z2 = NaN;
  93534. this.a2x2 = NaN;
  93535. this.a2y2 = NaN;
  93536. this.a2z2 = NaN;
  93537. this.a1x3 = NaN;
  93538. this.a1y3 = NaN;
  93539. this.a1z3 = NaN;
  93540. this.a2x3 = NaN;
  93541. this.a2y3 = NaN;
  93542. this.a2z3 = NaN;
  93543. this.lowerLimit1 = NaN;
  93544. this.upperLimit1 = NaN;
  93545. this.limitVelocity1 = NaN;
  93546. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  93547. this.enableMotor1 = false;
  93548. this.motorSpeed1 = NaN;
  93549. this.maxMotorForce1 = NaN;
  93550. this.maxMotorImpulse1 = NaN;
  93551. this.lowerLimit2 = NaN;
  93552. this.upperLimit2 = NaN;
  93553. this.limitVelocity2 = NaN;
  93554. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  93555. this.enableMotor2 = false;
  93556. this.motorSpeed2 = NaN;
  93557. this.maxMotorForce2 = NaN;
  93558. this.maxMotorImpulse2 = NaN;
  93559. this.lowerLimit3 = NaN;
  93560. this.upperLimit3 = NaN;
  93561. this.limitVelocity3 = NaN;
  93562. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  93563. this.enableMotor3 = false;
  93564. this.motorSpeed3 = NaN;
  93565. this.maxMotorForce3 = NaN;
  93566. this.maxMotorImpulse3 = NaN;
  93567. this.k00 = NaN; // K = J*M*JT
  93568. this.k01 = NaN;
  93569. this.k02 = NaN;
  93570. this.k10 = NaN;
  93571. this.k11 = NaN;
  93572. this.k12 = NaN;
  93573. this.k20 = NaN;
  93574. this.k21 = NaN;
  93575. this.k22 = NaN;
  93576. this.kv00 = NaN; // diagonals without CFMs
  93577. this.kv11 = NaN;
  93578. this.kv22 = NaN;
  93579. this.dv00 = NaN; // ...inverted
  93580. this.dv11 = NaN;
  93581. this.dv22 = NaN;
  93582. this.d00 = NaN; // K^-1
  93583. this.d01 = NaN;
  93584. this.d02 = NaN;
  93585. this.d10 = NaN;
  93586. this.d11 = NaN;
  93587. this.d12 = NaN;
  93588. this.d20 = NaN;
  93589. this.d21 = NaN;
  93590. this.d22 = NaN;
  93591. this.limitMotor1 = limitMotor1;
  93592. this.limitMotor2 = limitMotor2;
  93593. this.limitMotor3 = limitMotor3;
  93594. this.b1 = joint.body1;
  93595. this.b2 = joint.body2;
  93596. this.a1 = this.b1.angularVelocity;
  93597. this.a2 = this.b2.angularVelocity;
  93598. this.i1 = this.b1.inverseInertia;
  93599. this.i2 = this.b2.inverseInertia;
  93600. this.limitImpulse1 = 0;
  93601. this.motorImpulse1 = 0;
  93602. this.limitImpulse2 = 0;
  93603. this.motorImpulse2 = 0;
  93604. this.limitImpulse3 = 0;
  93605. this.motorImpulse3 = 0;
  93606. }
  93607. OIMO.Rotational3Constraint.prototype = {
  93608. constructor: OIMO.Rotational3Constraint,
  93609. preSolve: function (timeStep, invTimeStep) {
  93610. this.ax1 = this.limitMotor1.axis.x;
  93611. this.ay1 = this.limitMotor1.axis.y;
  93612. this.az1 = this.limitMotor1.axis.z;
  93613. this.ax2 = this.limitMotor2.axis.x;
  93614. this.ay2 = this.limitMotor2.axis.y;
  93615. this.az2 = this.limitMotor2.axis.z;
  93616. this.ax3 = this.limitMotor3.axis.x;
  93617. this.ay3 = this.limitMotor3.axis.y;
  93618. this.az3 = this.limitMotor3.axis.z;
  93619. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  93620. this.upperLimit1 = this.limitMotor1.upperLimit;
  93621. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  93622. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  93623. this.enableMotor1 = this.maxMotorForce1 > 0;
  93624. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  93625. this.upperLimit2 = this.limitMotor2.upperLimit;
  93626. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  93627. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  93628. this.enableMotor2 = this.maxMotorForce2 > 0;
  93629. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  93630. this.upperLimit3 = this.limitMotor3.upperLimit;
  93631. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  93632. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  93633. this.enableMotor3 = this.maxMotorForce3 > 0;
  93634. var ti1 = this.i1.elements;
  93635. var ti2 = this.i2.elements;
  93636. this.i1e00 = ti1[0];
  93637. this.i1e01 = ti1[1];
  93638. this.i1e02 = ti1[2];
  93639. this.i1e10 = ti1[3];
  93640. this.i1e11 = ti1[4];
  93641. this.i1e12 = ti1[5];
  93642. this.i1e20 = ti1[6];
  93643. this.i1e21 = ti1[7];
  93644. this.i1e22 = ti1[8];
  93645. this.i2e00 = ti2[0];
  93646. this.i2e01 = ti2[1];
  93647. this.i2e02 = ti2[2];
  93648. this.i2e10 = ti2[3];
  93649. this.i2e11 = ti2[4];
  93650. this.i2e12 = ti2[5];
  93651. this.i2e20 = ti2[6];
  93652. this.i2e21 = ti2[7];
  93653. this.i2e22 = ti2[8];
  93654. var frequency1 = this.limitMotor1.frequency;
  93655. var frequency2 = this.limitMotor2.frequency;
  93656. var frequency3 = this.limitMotor3.frequency;
  93657. var enableSpring1 = frequency1 > 0;
  93658. var enableSpring2 = frequency2 > 0;
  93659. var enableSpring3 = frequency3 > 0;
  93660. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  93661. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  93662. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  93663. var angle1 = this.limitMotor1.angle;
  93664. if (enableLimit1) {
  93665. if (this.lowerLimit1 == this.upperLimit1) {
  93666. if (this.limitState1 != 0) {
  93667. this.limitState1 = 0;
  93668. this.limitImpulse1 = 0;
  93669. }
  93670. this.limitVelocity1 = this.lowerLimit1 - angle1;
  93671. } else if (angle1 < this.lowerLimit1) {
  93672. if (this.limitState1 != -1) {
  93673. this.limitState1 = -1;
  93674. this.limitImpulse1 = 0;
  93675. }
  93676. this.limitVelocity1 = this.lowerLimit1 - angle1;
  93677. } else if (angle1 > this.upperLimit1) {
  93678. if (this.limitState1 != 1) {
  93679. this.limitState1 = 1;
  93680. this.limitImpulse1 = 0;
  93681. }
  93682. this.limitVelocity1 = this.upperLimit1 - angle1;
  93683. } else {
  93684. this.limitState1 = 2;
  93685. this.limitImpulse1 = 0;
  93686. this.limitVelocity1 = 0;
  93687. }
  93688. if (!enableSpring1) {
  93689. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  93690. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  93691. else this.limitVelocity1 = 0;
  93692. }
  93693. } else {
  93694. this.limitState1 = 2;
  93695. this.limitImpulse1 = 0;
  93696. }
  93697. var angle2 = this.limitMotor2.angle;
  93698. if (enableLimit2) {
  93699. if (this.lowerLimit2 == this.upperLimit2) {
  93700. if (this.limitState2 != 0) {
  93701. this.limitState2 = 0;
  93702. this.limitImpulse2 = 0;
  93703. }
  93704. this.limitVelocity2 = this.lowerLimit2 - angle2;
  93705. } else if (angle2 < this.lowerLimit2) {
  93706. if (this.limitState2 != -1) {
  93707. this.limitState2 = -1;
  93708. this.limitImpulse2 = 0;
  93709. }
  93710. this.limitVelocity2 = this.lowerLimit2 - angle2;
  93711. } else if (angle2 > this.upperLimit2) {
  93712. if (this.limitState2 != 1) {
  93713. this.limitState2 = 1;
  93714. this.limitImpulse2 = 0;
  93715. }
  93716. this.limitVelocity2 = this.upperLimit2 - angle2;
  93717. } else {
  93718. this.limitState2 = 2;
  93719. this.limitImpulse2 = 0;
  93720. this.limitVelocity2 = 0;
  93721. }
  93722. if (!enableSpring2) {
  93723. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  93724. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  93725. else this.limitVelocity2 = 0;
  93726. }
  93727. } else {
  93728. this.limitState2 = 2;
  93729. this.limitImpulse2 = 0;
  93730. }
  93731. var angle3 = this.limitMotor3.angle;
  93732. if (enableLimit3) {
  93733. if (this.lowerLimit3 == this.upperLimit3) {
  93734. if (this.limitState3 != 0) {
  93735. this.limitState3 = 0;
  93736. this.limitImpulse3 = 0;
  93737. }
  93738. this.limitVelocity3 = this.lowerLimit3 - angle3;
  93739. } else if (angle3 < this.lowerLimit3) {
  93740. if (this.limitState3 != -1) {
  93741. this.limitState3 = -1;
  93742. this.limitImpulse3 = 0;
  93743. }
  93744. this.limitVelocity3 = this.lowerLimit3 - angle3;
  93745. } else if (angle3 > this.upperLimit3) {
  93746. if (this.limitState3 != 1) {
  93747. this.limitState3 = 1;
  93748. this.limitImpulse3 = 0;
  93749. }
  93750. this.limitVelocity3 = this.upperLimit3 - angle3;
  93751. } else {
  93752. this.limitState3 = 2;
  93753. this.limitImpulse3 = 0;
  93754. this.limitVelocity3 = 0;
  93755. }
  93756. if (!enableSpring3) {
  93757. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  93758. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  93759. else this.limitVelocity3 = 0;
  93760. }
  93761. } else {
  93762. this.limitState3 = 2;
  93763. this.limitImpulse3 = 0;
  93764. }
  93765. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  93766. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  93767. } else {
  93768. this.motorImpulse1 = 0;
  93769. this.maxMotorImpulse1 = 0;
  93770. }
  93771. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  93772. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  93773. } else {
  93774. this.motorImpulse2 = 0;
  93775. this.maxMotorImpulse2 = 0;
  93776. }
  93777. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  93778. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  93779. } else {
  93780. this.motorImpulse3 = 0;
  93781. this.maxMotorImpulse3 = 0;
  93782. }
  93783. // build jacobians
  93784. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  93785. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  93786. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  93787. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  93788. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  93789. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  93790. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  93791. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  93792. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  93793. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  93794. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  93795. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  93796. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  93797. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  93798. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  93799. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  93800. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  93801. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  93802. // build an impulse matrix
  93803. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  93804. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  93805. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  93806. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  93807. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  93808. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  93809. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  93810. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  93811. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  93812. this.kv00 = this.k00;
  93813. this.kv11 = this.k11;
  93814. this.kv22 = this.k22;
  93815. this.dv00 = 1 / this.kv00;
  93816. this.dv11 = 1 / this.kv11;
  93817. this.dv22 = 1 / this.kv22;
  93818. if (enableSpring1 && this.limitState1 != 2) {
  93819. var omega = 6.2831853 * frequency1;
  93820. var k = omega * omega * timeStep;
  93821. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  93822. this.cfm1 = this.kv00 * dmp;
  93823. this.limitVelocity1 *= k * dmp;
  93824. } else {
  93825. this.cfm1 = 0;
  93826. this.limitVelocity1 *= invTimeStep * 0.05;
  93827. }
  93828. if (enableSpring2 && this.limitState2 != 2) {
  93829. omega = 6.2831853 * frequency2;
  93830. k = omega * omega * timeStep;
  93831. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  93832. this.cfm2 = this.kv11 * dmp;
  93833. this.limitVelocity2 *= k * dmp;
  93834. } else {
  93835. this.cfm2 = 0;
  93836. this.limitVelocity2 *= invTimeStep * 0.05;
  93837. }
  93838. if (enableSpring3 && this.limitState3 != 2) {
  93839. omega = 6.2831853 * frequency3;
  93840. k = omega * omega * timeStep;
  93841. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  93842. this.cfm3 = this.kv22 * dmp;
  93843. this.limitVelocity3 *= k * dmp;
  93844. } else {
  93845. this.cfm3 = 0;
  93846. this.limitVelocity3 *= invTimeStep * 0.05;
  93847. }
  93848. this.k00 += this.cfm1;
  93849. this.k11 += this.cfm2;
  93850. this.k22 += this.cfm3;
  93851. var inv = 1 / (
  93852. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  93853. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  93854. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  93855. );
  93856. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  93857. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  93858. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  93859. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  93860. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  93861. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  93862. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  93863. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  93864. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  93865. this.limitImpulse1 *= 0.95;
  93866. this.motorImpulse1 *= 0.95;
  93867. this.limitImpulse2 *= 0.95;
  93868. this.motorImpulse2 *= 0.95;
  93869. this.limitImpulse3 *= 0.95;
  93870. this.motorImpulse3 *= 0.95;
  93871. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  93872. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  93873. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  93874. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  93875. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  93876. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  93877. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  93878. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  93879. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  93880. },
  93881. solve_: function () {
  93882. var rvx = this.a2.x - this.a1.x;
  93883. var rvy = this.a2.y - this.a1.y;
  93884. var rvz = this.a2.z - this.a1.z;
  93885. this.limitVelocity3 = 30;
  93886. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  93887. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  93888. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  93889. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  93890. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  93891. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  93892. this.limitImpulse1 += dLimitImpulse1;
  93893. this.limitImpulse2 += dLimitImpulse2;
  93894. this.limitImpulse3 += dLimitImpulse3;
  93895. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  93896. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  93897. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  93898. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  93899. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  93900. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  93901. },
  93902. solve: function () {
  93903. var rvx = this.a2.x - this.a1.x;
  93904. var rvy = this.a2.y - this.a1.y;
  93905. var rvz = this.a2.z - this.a1.z;
  93906. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  93907. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  93908. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  93909. var oldMotorImpulse1 = this.motorImpulse1;
  93910. var oldMotorImpulse2 = this.motorImpulse2;
  93911. var oldMotorImpulse3 = this.motorImpulse3;
  93912. var dMotorImpulse1 = 0;
  93913. var dMotorImpulse2 = 0;
  93914. var dMotorImpulse3 = 0;
  93915. if (this.enableMotor1) {
  93916. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  93917. this.motorImpulse1 += dMotorImpulse1;
  93918. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  93919. this.motorImpulse1 = this.maxMotorImpulse1;
  93920. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  93921. this.motorImpulse1 = -this.maxMotorImpulse1;
  93922. }
  93923. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  93924. }
  93925. if (this.enableMotor2) {
  93926. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  93927. this.motorImpulse2 += dMotorImpulse2;
  93928. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  93929. this.motorImpulse2 = this.maxMotorImpulse2;
  93930. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  93931. this.motorImpulse2 = -this.maxMotorImpulse2;
  93932. }
  93933. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  93934. }
  93935. if (this.enableMotor3) {
  93936. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  93937. this.motorImpulse3 += dMotorImpulse3;
  93938. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  93939. this.motorImpulse3 = this.maxMotorImpulse3;
  93940. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  93941. this.motorImpulse3 = -this.maxMotorImpulse3;
  93942. }
  93943. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  93944. }
  93945. // apply motor impulse to relative velocity
  93946. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  93947. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  93948. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  93949. // subtract target velocity and applied impulse
  93950. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  93951. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  93952. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  93953. var oldLimitImpulse1 = this.limitImpulse1;
  93954. var oldLimitImpulse2 = this.limitImpulse2;
  93955. var oldLimitImpulse3 = this.limitImpulse3;
  93956. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  93957. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  93958. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  93959. this.limitImpulse1 += dLimitImpulse1;
  93960. this.limitImpulse2 += dLimitImpulse2;
  93961. this.limitImpulse3 += dLimitImpulse3;
  93962. // clamp
  93963. var clampState = 0;
  93964. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  93965. dLimitImpulse1 = -oldLimitImpulse1;
  93966. rvn2 += dLimitImpulse1 * this.k10;
  93967. rvn3 += dLimitImpulse1 * this.k20;
  93968. clampState |= 1;
  93969. }
  93970. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  93971. dLimitImpulse2 = -oldLimitImpulse2;
  93972. rvn1 += dLimitImpulse2 * this.k01;
  93973. rvn3 += dLimitImpulse2 * this.k21;
  93974. clampState |= 2;
  93975. }
  93976. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  93977. dLimitImpulse3 = -oldLimitImpulse3;
  93978. rvn1 += dLimitImpulse3 * this.k02;
  93979. rvn2 += dLimitImpulse3 * this.k12;
  93980. clampState |= 4;
  93981. }
  93982. // update un-clamped impulse
  93983. // TODO: isolate division
  93984. var det;
  93985. switch (clampState) {
  93986. case 1: // update 2 3
  93987. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  93988. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  93989. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  93990. break;
  93991. case 2: // update 1 3
  93992. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  93993. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  93994. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  93995. break;
  93996. case 3: // update 3
  93997. dLimitImpulse3 = rvn3 / this.k22;
  93998. break;
  93999. case 4: // update 1 2
  94000. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  94001. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  94002. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  94003. break;
  94004. case 5: // update 2
  94005. dLimitImpulse2 = rvn2 / this.k11;
  94006. break;
  94007. case 6: // update 1
  94008. dLimitImpulse1 = rvn1 / this.k00;
  94009. break;
  94010. }
  94011. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  94012. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  94013. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  94014. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  94015. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  94016. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  94017. // apply impulse
  94018. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  94019. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  94020. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  94021. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  94022. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  94023. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  94024. rvx = this.a2.x - this.a1.x;
  94025. rvy = this.a2.y - this.a1.y;
  94026. rvz = this.a2.z - this.a1.z;
  94027. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  94028. }
  94029. }
  94030. /**
  94031. * A rotational constraint for various joints.
  94032. * @author saharan
  94033. */
  94034. OIMO.RotationalConstraint = function (joint, limitMotor) {
  94035. this.cfm = NaN;
  94036. this.i1e00 = NaN;
  94037. this.i1e01 = NaN;
  94038. this.i1e02 = NaN;
  94039. this.i1e10 = NaN;
  94040. this.i1e11 = NaN;
  94041. this.i1e12 = NaN;
  94042. this.i1e20 = NaN;
  94043. this.i1e21 = NaN;
  94044. this.i1e22 = NaN;
  94045. this.i2e00 = NaN;
  94046. this.i2e01 = NaN;
  94047. this.i2e02 = NaN;
  94048. this.i2e10 = NaN;
  94049. this.i2e11 = NaN;
  94050. this.i2e12 = NaN;
  94051. this.i2e20 = NaN;
  94052. this.i2e21 = NaN;
  94053. this.i2e22 = NaN;
  94054. this.motorDenom = NaN;
  94055. this.invMotorDenom = NaN;
  94056. this.invDenom = NaN;
  94057. this.ax = NaN;
  94058. this.ay = NaN;
  94059. this.az = NaN;
  94060. this.a1x = NaN;
  94061. this.a1y = NaN;
  94062. this.a1z = NaN;
  94063. this.a2x = NaN;
  94064. this.a2y = NaN;
  94065. this.a2z = NaN;
  94066. this.enableLimit = false;
  94067. this.lowerLimit = NaN;
  94068. this.upperLimit = NaN;
  94069. this.limitVelocity = NaN;
  94070. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  94071. this.enableMotor = false;
  94072. this.motorSpeed = NaN;
  94073. this.maxMotorForce = NaN;
  94074. this.maxMotorImpulse = NaN;
  94075. this.limitMotor = limitMotor;
  94076. this.b1 = joint.body1;
  94077. this.b2 = joint.body2;
  94078. this.a1 = this.b1.angularVelocity;
  94079. this.a2 = this.b2.angularVelocity;
  94080. this.i1 = this.b1.inverseInertia;
  94081. this.i2 = this.b2.inverseInertia;
  94082. this.limitImpulse = 0;
  94083. this.motorImpulse = 0;
  94084. }
  94085. OIMO.RotationalConstraint.prototype = {
  94086. constructor: OIMO.RotationalConstraint,
  94087. preSolve: function (timeStep, invTimeStep) {
  94088. this.ax = this.limitMotor.axis.x;
  94089. this.ay = this.limitMotor.axis.y;
  94090. this.az = this.limitMotor.axis.z;
  94091. this.lowerLimit = this.limitMotor.lowerLimit;
  94092. this.upperLimit = this.limitMotor.upperLimit;
  94093. this.motorSpeed = this.limitMotor.motorSpeed;
  94094. this.maxMotorForce = this.limitMotor.maxMotorForce;
  94095. this.enableMotor = this.maxMotorForce > 0;
  94096. var ti1 = this.i1.elements;
  94097. var ti2 = this.i2.elements;
  94098. this.i1e00 = ti1[0];
  94099. this.i1e01 = ti1[1];
  94100. this.i1e02 = ti1[2];
  94101. this.i1e10 = ti1[3];
  94102. this.i1e11 = ti1[4];
  94103. this.i1e12 = ti1[5];
  94104. this.i1e20 = ti1[6];
  94105. this.i1e21 = ti1[7];
  94106. this.i1e22 = ti1[8];
  94107. this.i2e00 = ti2[0];
  94108. this.i2e01 = ti2[1];
  94109. this.i2e02 = ti2[2];
  94110. this.i2e10 = ti2[3];
  94111. this.i2e11 = ti2[4];
  94112. this.i2e12 = ti2[5];
  94113. this.i2e20 = ti2[6];
  94114. this.i2e21 = ti2[7];
  94115. this.i2e22 = ti2[8];
  94116. var frequency = this.limitMotor.frequency;
  94117. var enableSpring = frequency > 0;
  94118. var enableLimit = this.lowerLimit <= this.upperLimit;
  94119. var angle = this.limitMotor.angle;
  94120. if (enableLimit) {
  94121. if (this.lowerLimit == this.upperLimit) {
  94122. if (this.limitState != 0) {
  94123. this.limitState = 0;
  94124. this.limitImpulse = 0;
  94125. }
  94126. this.limitVelocity = this.lowerLimit - angle;
  94127. } else if (angle < this.lowerLimit) {
  94128. if (this.limitState != -1) {
  94129. this.limitState = -1;
  94130. this.limitImpulse = 0;
  94131. }
  94132. this.limitVelocity = this.lowerLimit - angle;
  94133. } else if (angle > this.upperLimit) {
  94134. if (this.limitState != 1) {
  94135. this.limitState = 1;
  94136. this.limitImpulse = 0;
  94137. }
  94138. this.limitVelocity = this.upperLimit - angle;
  94139. } else {
  94140. this.limitState = 2;
  94141. this.limitImpulse = 0;
  94142. this.limitVelocity = 0;
  94143. }
  94144. if (!enableSpring) {
  94145. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  94146. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  94147. else this.limitVelocity = 0;
  94148. }
  94149. } else {
  94150. this.limitState = 2;
  94151. this.limitImpulse = 0;
  94152. }
  94153. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  94154. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  94155. } else {
  94156. this.motorImpulse = 0;
  94157. this.maxMotorImpulse = 0;
  94158. }
  94159. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  94160. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  94161. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  94162. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  94163. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  94164. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  94165. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  94166. this.invMotorDenom = 1 / this.motorDenom;
  94167. if (enableSpring && this.limitState != 2) {
  94168. var omega = 6.2831853 * frequency;
  94169. var k = omega * omega * timeStep;
  94170. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  94171. this.cfm = this.motorDenom * dmp;
  94172. this.limitVelocity *= k * dmp;
  94173. } else {
  94174. this.cfm = 0;
  94175. this.limitVelocity *= invTimeStep * 0.05;
  94176. }
  94177. this.invDenom = 1 / (this.motorDenom + this.cfm);
  94178. this.limitImpulse *= 0.95;
  94179. this.motorImpulse *= 0.95;
  94180. var totalImpulse = this.limitImpulse + this.motorImpulse;
  94181. this.a1.x += totalImpulse * this.a1x;
  94182. this.a1.y += totalImpulse * this.a1y;
  94183. this.a1.z += totalImpulse * this.a1z;
  94184. this.a2.x -= totalImpulse * this.a2x;
  94185. this.a2.y -= totalImpulse * this.a2y;
  94186. this.a2.z -= totalImpulse * this.a2z;
  94187. },
  94188. solve: function () {
  94189. 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);
  94190. // motor part
  94191. var newMotorImpulse;
  94192. if (this.enableMotor) {
  94193. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  94194. var oldMotorImpulse = this.motorImpulse;
  94195. this.motorImpulse += newMotorImpulse;
  94196. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  94197. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  94198. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  94199. rvn -= newMotorImpulse * this.motorDenom;
  94200. } else newMotorImpulse = 0;
  94201. // limit part
  94202. var newLimitImpulse;
  94203. if (this.limitState != 2) {
  94204. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  94205. var oldLimitImpulse = this.limitImpulse;
  94206. this.limitImpulse += newLimitImpulse;
  94207. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  94208. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  94209. } else newLimitImpulse = 0;
  94210. var totalImpulse = newLimitImpulse + newMotorImpulse;
  94211. this.a1.x += totalImpulse * this.a1x;
  94212. this.a1.y += totalImpulse * this.a1y;
  94213. this.a1.z += totalImpulse * this.a1z;
  94214. this.a2.x -= totalImpulse * this.a2x;
  94215. this.a2.y -= totalImpulse * this.a2y;
  94216. this.a2.z -= totalImpulse * this.a2z;
  94217. }
  94218. }
  94219. /**
  94220. * A three-axis translational constraint for various joints.
  94221. * @author saharan
  94222. */
  94223. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  94224. this.m1 = NaN;
  94225. this.m2 = NaN;
  94226. this.i1e00 = NaN;
  94227. this.i1e01 = NaN;
  94228. this.i1e02 = NaN;
  94229. this.i1e10 = NaN;
  94230. this.i1e11 = NaN;
  94231. this.i1e12 = NaN;
  94232. this.i1e20 = NaN;
  94233. this.i1e21 = NaN;
  94234. this.i1e22 = NaN;
  94235. this.i2e00 = NaN;
  94236. this.i2e01 = NaN;
  94237. this.i2e02 = NaN;
  94238. this.i2e10 = NaN;
  94239. this.i2e11 = NaN;
  94240. this.i2e12 = NaN;
  94241. this.i2e20 = NaN;
  94242. this.i2e21 = NaN;
  94243. this.i2e22 = NaN;
  94244. this.ax1 = NaN;
  94245. this.ay1 = NaN;
  94246. this.az1 = NaN;
  94247. this.ax2 = NaN;
  94248. this.ay2 = NaN;
  94249. this.az2 = NaN;
  94250. this.ax3 = NaN;
  94251. this.ay3 = NaN;
  94252. this.az3 = NaN;
  94253. this.r1x = NaN;
  94254. this.r1y = NaN;
  94255. this.r1z = NaN;
  94256. this.r2x = NaN;
  94257. this.r2y = NaN;
  94258. this.r2z = NaN;
  94259. this.t1x1 = NaN;// jacobians
  94260. this.t1y1 = NaN;
  94261. this.t1z1 = NaN;
  94262. this.t2x1 = NaN;
  94263. this.t2y1 = NaN;
  94264. this.t2z1 = NaN;
  94265. this.l1x1 = NaN;
  94266. this.l1y1 = NaN;
  94267. this.l1z1 = NaN;
  94268. this.l2x1 = NaN;
  94269. this.l2y1 = NaN;
  94270. this.l2z1 = NaN;
  94271. this.a1x1 = NaN;
  94272. this.a1y1 = NaN;
  94273. this.a1z1 = NaN;
  94274. this.a2x1 = NaN;
  94275. this.a2y1 = NaN;
  94276. this.a2z1 = NaN;
  94277. this.t1x2 = NaN;
  94278. this.t1y2 = NaN;
  94279. this.t1z2 = NaN;
  94280. this.t2x2 = NaN;
  94281. this.t2y2 = NaN;
  94282. this.t2z2 = NaN;
  94283. this.l1x2 = NaN;
  94284. this.l1y2 = NaN;
  94285. this.l1z2 = NaN;
  94286. this.l2x2 = NaN;
  94287. this.l2y2 = NaN;
  94288. this.l2z2 = NaN;
  94289. this.a1x2 = NaN;
  94290. this.a1y2 = NaN;
  94291. this.a1z2 = NaN;
  94292. this.a2x2 = NaN;
  94293. this.a2y2 = NaN;
  94294. this.a2z2 = NaN;
  94295. this.t1x3 = NaN;
  94296. this.t1y3 = NaN;
  94297. this.t1z3 = NaN;
  94298. this.t2x3 = NaN;
  94299. this.t2y3 = NaN;
  94300. this.t2z3 = NaN;
  94301. this.l1x3 = NaN;
  94302. this.l1y3 = NaN;
  94303. this.l1z3 = NaN;
  94304. this.l2x3 = NaN;
  94305. this.l2y3 = NaN;
  94306. this.l2z3 = NaN;
  94307. this.a1x3 = NaN;
  94308. this.a1y3 = NaN;
  94309. this.a1z3 = NaN;
  94310. this.a2x3 = NaN;
  94311. this.a2y3 = NaN;
  94312. this.a2z3 = NaN;
  94313. this.lowerLimit1 = NaN;
  94314. this.upperLimit1 = NaN;
  94315. this.limitVelocity1 = NaN;
  94316. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  94317. this.enableMotor1 = false;
  94318. this.motorSpeed1 = NaN;
  94319. this.maxMotorForce1 = NaN;
  94320. this.maxMotorImpulse1 = NaN;
  94321. this.lowerLimit2 = NaN;
  94322. this.upperLimit2 = NaN;
  94323. this.limitVelocity2 = NaN;
  94324. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  94325. this.enableMotor2 = false;
  94326. this.motorSpeed2 = NaN;
  94327. this.maxMotorForce2 = NaN;
  94328. this.maxMotorImpulse2 = NaN;
  94329. this.lowerLimit3 = NaN;
  94330. this.upperLimit3 = NaN;
  94331. this.limitVelocity3 = NaN;
  94332. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  94333. this.enableMotor3 = false;
  94334. this.motorSpeed3 = NaN;
  94335. this.maxMotorForce3 = NaN;
  94336. this.maxMotorImpulse3 = NaN;
  94337. this.k00 = NaN; // K = J*M*JT
  94338. this.k01 = NaN;
  94339. this.k02 = NaN;
  94340. this.k10 = NaN;
  94341. this.k11 = NaN;
  94342. this.k12 = NaN;
  94343. this.k20 = NaN;
  94344. this.k21 = NaN;
  94345. this.k22 = NaN;
  94346. this.kv00 = NaN; // diagonals without CFMs
  94347. this.kv11 = NaN;
  94348. this.kv22 = NaN;
  94349. this.dv00 = NaN; // ...inverted
  94350. this.dv11 = NaN;
  94351. this.dv22 = NaN;
  94352. this.d00 = NaN; // K^-1
  94353. this.d01 = NaN;
  94354. this.d02 = NaN;
  94355. this.d10 = NaN;
  94356. this.d11 = NaN;
  94357. this.d12 = NaN;
  94358. this.d20 = NaN;
  94359. this.d21 = NaN;
  94360. this.d22 = NaN;
  94361. this.limitMotor1 = limitMotor1;
  94362. this.limitMotor2 = limitMotor2;
  94363. this.limitMotor3 = limitMotor3;
  94364. this.b1 = joint.body1;
  94365. this.b2 = joint.body2;
  94366. this.p1 = joint.anchorPoint1;
  94367. this.p2 = joint.anchorPoint2;
  94368. this.r1 = joint.relativeAnchorPoint1;
  94369. this.r2 = joint.relativeAnchorPoint2;
  94370. this.l1 = this.b1.linearVelocity;
  94371. this.l2 = this.b2.linearVelocity;
  94372. this.a1 = this.b1.angularVelocity;
  94373. this.a2 = this.b2.angularVelocity;
  94374. this.i1 = this.b1.inverseInertia;
  94375. this.i2 = this.b2.inverseInertia;
  94376. this.limitImpulse1 = 0;
  94377. this.motorImpulse1 = 0;
  94378. this.limitImpulse2 = 0;
  94379. this.motorImpulse2 = 0;
  94380. this.limitImpulse3 = 0;
  94381. this.motorImpulse3 = 0;
  94382. this.cfm1 = 0;// Constraint Force Mixing
  94383. this.cfm2 = 0;
  94384. this.cfm3 = 0;
  94385. this.weight = -1;
  94386. }
  94387. OIMO.Translational3Constraint.prototype = {
  94388. constructor: OIMO.Translational3Constraint,
  94389. preSolve: function (timeStep, invTimeStep) {
  94390. this.ax1 = this.limitMotor1.axis.x;
  94391. this.ay1 = this.limitMotor1.axis.y;
  94392. this.az1 = this.limitMotor1.axis.z;
  94393. this.ax2 = this.limitMotor2.axis.x;
  94394. this.ay2 = this.limitMotor2.axis.y;
  94395. this.az2 = this.limitMotor2.axis.z;
  94396. this.ax3 = this.limitMotor3.axis.x;
  94397. this.ay3 = this.limitMotor3.axis.y;
  94398. this.az3 = this.limitMotor3.axis.z;
  94399. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  94400. this.upperLimit1 = this.limitMotor1.upperLimit;
  94401. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  94402. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  94403. this.enableMotor1 = this.maxMotorForce1 > 0;
  94404. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  94405. this.upperLimit2 = this.limitMotor2.upperLimit;
  94406. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  94407. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  94408. this.enableMotor2 = this.maxMotorForce2 > 0;
  94409. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  94410. this.upperLimit3 = this.limitMotor3.upperLimit;
  94411. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  94412. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  94413. this.enableMotor3 = this.maxMotorForce3 > 0;
  94414. this.m1 = this.b1.inverseMass;
  94415. this.m2 = this.b2.inverseMass;
  94416. var ti1 = this.i1.elements;
  94417. var ti2 = this.i2.elements;
  94418. this.i1e00 = ti1[0];
  94419. this.i1e01 = ti1[1];
  94420. this.i1e02 = ti1[2];
  94421. this.i1e10 = ti1[3];
  94422. this.i1e11 = ti1[4];
  94423. this.i1e12 = ti1[5];
  94424. this.i1e20 = ti1[6];
  94425. this.i1e21 = ti1[7];
  94426. this.i1e22 = ti1[8];
  94427. this.i2e00 = ti2[0];
  94428. this.i2e01 = ti2[1];
  94429. this.i2e02 = ti2[2];
  94430. this.i2e10 = ti2[3];
  94431. this.i2e11 = ti2[4];
  94432. this.i2e12 = ti2[5];
  94433. this.i2e20 = ti2[6];
  94434. this.i2e21 = ti2[7];
  94435. this.i2e22 = ti2[8];
  94436. var dx = this.p2.x - this.p1.x;
  94437. var dy = this.p2.y - this.p1.y;
  94438. var dz = this.p2.z - this.p1.z;
  94439. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  94440. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  94441. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  94442. var frequency1 = this.limitMotor1.frequency;
  94443. var frequency2 = this.limitMotor2.frequency;
  94444. var frequency3 = this.limitMotor3.frequency;
  94445. var enableSpring1 = frequency1 > 0;
  94446. var enableSpring2 = frequency2 > 0;
  94447. var enableSpring3 = frequency3 > 0;
  94448. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  94449. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  94450. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  94451. // for stability
  94452. if (enableSpring1 && d1 > 20 || d1 < -20) {
  94453. enableSpring1 = false;
  94454. }
  94455. if (enableSpring2 && d2 > 20 || d2 < -20) {
  94456. enableSpring2 = false;
  94457. }
  94458. if (enableSpring3 && d3 > 20 || d3 < -20) {
  94459. enableSpring3 = false;
  94460. }
  94461. if (enableLimit1) {
  94462. if (this.lowerLimit1 == this.upperLimit1) {
  94463. if (this.limitState1 != 0) {
  94464. this.limitState1 = 0;
  94465. this.limitImpulse1 = 0;
  94466. }
  94467. this.limitVelocity1 = this.lowerLimit1 - d1;
  94468. if (!enableSpring1) d1 = this.lowerLimit1;
  94469. } else if (d1 < this.lowerLimit1) {
  94470. if (this.limitState1 != -1) {
  94471. this.limitState1 = -1;
  94472. this.limitImpulse1 = 0;
  94473. }
  94474. this.limitVelocity1 = this.lowerLimit1 - d1;
  94475. if (!enableSpring1) d1 = this.lowerLimit1;
  94476. } else if (d1 > this.upperLimit1) {
  94477. if (this.limitState1 != 1) {
  94478. this.limitState1 = 1;
  94479. this.limitImpulse1 = 0;
  94480. }
  94481. this.limitVelocity1 = this.upperLimit1 - d1;
  94482. if (!enableSpring1) d1 = this.upperLimit1;
  94483. } else {
  94484. this.limitState1 = 2;
  94485. this.limitImpulse1 = 0;
  94486. this.limitVelocity1 = 0;
  94487. }
  94488. if (!enableSpring1) {
  94489. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  94490. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  94491. else this.limitVelocity1 = 0;
  94492. }
  94493. } else {
  94494. this.limitState1 = 2;
  94495. this.limitImpulse1 = 0;
  94496. }
  94497. if (enableLimit2) {
  94498. if (this.lowerLimit2 == this.upperLimit2) {
  94499. if (this.limitState2 != 0) {
  94500. this.limitState2 = 0;
  94501. this.limitImpulse2 = 0;
  94502. }
  94503. this.limitVelocity2 = this.lowerLimit2 - d2;
  94504. if (!enableSpring2) d2 = this.lowerLimit2;
  94505. } else if (d2 < this.lowerLimit2) {
  94506. if (this.limitState2 != -1) {
  94507. this.limitState2 = -1;
  94508. this.limitImpulse2 = 0;
  94509. }
  94510. this.limitVelocity2 = this.lowerLimit2 - d2;
  94511. if (!enableSpring2) d2 = this.lowerLimit2;
  94512. } else if (d2 > this.upperLimit2) {
  94513. if (this.limitState2 != 1) {
  94514. this.limitState2 = 1;
  94515. this.limitImpulse2 = 0;
  94516. }
  94517. this.limitVelocity2 = this.upperLimit2 - d2;
  94518. if (!enableSpring2) d2 = this.upperLimit2;
  94519. } else {
  94520. this.limitState2 = 2;
  94521. this.limitImpulse2 = 0;
  94522. this.limitVelocity2 = 0;
  94523. }
  94524. if (!enableSpring2) {
  94525. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  94526. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  94527. else this.limitVelocity2 = 0;
  94528. }
  94529. } else {
  94530. this.limitState2 = 2;
  94531. this.limitImpulse2 = 0;
  94532. }
  94533. if (enableLimit3) {
  94534. if (this.lowerLimit3 == this.upperLimit3) {
  94535. if (this.limitState3 != 0) {
  94536. this.limitState3 = 0;
  94537. this.limitImpulse3 = 0;
  94538. }
  94539. this.limitVelocity3 = this.lowerLimit3 - d3;
  94540. if (!enableSpring3) d3 = this.lowerLimit3;
  94541. } else if (d3 < this.lowerLimit3) {
  94542. if (this.limitState3 != -1) {
  94543. this.limitState3 = -1;
  94544. this.limitImpulse3 = 0;
  94545. }
  94546. this.limitVelocity3 = this.lowerLimit3 - d3;
  94547. if (!enableSpring3) d3 = this.lowerLimit3;
  94548. } else if (d3 > this.upperLimit3) {
  94549. if (this.limitState3 != 1) {
  94550. this.limitState3 = 1;
  94551. this.limitImpulse3 = 0;
  94552. }
  94553. this.limitVelocity3 = this.upperLimit3 - d3;
  94554. if (!enableSpring3) d3 = this.upperLimit3;
  94555. } else {
  94556. this.limitState3 = 2;
  94557. this.limitImpulse3 = 0;
  94558. this.limitVelocity3 = 0;
  94559. }
  94560. if (!enableSpring3) {
  94561. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  94562. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  94563. else this.limitVelocity3 = 0;
  94564. }
  94565. } else {
  94566. this.limitState3 = 2;
  94567. this.limitImpulse3 = 0;
  94568. }
  94569. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  94570. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  94571. } else {
  94572. this.motorImpulse1 = 0;
  94573. this.maxMotorImpulse1 = 0;
  94574. }
  94575. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  94576. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  94577. } else {
  94578. this.motorImpulse2 = 0;
  94579. this.maxMotorImpulse2 = 0;
  94580. }
  94581. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  94582. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  94583. } else {
  94584. this.motorImpulse3 = 0;
  94585. this.maxMotorImpulse3 = 0;
  94586. }
  94587. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  94588. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  94589. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  94590. var w1 = this.m2 / (this.m1 + this.m2);
  94591. if (this.weight >= 0) w1 = this.weight; // use given weight
  94592. var w2 = 1 - w1;
  94593. this.r1x = this.r1.x + rdx * w1;
  94594. this.r1y = this.r1.y + rdy * w1;
  94595. this.r1z = this.r1.z + rdz * w1;
  94596. this.r2x = this.r2.x - rdx * w2;
  94597. this.r2y = this.r2.y - rdy * w2;
  94598. this.r2z = this.r2.z - rdz * w2;
  94599. // build jacobians
  94600. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  94601. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  94602. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  94603. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  94604. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  94605. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  94606. this.l1x1 = this.ax1 * this.m1;
  94607. this.l1y1 = this.ay1 * this.m1;
  94608. this.l1z1 = this.az1 * this.m1;
  94609. this.l2x1 = this.ax1 * this.m2;
  94610. this.l2y1 = this.ay1 * this.m2;
  94611. this.l2z1 = this.az1 * this.m2;
  94612. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  94613. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  94614. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  94615. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  94616. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  94617. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  94618. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  94619. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  94620. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  94621. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  94622. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  94623. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  94624. this.l1x2 = this.ax2 * this.m1;
  94625. this.l1y2 = this.ay2 * this.m1;
  94626. this.l1z2 = this.az2 * this.m1;
  94627. this.l2x2 = this.ax2 * this.m2;
  94628. this.l2y2 = this.ay2 * this.m2;
  94629. this.l2z2 = this.az2 * this.m2;
  94630. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  94631. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  94632. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  94633. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  94634. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  94635. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  94636. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  94637. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  94638. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  94639. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  94640. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  94641. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  94642. this.l1x3 = this.ax3 * this.m1;
  94643. this.l1y3 = this.ay3 * this.m1;
  94644. this.l1z3 = this.az3 * this.m1;
  94645. this.l2x3 = this.ax3 * this.m2;
  94646. this.l2y3 = this.ay3 * this.m2;
  94647. this.l2z3 = this.az3 * this.m2;
  94648. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  94649. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  94650. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  94651. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  94652. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  94653. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  94654. // build an impulse matrix
  94655. var m12 = this.m1 + this.m2;
  94656. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  94657. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  94658. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  94659. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  94660. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  94661. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  94662. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  94663. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  94664. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  94665. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  94666. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  94667. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  94668. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  94669. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  94670. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  94671. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  94672. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  94673. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  94674. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  94675. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  94676. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  94677. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  94678. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  94679. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  94680. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  94681. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  94682. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  94683. this.kv00 = this.k00;
  94684. this.kv11 = this.k11;
  94685. this.kv22 = this.k22;
  94686. this.dv00 = 1 / this.kv00;
  94687. this.dv11 = 1 / this.kv11;
  94688. this.dv22 = 1 / this.kv22;
  94689. if (enableSpring1 && this.limitState1 != 2) {
  94690. var omega = 6.2831853 * frequency1;
  94691. var k = omega * omega * timeStep;
  94692. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  94693. this.cfm1 = this.kv00 * dmp;
  94694. this.limitVelocity1 *= k * dmp;
  94695. } else {
  94696. this.cfm1 = 0;
  94697. this.limitVelocity1 *= invTimeStep * 0.05;
  94698. }
  94699. if (enableSpring2 && this.limitState2 != 2) {
  94700. omega = 6.2831853 * frequency2;
  94701. k = omega * omega * timeStep;
  94702. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  94703. this.cfm2 = this.kv11 * dmp;
  94704. this.limitVelocity2 *= k * dmp;
  94705. } else {
  94706. this.cfm2 = 0;
  94707. this.limitVelocity2 *= invTimeStep * 0.05;
  94708. }
  94709. if (enableSpring3 && this.limitState3 != 2) {
  94710. omega = 6.2831853 * frequency3;
  94711. k = omega * omega * timeStep;
  94712. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  94713. this.cfm3 = this.kv22 * dmp;
  94714. this.limitVelocity3 *= k * dmp;
  94715. } else {
  94716. this.cfm3 = 0;
  94717. this.limitVelocity3 *= invTimeStep * 0.05;
  94718. }
  94719. this.k00 += this.cfm1;
  94720. this.k11 += this.cfm2;
  94721. this.k22 += this.cfm3;
  94722. var inv = 1 / (
  94723. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  94724. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  94725. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  94726. );
  94727. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  94728. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  94729. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  94730. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  94731. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  94732. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  94733. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  94734. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  94735. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  94736. // warm starting
  94737. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  94738. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  94739. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  94740. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  94741. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  94742. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  94743. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  94744. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  94745. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  94746. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  94747. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  94748. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  94749. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  94750. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  94751. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  94752. },
  94753. solve: function () {
  94754. 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;
  94755. 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;
  94756. 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;
  94757. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  94758. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  94759. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  94760. var oldMotorImpulse1 = this.motorImpulse1;
  94761. var oldMotorImpulse2 = this.motorImpulse2;
  94762. var oldMotorImpulse3 = this.motorImpulse3;
  94763. var dMotorImpulse1 = 0;
  94764. var dMotorImpulse2 = 0;
  94765. var dMotorImpulse3 = 0;
  94766. if (this.enableMotor1) {
  94767. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  94768. this.motorImpulse1 += dMotorImpulse1;
  94769. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  94770. this.motorImpulse1 = this.maxMotorImpulse1;
  94771. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  94772. this.motorImpulse1 = -this.maxMotorImpulse1;
  94773. }
  94774. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  94775. }
  94776. if (this.enableMotor2) {
  94777. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  94778. this.motorImpulse2 += dMotorImpulse2;
  94779. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  94780. this.motorImpulse2 = this.maxMotorImpulse2;
  94781. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  94782. this.motorImpulse2 = -this.maxMotorImpulse2;
  94783. }
  94784. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  94785. }
  94786. if (this.enableMotor3) {
  94787. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  94788. this.motorImpulse3 += dMotorImpulse3;
  94789. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  94790. this.motorImpulse3 = this.maxMotorImpulse3;
  94791. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  94792. this.motorImpulse3 = -this.maxMotorImpulse3;
  94793. }
  94794. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  94795. }
  94796. // apply motor impulse to relative velocity
  94797. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  94798. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  94799. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  94800. // subtract target velocity and applied impulse
  94801. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  94802. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  94803. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  94804. var oldLimitImpulse1 = this.limitImpulse1;
  94805. var oldLimitImpulse2 = this.limitImpulse2;
  94806. var oldLimitImpulse3 = this.limitImpulse3;
  94807. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  94808. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  94809. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  94810. this.limitImpulse1 += dLimitImpulse1;
  94811. this.limitImpulse2 += dLimitImpulse2;
  94812. this.limitImpulse3 += dLimitImpulse3;
  94813. // clamp
  94814. var clampState = 0;
  94815. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  94816. dLimitImpulse1 = -oldLimitImpulse1;
  94817. rvn2 += dLimitImpulse1 * this.k10;
  94818. rvn3 += dLimitImpulse1 * this.k20;
  94819. clampState |= 1;
  94820. }
  94821. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  94822. dLimitImpulse2 = -oldLimitImpulse2;
  94823. rvn1 += dLimitImpulse2 * this.k01;
  94824. rvn3 += dLimitImpulse2 * this.k21;
  94825. clampState |= 2;
  94826. }
  94827. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  94828. dLimitImpulse3 = -oldLimitImpulse3;
  94829. rvn1 += dLimitImpulse3 * this.k02;
  94830. rvn2 += dLimitImpulse3 * this.k12;
  94831. clampState |= 4;
  94832. }
  94833. // update un-clamped impulse
  94834. // TODO: isolate division
  94835. var det;
  94836. switch (clampState) {
  94837. case 1:// update 2 3
  94838. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  94839. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  94840. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  94841. break;
  94842. case 2:// update 1 3
  94843. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  94844. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  94845. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  94846. break;
  94847. case 3:// update 3
  94848. dLimitImpulse3 = rvn3 / this.k22;
  94849. break;
  94850. case 4:// update 1 2
  94851. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  94852. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  94853. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  94854. break;
  94855. case 5:// update 2
  94856. dLimitImpulse2 = rvn2 / this.k11;
  94857. break;
  94858. case 6:// update 1
  94859. dLimitImpulse1 = rvn1 / this.k00;
  94860. break;
  94861. }
  94862. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  94863. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  94864. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  94865. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  94866. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  94867. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  94868. // apply impulse
  94869. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  94870. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  94871. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  94872. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  94873. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  94874. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  94875. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  94876. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  94877. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  94878. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  94879. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  94880. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  94881. }
  94882. }
  94883. /**
  94884. * A translational constraint for various joints.
  94885. * @author saharan
  94886. */
  94887. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  94888. this.cfm = NaN;
  94889. this.m1 = NaN;
  94890. this.m2 = NaN;
  94891. this.i1e00 = NaN;
  94892. this.i1e01 = NaN;
  94893. this.i1e02 = NaN;
  94894. this.i1e10 = NaN;
  94895. this.i1e11 = NaN;
  94896. this.i1e12 = NaN;
  94897. this.i1e20 = NaN;
  94898. this.i1e21 = NaN;
  94899. this.i1e22 = NaN;
  94900. this.i2e00 = NaN;
  94901. this.i2e01 = NaN;
  94902. this.i2e02 = NaN;
  94903. this.i2e10 = NaN;
  94904. this.i2e11 = NaN;
  94905. this.i2e12 = NaN;
  94906. this.i2e20 = NaN;
  94907. this.i2e21 = NaN;
  94908. this.i2e22 = NaN;
  94909. this.motorDenom = NaN;
  94910. this.invMotorDenom = NaN;
  94911. this.invDenom = NaN;
  94912. this.ax = NaN;
  94913. this.ay = NaN;
  94914. this.az = NaN;
  94915. this.r1x = NaN;
  94916. this.r1y = NaN;
  94917. this.r1z = NaN;
  94918. this.r2x = NaN;
  94919. this.r2y = NaN;
  94920. this.r2z = NaN;
  94921. this.t1x = NaN;
  94922. this.t1y = NaN;
  94923. this.t1z = NaN;
  94924. this.t2x = NaN;
  94925. this.t2y = NaN;
  94926. this.t2z = NaN;
  94927. this.l1x = NaN;
  94928. this.l1y = NaN;
  94929. this.l1z = NaN;
  94930. this.l2x = NaN;
  94931. this.l2y = NaN;
  94932. this.l2z = NaN;
  94933. this.a1x = NaN;
  94934. this.a1y = NaN;
  94935. this.a1z = NaN;
  94936. this.a2x = NaN;
  94937. this.a2y = NaN;
  94938. this.a2z = NaN;
  94939. this.lowerLimit = NaN;
  94940. this.upperLimit = NaN;
  94941. this.limitVelocity = NaN;
  94942. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  94943. this.enableMotor = false;
  94944. this.motorSpeed = NaN;
  94945. this.maxMotorForce = NaN;
  94946. this.maxMotorImpulse = NaN;
  94947. this.limitMotor = limitMotor;
  94948. this.b1 = joint.body1;
  94949. this.b2 = joint.body2;
  94950. this.p1 = joint.anchorPoint1;
  94951. this.p2 = joint.anchorPoint2;
  94952. this.r1 = joint.relativeAnchorPoint1;
  94953. this.r2 = joint.relativeAnchorPoint2;
  94954. this.l1 = this.b1.linearVelocity;
  94955. this.l2 = this.b2.linearVelocity;
  94956. this.a1 = this.b1.angularVelocity;
  94957. this.a2 = this.b2.angularVelocity;
  94958. this.i1 = this.b1.inverseInertia;
  94959. this.i2 = this.b2.inverseInertia;
  94960. this.limitImpulse = 0;
  94961. this.motorImpulse = 0;
  94962. }
  94963. OIMO.TranslationalConstraint.prototype = {
  94964. constructor: OIMO.TranslationalConstraint,
  94965. preSolve: function (timeStep, invTimeStep) {
  94966. this.ax = this.limitMotor.axis.x;
  94967. this.ay = this.limitMotor.axis.y;
  94968. this.az = this.limitMotor.axis.z;
  94969. this.lowerLimit = this.limitMotor.lowerLimit;
  94970. this.upperLimit = this.limitMotor.upperLimit;
  94971. this.motorSpeed = this.limitMotor.motorSpeed;
  94972. this.maxMotorForce = this.limitMotor.maxMotorForce;
  94973. this.enableMotor = this.maxMotorForce > 0;
  94974. this.m1 = this.b1.inverseMass;
  94975. this.m2 = this.b2.inverseMass;
  94976. var ti1 = this.i1.elements;
  94977. var ti2 = this.i2.elements;
  94978. this.i1e00 = ti1[0];
  94979. this.i1e01 = ti1[1];
  94980. this.i1e02 = ti1[2];
  94981. this.i1e10 = ti1[3];
  94982. this.i1e11 = ti1[4];
  94983. this.i1e12 = ti1[5];
  94984. this.i1e20 = ti1[6];
  94985. this.i1e21 = ti1[7];
  94986. this.i1e22 = ti1[8];
  94987. this.i2e00 = ti2[0];
  94988. this.i2e01 = ti2[1];
  94989. this.i2e02 = ti2[2];
  94990. this.i2e10 = ti2[3];
  94991. this.i2e11 = ti2[4];
  94992. this.i2e12 = ti2[5];
  94993. this.i2e20 = ti2[6];
  94994. this.i2e21 = ti2[7];
  94995. this.i2e22 = ti2[8];
  94996. var dx = this.p2.x - this.p1.x;
  94997. var dy = this.p2.y - this.p1.y;
  94998. var dz = this.p2.z - this.p1.z;
  94999. var d = dx * this.ax + dy * this.ay + dz * this.az;
  95000. var frequency = this.limitMotor.frequency;
  95001. var enableSpring = frequency > 0;
  95002. var enableLimit = this.lowerLimit <= this.upperLimit;
  95003. if (enableSpring && d > 20 || d < -20) {
  95004. enableSpring = false;
  95005. }
  95006. if (enableLimit) {
  95007. if (this.lowerLimit == this.upperLimit) {
  95008. if (this.limitState != 0) {
  95009. this.limitState = 0;
  95010. this.limitImpulse = 0;
  95011. }
  95012. this.limitVelocity = this.lowerLimit - d;
  95013. if (!enableSpring) d = this.lowerLimit;
  95014. } else if (d < this.lowerLimit) {
  95015. if (this.limitState != -1) {
  95016. this.limitState = -1;
  95017. this.limitImpulse = 0;
  95018. }
  95019. this.limitVelocity = this.lowerLimit - d;
  95020. if (!enableSpring) d = this.lowerLimit;
  95021. } else if (d > this.upperLimit) {
  95022. if (this.limitState != 1) {
  95023. this.limitState = 1;
  95024. this.limitImpulse = 0;
  95025. }
  95026. this.limitVelocity = this.upperLimit - d;
  95027. if (!enableSpring) d = this.upperLimit;
  95028. } else {
  95029. this.limitState = 2;
  95030. this.limitImpulse = 0;
  95031. this.limitVelocity = 0;
  95032. }
  95033. if (!enableSpring) {
  95034. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  95035. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  95036. else this.limitVelocity = 0;
  95037. }
  95038. } else {
  95039. this.limitState = 2;
  95040. this.limitImpulse = 0;
  95041. }
  95042. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  95043. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  95044. } else {
  95045. this.motorImpulse = 0;
  95046. this.maxMotorImpulse = 0;
  95047. }
  95048. var rdx = d * this.ax;
  95049. var rdy = d * this.ay;
  95050. var rdz = d * this.az;
  95051. var w1 = this.m1 / (this.m1 + this.m2);
  95052. var w2 = 1 - w1;
  95053. this.r1x = this.r1.x + rdx * w1;
  95054. this.r1y = this.r1.y + rdy * w1;
  95055. this.r1z = this.r1.z + rdz * w1;
  95056. this.r2x = this.r2.x - rdx * w2;
  95057. this.r2y = this.r2.y - rdy * w2;
  95058. this.r2z = this.r2.z - rdz * w2;
  95059. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  95060. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  95061. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  95062. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  95063. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  95064. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  95065. this.l1x = this.ax * this.m1;
  95066. this.l1y = this.ay * this.m1;
  95067. this.l1z = this.az * this.m1;
  95068. this.l2x = this.ax * this.m2;
  95069. this.l2y = this.ay * this.m2;
  95070. this.l2z = this.az * this.m2;
  95071. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  95072. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  95073. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  95074. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  95075. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  95076. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  95077. this.motorDenom =
  95078. this.m1 + this.m2 +
  95079. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  95080. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  95081. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  95082. this.invMotorDenom = 1 / this.motorDenom;
  95083. if (enableSpring && this.limitState != 2) {
  95084. var omega = 6.2831853 * frequency;
  95085. var k = omega * omega * timeStep;
  95086. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  95087. this.cfm = this.motorDenom * dmp;
  95088. this.limitVelocity *= k * dmp;
  95089. } else {
  95090. this.cfm = 0;
  95091. this.limitVelocity *= invTimeStep * 0.05;
  95092. }
  95093. this.invDenom = 1 / (this.motorDenom + this.cfm);
  95094. var totalImpulse = this.limitImpulse + this.motorImpulse;
  95095. this.l1.x += totalImpulse * this.l1x;
  95096. this.l1.y += totalImpulse * this.l1y;
  95097. this.l1.z += totalImpulse * this.l1z;
  95098. this.a1.x += totalImpulse * this.a1x;
  95099. this.a1.y += totalImpulse * this.a1y;
  95100. this.a1.z += totalImpulse * this.a1z;
  95101. this.l2.x -= totalImpulse * this.l2x;
  95102. this.l2.y -= totalImpulse * this.l2y;
  95103. this.l2.z -= totalImpulse * this.l2z;
  95104. this.a2.x -= totalImpulse * this.a2x;
  95105. this.a2.y -= totalImpulse * this.a2y;
  95106. this.a2.z -= totalImpulse * this.a2z;
  95107. },
  95108. solve: function () {
  95109. var rvn =
  95110. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  95111. 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;
  95112. // motor part
  95113. var newMotorImpulse;
  95114. if (this.enableMotor) {
  95115. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  95116. var oldMotorImpulse = this.motorImpulse;
  95117. this.motorImpulse += newMotorImpulse;
  95118. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  95119. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  95120. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  95121. rvn -= newMotorImpulse * this.motorDenom;
  95122. } else newMotorImpulse = 0;
  95123. // limit part
  95124. var newLimitImpulse;
  95125. if (this.limitState != 2) {
  95126. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  95127. var oldLimitImpulse = this.limitImpulse;
  95128. this.limitImpulse += newLimitImpulse;
  95129. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  95130. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  95131. } else newLimitImpulse = 0;
  95132. var totalImpulse = newLimitImpulse + newMotorImpulse;
  95133. this.l1.x += totalImpulse * this.l1x;
  95134. this.l1.y += totalImpulse * this.l1y;
  95135. this.l1.z += totalImpulse * this.l1z;
  95136. this.a1.x += totalImpulse * this.a1x;
  95137. this.a1.y += totalImpulse * this.a1y;
  95138. this.a1.z += totalImpulse * this.a1z;
  95139. this.l2.x -= totalImpulse * this.l2x;
  95140. this.l2.y -= totalImpulse * this.l2y;
  95141. this.l2.z -= totalImpulse * this.l2z;
  95142. this.a2.x -= totalImpulse * this.a2x;
  95143. this.a2.y -= totalImpulse * this.a2y;
  95144. this.a2.z -= totalImpulse * this.a2z;
  95145. }
  95146. }
  95147. /**
  95148. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  95149. * @author saharan
  95150. */
  95151. OIMO.Contact = function () {
  95152. // The first shape.
  95153. this.shape1 = null;
  95154. // The second shape.
  95155. this.shape2 = null;
  95156. // The first rigid body.
  95157. this.body1 = null;
  95158. // The second rigid body.
  95159. this.body2 = null;
  95160. // The previous contact in the world.
  95161. this.prev = null;
  95162. // The next contact in the world.
  95163. this.next = null;
  95164. // Internal
  95165. this.persisting = false;
  95166. // Whether both the rigid bodies are sleeping or not.
  95167. this.sleeping = false;
  95168. // The collision detector between two shapes.
  95169. this.detector = null;
  95170. // The contact constraint of the contact.
  95171. this.constraint = null;
  95172. // Whether the shapes are touching or not.
  95173. this.touching = false;
  95174. this.b1Link = new OIMO.ContactLink(this);
  95175. this.b2Link = new OIMO.ContactLink(this);
  95176. this.s1Link = new OIMO.ContactLink(this);
  95177. this.s2Link = new OIMO.ContactLink(this);
  95178. // The contact manifold of the contact.
  95179. this.manifold = new OIMO.ContactManifold();
  95180. this.buffer = [];// vector 4
  95181. this.buffer.length = 4;
  95182. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  95183. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  95184. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  95185. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  95186. this.points = this.manifold.points;
  95187. this.constraint = new OIMO.ContactConstraint(this.manifold);
  95188. }
  95189. OIMO.Contact.prototype = {
  95190. constructor: OIMO.Contact,
  95191. mixRestitution: function (restitution1, restitution2) {
  95192. return OIMO.sqrt(restitution1 * restitution2);
  95193. },
  95194. mixFriction: function (friction1, friction2) {
  95195. return OIMO.sqrt(friction1 * friction2);
  95196. },
  95197. /**
  95198. * Update the contact manifold.
  95199. */
  95200. updateManifold: function () {
  95201. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  95202. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  95203. var numBuffers = this.manifold.numPoints;
  95204. var i = numBuffers;
  95205. while (i--) {
  95206. //for(var i=0;i<numBuffers;i++){
  95207. var b = this.buffer[i];
  95208. var p = this.points[i];
  95209. b.lp1X = p.localPoint1.x;
  95210. b.lp1Y = p.localPoint1.y;
  95211. b.lp1Z = p.localPoint1.z;
  95212. b.lp2X = p.localPoint2.x;
  95213. b.lp2Y = p.localPoint2.y;
  95214. b.lp2Z = p.localPoint2.z;
  95215. b.impulse = p.normalImpulse;
  95216. }
  95217. this.manifold.numPoints = 0;
  95218. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  95219. var num = this.manifold.numPoints;
  95220. if (num == 0) {
  95221. this.touching = false;
  95222. return;
  95223. }
  95224. this.touching = true;
  95225. i = num;
  95226. while (i--) {
  95227. //for(i=0; i<num; i++){
  95228. p = this.points[i];
  95229. var lp1x = p.localPoint1.x;
  95230. var lp1y = p.localPoint1.y;
  95231. var lp1z = p.localPoint1.z;
  95232. var lp2x = p.localPoint2.x;
  95233. var lp2y = p.localPoint2.y;
  95234. var lp2z = p.localPoint2.z;
  95235. var index = -1;
  95236. var minDistance = 0.0004;
  95237. var j = numBuffers;
  95238. while (j--) {
  95239. //for(var j=0;j<numBuffers;j++){
  95240. b = this.buffer[j];
  95241. var dx = b.lp1X - lp1x;
  95242. var dy = b.lp1Y - lp1y;
  95243. var dz = b.lp1Z - lp1z;
  95244. var distance1 = dx * dx + dy * dy + dz * dz;
  95245. dx = b.lp2X - lp2x;
  95246. dy = b.lp2Y - lp2y;
  95247. dz = b.lp2Z - lp2z;
  95248. var distance2 = dx * dx + dy * dy + dz * dz;
  95249. if (distance1 < distance2) {
  95250. if (distance1 < minDistance) {
  95251. minDistance = distance1;
  95252. index = j;
  95253. }
  95254. } else {
  95255. if (distance2 < minDistance) {
  95256. minDistance = distance2;
  95257. index = j;
  95258. }
  95259. }
  95260. }
  95261. if (index != -1) {
  95262. var tmp = this.buffer[index];
  95263. this.buffer[index] = this.buffer[--numBuffers];
  95264. this.buffer[numBuffers] = tmp;
  95265. p.normalImpulse = tmp.impulse;
  95266. p.warmStarted = true;
  95267. } else {
  95268. p.normalImpulse = 0;
  95269. p.warmStarted = false;
  95270. }
  95271. }
  95272. },
  95273. /**
  95274. * Attach the contact to the shapes.
  95275. * @param shape1
  95276. * @param shape2
  95277. */
  95278. attach: function (shape1, shape2) {
  95279. this.shape1 = shape1;
  95280. this.shape2 = shape2;
  95281. this.body1 = shape1.parent;
  95282. this.body2 = shape2.parent;
  95283. this.manifold.body1 = this.body1;
  95284. this.manifold.body2 = this.body2;
  95285. this.constraint.body1 = this.body1;
  95286. this.constraint.body2 = this.body2;
  95287. this.constraint.attach();
  95288. this.s1Link.shape = shape2;
  95289. this.s1Link.body = this.body2;
  95290. this.s2Link.shape = shape1;
  95291. this.s2Link.body = this.body1;
  95292. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  95293. else this.s1Link.next = null;
  95294. shape1.contactLink = this.s1Link;
  95295. shape1.numContacts++;
  95296. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  95297. else this.s2Link.next = null;
  95298. shape2.contactLink = this.s2Link;
  95299. shape2.numContacts++;
  95300. this.b1Link.shape = shape2;
  95301. this.b1Link.body = this.body2;
  95302. this.b2Link.shape = shape1;
  95303. this.b2Link.body = this.body1;
  95304. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  95305. else this.b1Link.next = null;
  95306. this.body1.contactLink = this.b1Link;
  95307. this.body1.numContacts++;
  95308. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  95309. else this.b2Link.next = null;
  95310. this.body2.contactLink = this.b2Link;
  95311. this.body2.numContacts++;
  95312. this.prev = null;
  95313. this.next = null;
  95314. this.persisting = true;
  95315. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  95316. this.manifold.numPoints = 0;
  95317. },
  95318. /**
  95319. * Detach the contact from the shapes.
  95320. */
  95321. detach: function () {
  95322. var prev = this.s1Link.prev;
  95323. var next = this.s1Link.next;
  95324. if (prev !== null) prev.next = next;
  95325. if (next !== null) next.prev = prev;
  95326. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  95327. this.s1Link.prev = null;
  95328. this.s1Link.next = null;
  95329. this.s1Link.shape = null;
  95330. this.s1Link.body = null;
  95331. this.shape1.numContacts--;
  95332. prev = this.s2Link.prev;
  95333. next = this.s2Link.next;
  95334. if (prev !== null) prev.next = next;
  95335. if (next !== null) next.prev = prev;
  95336. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  95337. this.s2Link.prev = null;
  95338. this.s2Link.next = null;
  95339. this.s2Link.shape = null;
  95340. this.s2Link.body = null;
  95341. this.shape2.numContacts--;
  95342. prev = this.b1Link.prev;
  95343. next = this.b1Link.next;
  95344. if (prev !== null) prev.next = next;
  95345. if (next !== null) next.prev = prev;
  95346. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  95347. this.b1Link.prev = null;
  95348. this.b1Link.next = null;
  95349. this.b1Link.shape = null;
  95350. this.b1Link.body = null;
  95351. this.body1.numContacts--;
  95352. prev = this.b2Link.prev;
  95353. next = this.b2Link.next;
  95354. if (prev !== null) prev.next = next;
  95355. if (next !== null) next.prev = prev;
  95356. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  95357. this.b2Link.prev = null;
  95358. this.b2Link.next = null;
  95359. this.b2Link.shape = null;
  95360. this.b2Link.body = null;
  95361. this.body2.numContacts--;
  95362. this.manifold.body1 = null;
  95363. this.manifold.body2 = null;
  95364. this.constraint.body1 = null;
  95365. this.constraint.body2 = null;
  95366. this.constraint.detach();
  95367. this.shape1 = null;
  95368. this.shape2 = null;
  95369. this.body1 = null;
  95370. this.body2 = null;
  95371. }
  95372. }
  95373. /**
  95374. * ...
  95375. * @author saharan
  95376. */
  95377. OIMO.ContactConstraint = function (manifold) {
  95378. OIMO.Constraint.call(this);
  95379. // The contact manifold of the constraint.
  95380. this.manifold = manifold;
  95381. // The coefficient of restitution of the constraint.
  95382. this.restitution = NaN;
  95383. // The coefficient of friction of the constraint.
  95384. this.friction = NaN;
  95385. this.p1 = null;
  95386. this.p2 = null;
  95387. this.lv1 = null;
  95388. this.lv2 = null;
  95389. this.av1 = null;
  95390. this.av2 = null;
  95391. this.i1 = null;
  95392. this.i2 = null;
  95393. this.ii1 = null;
  95394. this.ii2 = null;
  95395. this.m1 = NaN;
  95396. this.m2 = NaN;
  95397. this.num = 0;
  95398. this.ps = manifold.points;
  95399. this.cs = new OIMO.ContactPointDataBuffer();
  95400. this.cs.next = new OIMO.ContactPointDataBuffer();
  95401. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  95402. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  95403. }
  95404. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  95405. /**
  95406. * Attach the constraint to the bodies.
  95407. */
  95408. OIMO.ContactConstraint.prototype.attach = function () {
  95409. this.p1 = this.body1.position;
  95410. this.p2 = this.body2.position;
  95411. this.lv1 = this.body1.linearVelocity;
  95412. this.av1 = this.body1.angularVelocity;
  95413. this.lv2 = this.body2.linearVelocity;
  95414. this.av2 = this.body2.angularVelocity;
  95415. this.i1 = this.body1.inverseInertia;
  95416. this.i2 = this.body2.inverseInertia;
  95417. }
  95418. /**
  95419. * Detach the constraint from the bodies.
  95420. */
  95421. OIMO.ContactConstraint.prototype.detach = function () {
  95422. this.p1 = null;
  95423. this.p2 = null;
  95424. this.lv1 = null;
  95425. this.lv2 = null;
  95426. this.av1 = null;
  95427. this.av2 = null;
  95428. this.i1 = null;
  95429. this.i2 = null;
  95430. }
  95431. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  95432. this.m1 = this.body1.inverseMass;
  95433. this.m2 = this.body2.inverseMass;
  95434. this.ii1 = this.i1.clone();
  95435. this.ii2 = this.i2.clone();
  95436. var ii1 = this.ii1.elements;
  95437. var ii2 = this.ii2.elements;
  95438. var p1x = this.p1.x;
  95439. var p1y = this.p1.y;
  95440. var p1z = this.p1.z;
  95441. var p2x = this.p2.x;
  95442. var p2y = this.p2.y;
  95443. var p2z = this.p2.z;
  95444. var m1m2 = this.m1 + this.m2;
  95445. this.num = this.manifold.numPoints;
  95446. var c = this.cs;
  95447. for (var i = 0; i < this.num; i++) {
  95448. var p = this.ps[i];
  95449. var tmp1X;
  95450. var tmp1Y;
  95451. var tmp1Z;
  95452. var tmp2X;
  95453. var tmp2Y;
  95454. var tmp2Z;
  95455. tmp1X = p.position.x;
  95456. tmp1Y = p.position.y;
  95457. tmp1Z = p.position.z;
  95458. var rp1X = tmp1X - p1x;
  95459. var rp1Y = tmp1Y - p1y;
  95460. var rp1Z = tmp1Z - p1z;
  95461. var rp2X = tmp1X - p2x;
  95462. var rp2Y = tmp1Y - p2y;
  95463. var rp2Z = tmp1Z - p2z;
  95464. c.rp1X = rp1X;
  95465. c.rp1Y = rp1Y;
  95466. c.rp1Z = rp1Z;
  95467. c.rp2X = rp2X;
  95468. c.rp2Y = rp2Y;
  95469. c.rp2Z = rp2Z;
  95470. c.norImp = p.normalImpulse;
  95471. c.tanImp = p.tangentImpulse;
  95472. c.binImp = p.binormalImpulse;
  95473. var norX = p.normal.x;
  95474. var norY = p.normal.y;
  95475. var norZ = p.normal.z;
  95476. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  95477. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  95478. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  95479. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  95480. var tanX = rvX - rvn * norX;
  95481. var tanY = rvY - rvn * norY;
  95482. var tanZ = rvZ - rvn * norZ;
  95483. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  95484. if (len > 0.04) {
  95485. len = 1 / OIMO.sqrt(len);
  95486. } else {
  95487. tanX = norY * norX - norZ * norZ;
  95488. tanY = -norZ * norY - norX * norX;
  95489. tanZ = norX * norZ + norY * norY;
  95490. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  95491. }
  95492. tanX *= len;
  95493. tanY *= len;
  95494. tanZ *= len;
  95495. var binX = norY * tanZ - norZ * tanY;
  95496. var binY = norZ * tanX - norX * tanZ;
  95497. var binZ = norX * tanY - norY * tanX;
  95498. c.norX = norX;
  95499. c.norY = norY;
  95500. c.norZ = norZ;
  95501. c.tanX = tanX;
  95502. c.tanY = tanY;
  95503. c.tanZ = tanZ;
  95504. c.binX = binX;
  95505. c.binY = binY;
  95506. c.binZ = binZ;
  95507. c.norU1X = norX * this.m1;
  95508. c.norU1Y = norY * this.m1;
  95509. c.norU1Z = norZ * this.m1;
  95510. c.norU2X = norX * this.m2;
  95511. c.norU2Y = norY * this.m2;
  95512. c.norU2Z = norZ * this.m2;
  95513. c.tanU1X = tanX * this.m1;
  95514. c.tanU1Y = tanY * this.m1;
  95515. c.tanU1Z = tanZ * this.m1;
  95516. c.tanU2X = tanX * this.m2;
  95517. c.tanU2Y = tanY * this.m2;
  95518. c.tanU2Z = tanZ * this.m2;
  95519. c.binU1X = binX * this.m1;
  95520. c.binU1Y = binY * this.m1;
  95521. c.binU1Z = binZ * this.m1;
  95522. c.binU2X = binX * this.m2;
  95523. c.binU2Y = binY * this.m2;
  95524. c.binU2Z = binZ * this.m2;
  95525. var norT1X = rp1Y * norZ - rp1Z * norY;
  95526. var norT1Y = rp1Z * norX - rp1X * norZ;
  95527. var norT1Z = rp1X * norY - rp1Y * norX;
  95528. var norT2X = rp2Y * norZ - rp2Z * norY;
  95529. var norT2Y = rp2Z * norX - rp2X * norZ;
  95530. var norT2Z = rp2X * norY - rp2Y * norX;
  95531. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  95532. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  95533. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  95534. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  95535. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  95536. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  95537. var binT1X = rp1Y * binZ - rp1Z * binY;
  95538. var binT1Y = rp1Z * binX - rp1X * binZ;
  95539. var binT1Z = rp1X * binY - rp1Y * binX;
  95540. var binT2X = rp2Y * binZ - rp2Z * binY;
  95541. var binT2Y = rp2Z * binX - rp2X * binZ;
  95542. var binT2Z = rp2X * binY - rp2Y * binX;
  95543. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  95544. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  95545. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  95546. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  95547. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  95548. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  95549. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  95550. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  95551. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  95552. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  95553. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  95554. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  95555. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  95556. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  95557. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  95558. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  95559. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  95560. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  95561. c.norT1X = norT1X;
  95562. c.norT1Y = norT1Y;
  95563. c.norT1Z = norT1Z;
  95564. c.tanT1X = tanT1X;
  95565. c.tanT1Y = tanT1Y;
  95566. c.tanT1Z = tanT1Z;
  95567. c.binT1X = binT1X;
  95568. c.binT1Y = binT1Y;
  95569. c.binT1Z = binT1Z;
  95570. c.norT2X = norT2X;
  95571. c.norT2Y = norT2Y;
  95572. c.norT2Z = norT2Z;
  95573. c.tanT2X = tanT2X;
  95574. c.tanT2Y = tanT2Y;
  95575. c.tanT2Z = tanT2Z;
  95576. c.binT2X = binT2X;
  95577. c.binT2Y = binT2Y;
  95578. c.binT2Z = binT2Z;
  95579. c.norTU1X = norTU1X;
  95580. c.norTU1Y = norTU1Y;
  95581. c.norTU1Z = norTU1Z;
  95582. c.tanTU1X = tanTU1X;
  95583. c.tanTU1Y = tanTU1Y;
  95584. c.tanTU1Z = tanTU1Z;
  95585. c.binTU1X = binTU1X;
  95586. c.binTU1Y = binTU1Y;
  95587. c.binTU1Z = binTU1Z;
  95588. c.norTU2X = norTU2X;
  95589. c.norTU2Y = norTU2Y;
  95590. c.norTU2Z = norTU2Z;
  95591. c.tanTU2X = tanTU2X;
  95592. c.tanTU2Y = tanTU2Y;
  95593. c.tanTU2Z = tanTU2Z;
  95594. c.binTU2X = binTU2X;
  95595. c.binTU2Y = binTU2Y;
  95596. c.binTU2Z = binTU2Z;
  95597. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  95598. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  95599. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  95600. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  95601. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  95602. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  95603. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  95604. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  95605. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  95606. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  95607. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  95608. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  95609. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  95610. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  95611. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  95612. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  95613. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  95614. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  95615. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  95616. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  95617. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  95618. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  95619. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  95620. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  95621. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  95622. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  95623. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  95624. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  95625. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  95626. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  95627. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  95628. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  95629. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  95630. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  95631. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  95632. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  95633. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  95634. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  95635. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  95636. c.norDen = norDen;
  95637. c.tanDen = tanDen;
  95638. c.binDen = binDen;
  95639. if (p.warmStarted) {
  95640. var norImp = p.normalImpulse;
  95641. this.lv1.x += c.norU1X * norImp;
  95642. this.lv1.y += c.norU1Y * norImp;
  95643. this.lv1.z += c.norU1Z * norImp;
  95644. this.av1.x += norTU1X * norImp;
  95645. this.av1.y += norTU1Y * norImp;
  95646. this.av1.z += norTU1Z * norImp;
  95647. this.lv2.x -= c.norU2X * norImp;
  95648. this.lv2.y -= c.norU2Y * norImp;
  95649. this.lv2.z -= c.norU2Z * norImp;
  95650. this.av2.x -= norTU2X * norImp;
  95651. this.av2.y -= norTU2Y * norImp;
  95652. this.av2.z -= norTU2Z * norImp;
  95653. c.norImp = norImp;
  95654. c.tanImp = 0;
  95655. c.binImp = 0;
  95656. rvn = 0; // disable bouncing
  95657. } else {
  95658. c.norImp = 0;
  95659. c.tanImp = 0;
  95660. c.binImp = 0;
  95661. }
  95662. if (rvn > -1) {
  95663. rvn = 0; // disable bouncing
  95664. }
  95665. var norTar = this.restitution * -rvn;
  95666. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  95667. if (norTar < sepV) norTar = sepV;
  95668. c.norTar = norTar;
  95669. c.last = i == this.num - 1;
  95670. c = c.next;
  95671. }
  95672. }
  95673. OIMO.ContactConstraint.prototype.solve = function () {
  95674. var lv1x = this.lv1.x;
  95675. var lv1y = this.lv1.y;
  95676. var lv1z = this.lv1.z;
  95677. var lv2x = this.lv2.x;
  95678. var lv2y = this.lv2.y;
  95679. var lv2z = this.lv2.z;
  95680. var av1x = this.av1.x;
  95681. var av1y = this.av1.y;
  95682. var av1z = this.av1.z;
  95683. var av2x = this.av2.x;
  95684. var av2y = this.av2.y;
  95685. var av2z = this.av2.z;
  95686. var c = this.cs;
  95687. while (true) {
  95688. var oldImp1;
  95689. var newImp1;
  95690. var oldImp2;
  95691. var newImp2;
  95692. var rvn;
  95693. var norImp = c.norImp;
  95694. var tanImp = c.tanImp;
  95695. var binImp = c.binImp;
  95696. var max = -norImp * this.friction;
  95697. var rvX = lv2x - lv1x;
  95698. var rvY = lv2y - lv1y;
  95699. var rvZ = lv2z - lv1z;
  95700. rvn =
  95701. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  95702. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  95703. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  95704. ;
  95705. oldImp1 = tanImp;
  95706. newImp1 = rvn * c.tanDen;
  95707. tanImp += newImp1;
  95708. rvn =
  95709. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  95710. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  95711. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  95712. ;
  95713. oldImp2 = binImp;
  95714. newImp2 = rvn * c.binDen;
  95715. binImp += newImp2;
  95716. // cone friction clamp
  95717. var len = tanImp * tanImp + binImp * binImp;
  95718. if (len > max * max) {
  95719. len = max / OIMO.sqrt(len);
  95720. tanImp *= len;
  95721. binImp *= len;
  95722. }
  95723. newImp1 = tanImp - oldImp1;
  95724. newImp2 = binImp - oldImp2;
  95725. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  95726. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  95727. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  95728. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  95729. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  95730. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  95731. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  95732. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  95733. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  95734. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  95735. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  95736. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  95737. // restitution part
  95738. rvn =
  95739. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  95740. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  95741. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  95742. oldImp1 = norImp;
  95743. newImp1 = (rvn - c.norTar) * c.norDen;
  95744. norImp += newImp1;
  95745. if (norImp > 0) norImp = 0;
  95746. newImp1 = norImp - oldImp1;
  95747. lv1x += c.norU1X * newImp1;
  95748. lv1y += c.norU1Y * newImp1;
  95749. lv1z += c.norU1Z * newImp1;
  95750. av1x += c.norTU1X * newImp1;
  95751. av1y += c.norTU1Y * newImp1;
  95752. av1z += c.norTU1Z * newImp1;
  95753. lv2x -= c.norU2X * newImp1;
  95754. lv2y -= c.norU2Y * newImp1;
  95755. lv2z -= c.norU2Z * newImp1;
  95756. av2x -= c.norTU2X * newImp1;
  95757. av2y -= c.norTU2Y * newImp1;
  95758. av2z -= c.norTU2Z * newImp1;
  95759. c.norImp = norImp;
  95760. c.tanImp = tanImp;
  95761. c.binImp = binImp;
  95762. if (c.last) break;
  95763. c = c.next;
  95764. }
  95765. this.lv1.x = lv1x;
  95766. this.lv1.y = lv1y;
  95767. this.lv1.z = lv1z;
  95768. this.lv2.x = lv2x;
  95769. this.lv2.y = lv2y;
  95770. this.lv2.z = lv2z;
  95771. this.av1.x = av1x;
  95772. this.av1.y = av1y;
  95773. this.av1.z = av1z;
  95774. this.av2.x = av2x;
  95775. this.av2.y = av2y;
  95776. this.av2.z = av2z;
  95777. }
  95778. OIMO.ContactConstraint.prototype.postSolve = function () {
  95779. var c = this.cs;
  95780. var i = this.num;
  95781. while (i--) {
  95782. //for(var i=0;i<this.num;i++){
  95783. var p = this.ps[i];
  95784. p.normal.x = c.norX;
  95785. p.normal.y = c.norY;
  95786. p.normal.z = c.norZ;
  95787. p.tangent.x = c.tanX;
  95788. p.tangent.y = c.tanY;
  95789. p.tangent.z = c.tanZ;
  95790. p.binormal.x = c.binX;
  95791. p.binormal.y = c.binY;
  95792. p.binormal.z = c.binZ;
  95793. p.normalImpulse = c.norImp;
  95794. p.tangentImpulse = c.tanImp;
  95795. p.binormalImpulse = c.binImp;
  95796. p.normalDenominator = c.norDen;
  95797. p.tangentDenominator = c.tanDen;
  95798. p.binormalDenominator = c.binDen;
  95799. c = c.next;
  95800. }
  95801. }
  95802. /**
  95803. * A link list of contacts.
  95804. * @author saharan
  95805. */
  95806. OIMO.ContactLink = function (contact) {
  95807. // The previous contact link.
  95808. this.prev = null;
  95809. // The next contact link.
  95810. this.next = null;
  95811. // The shape of the contact.
  95812. this.shape = null;
  95813. // The other rigid body.
  95814. this.body = null;
  95815. // The contact of the link.
  95816. this.contact = contact;
  95817. }
  95818. /**
  95819. * A contact manifold between two shapes.
  95820. * @author saharan
  95821. */
  95822. OIMO.ContactManifold = function () {
  95823. // The first rigid body.
  95824. this.body1 = null;
  95825. // The second rigid body.
  95826. this.body2 = null;
  95827. // The number of manifold points.
  95828. this.numPoints = 0;
  95829. // The manifold points.
  95830. this.points = [];
  95831. this.points.length = 4;
  95832. this.points[0] = new OIMO.ManifoldPoint();
  95833. this.points[1] = new OIMO.ManifoldPoint();
  95834. this.points[2] = new OIMO.ManifoldPoint();
  95835. this.points[3] = new OIMO.ManifoldPoint();
  95836. }
  95837. OIMO.ContactManifold.prototype = {
  95838. constructor: OIMO.ContactManifold,
  95839. /**
  95840. * Reset the manifold.
  95841. * @param shape1
  95842. * @param shape2
  95843. */
  95844. reset: function (shape1, shape2) {
  95845. this.body1 = shape1.parent;
  95846. this.body2 = shape2.parent;
  95847. this.numPoints = 0;
  95848. },
  95849. /**
  95850. * Add a point into this manifold.
  95851. * @param x
  95852. * @param y
  95853. * @param z
  95854. * @param normalX
  95855. * @param normalY
  95856. * @param normalZ
  95857. * @param penetration
  95858. * @param flip
  95859. */
  95860. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  95861. var p = this.points[this.numPoints++];
  95862. p.position.x = x;
  95863. p.position.y = y;
  95864. p.position.z = z;
  95865. var r = this.body1.rotation;
  95866. var rx = x - this.body1.position.x;
  95867. var ry = y - this.body1.position.y;
  95868. var rz = z - this.body1.position.z;
  95869. var tr = r.elements;
  95870. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  95871. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  95872. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  95873. r = this.body2.rotation;
  95874. rx = x - this.body2.position.x;
  95875. ry = y - this.body2.position.y;
  95876. rz = z - this.body2.position.z;
  95877. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  95878. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  95879. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  95880. p.normalImpulse = 0;
  95881. if (flip) {
  95882. p.normal.x = -normalX;
  95883. p.normal.y = -normalY;
  95884. p.normal.z = -normalZ;
  95885. } else {
  95886. p.normal.x = normalX;
  95887. p.normal.y = normalY;
  95888. p.normal.z = normalZ;
  95889. }
  95890. p.penetration = penetration;
  95891. p.warmStarted = false;
  95892. }
  95893. }
  95894. OIMO.ContactPointDataBuffer = function () {
  95895. this.norX = NaN;
  95896. this.norY = NaN;
  95897. this.norZ = NaN;
  95898. this.tanX = NaN;
  95899. this.tanY = NaN;
  95900. this.tanZ = NaN;
  95901. this.binX = NaN;
  95902. this.binY = NaN;
  95903. this.binZ = NaN;
  95904. this.rp1X = NaN;
  95905. this.rp1Y = NaN;
  95906. this.rp1Z = NaN;
  95907. this.rp2X = NaN;
  95908. this.rp2Y = NaN;
  95909. this.rp2Z = NaN;
  95910. this.norU1X = NaN;
  95911. this.norU1Y = NaN;
  95912. this.norU1Z = NaN;
  95913. this.norU2X = NaN;
  95914. this.norU2Y = NaN;
  95915. this.norU2Z = NaN;
  95916. this.tanU1X = NaN;
  95917. this.tanU1Y = NaN;
  95918. this.tanU1Z = NaN;
  95919. this.tanU2X = NaN;
  95920. this.tanU2Y = NaN;
  95921. this.tanU2Z = NaN;
  95922. this.binU1X = NaN;
  95923. this.binU1Y = NaN;
  95924. this.binU1Z = NaN;
  95925. this.binU2X = NaN;
  95926. this.binU2Y = NaN;
  95927. this.binU2Z = NaN;
  95928. this.norT1X = NaN;
  95929. this.norT1Y = NaN;
  95930. this.norT1Z = NaN;
  95931. this.norT2X = NaN;
  95932. this.norT2Y = NaN;
  95933. this.norT2Z = NaN;
  95934. this.tanT1X = NaN;
  95935. this.tanT1Y = NaN;
  95936. this.tanT1Z = NaN;
  95937. this.tanT2X = NaN;
  95938. this.tanT2Y = NaN;
  95939. this.tanT2Z = NaN;
  95940. this.binT1X = NaN;
  95941. this.binT1Y = NaN;
  95942. this.binT1Z = NaN;
  95943. this.binT2X = NaN;
  95944. this.binT2Y = NaN;
  95945. this.binT2Z = NaN;
  95946. this.norTU1X = NaN;
  95947. this.norTU1Y = NaN;
  95948. this.norTU1Z = NaN;
  95949. this.norTU2X = NaN;
  95950. this.norTU2Y = NaN;
  95951. this.norTU2Z = NaN;
  95952. this.tanTU1X = NaN;
  95953. this.tanTU1Y = NaN;
  95954. this.tanTU1Z = NaN;
  95955. this.tanTU2X = NaN;
  95956. this.tanTU2Y = NaN;
  95957. this.tanTU2Z = NaN;
  95958. this.binTU1X = NaN;
  95959. this.binTU1Y = NaN;
  95960. this.binTU1Z = NaN;
  95961. this.binTU2X = NaN;
  95962. this.binTU2Y = NaN;
  95963. this.binTU2Z = NaN;
  95964. this.norImp = NaN;
  95965. this.tanImp = NaN;
  95966. this.binImp = NaN;
  95967. this.norDen = NaN;
  95968. this.tanDen = NaN;
  95969. this.binDen = NaN;
  95970. this.norTar = NaN;
  95971. this.next = null;
  95972. this.last = false;
  95973. }
  95974. OIMO.ImpulseDataBuffer = function () {
  95975. this.lp1X = NaN;
  95976. this.lp1Y = NaN;
  95977. this.lp1Z = NaN;
  95978. this.lp2X = NaN;
  95979. this.lp2Y = NaN;
  95980. this.lp2Z = NaN;
  95981. this.impulse = NaN;
  95982. }
  95983. /**
  95984. * The class holds details of the contact point.
  95985. * @author saharan
  95986. */
  95987. OIMO.ManifoldPoint = function () {
  95988. // Whether this manifold point is persisting or not.
  95989. this.warmStarted = false;
  95990. // The position of this manifold point.
  95991. this.position = new OIMO.Vec3();
  95992. // The position in the first shape's coordinate.
  95993. this.localPoint1 = new OIMO.Vec3();
  95994. // The position in the second shape's coordinate.
  95995. this.localPoint2 = new OIMO.Vec3();
  95996. // The normal vector of this manifold point.
  95997. this.normal = new OIMO.Vec3();
  95998. // The tangent vector of this manifold point.
  95999. this.tangent = new OIMO.Vec3();
  96000. // The binormal vector of this manifold point.
  96001. this.binormal = new OIMO.Vec3();
  96002. // The impulse in normal direction.
  96003. this.normalImpulse = 0;
  96004. // The impulse in tangent direction.
  96005. this.tangentImpulse = 0;
  96006. // The impulse in binormal direction.
  96007. this.binormalImpulse = 0;
  96008. // The denominator in normal direction.
  96009. this.normalDenominator = 0;
  96010. // The denominator in tangent direction.
  96011. this.tangentDenominator = 0;
  96012. // The denominator in binormal direction.
  96013. this.binormalDenominator = 0;
  96014. // The depth of penetration.
  96015. this.penetration = 0;
  96016. }
  96017. /**
  96018. * This class holds mass information of a shape.
  96019. * @author saharan
  96020. */
  96021. OIMO.MassInfo = function () {
  96022. // Mass of the shape.
  96023. this.mass = 0;
  96024. // The moment inertia of the shape.
  96025. this.inertia = new OIMO.Mat33();
  96026. };
  96027. /**
  96028. * A shape is used to detect collisions of rigid bodies.
  96029. * @author saharan
  96030. * @author lo-th
  96031. */
  96032. OIMO.Shape = function (config) {
  96033. this.type = OIMO.SHAPE_NULL;
  96034. // The global identification of the shape should be unique to the shape.
  96035. this.id = OIMO.nextID++;
  96036. // The previous shape in parent rigid body.
  96037. this.prev = null;
  96038. // The next shape in parent rigid body.
  96039. this.next = null;
  96040. // The proxy of the shape used for broad-phase collision detection.
  96041. this.proxy = null;
  96042. // The parent rigid body of the shape.
  96043. this.parent = null;
  96044. // The linked list of the contacts with the shape.
  96045. this.contactLink = null;
  96046. // The number of the contacts with the shape.
  96047. this.numContacts = 0;
  96048. // The center of gravity of the shape in world coordinate system.
  96049. this.position = new OIMO.Vec3();
  96050. // The rotation matrix of the shape in world coordinate system
  96051. this.rotation = new OIMO.Mat33();
  96052. // The position of the shape in parent's coordinate system.
  96053. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  96054. // The rotation matrix of the shape in parent's coordinate system.
  96055. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  96056. // The axis-aligned bounding box of the shape.
  96057. this.aabb = new OIMO.AABB();
  96058. // The density of the shape.
  96059. this.density = config.density;
  96060. // The coefficient of friction of the shape.
  96061. this.friction = config.friction;
  96062. // The coefficient of restitution of the shape.
  96063. this.restitution = config.restitution;
  96064. // The bits of the collision groups to which the shape belongs.
  96065. this.belongsTo = config.belongsTo;
  96066. // The bits of the collision groups with which the shape collides.
  96067. this.collidesWith = config.collidesWith;
  96068. };
  96069. OIMO.Shape.prototype = {
  96070. constructor: OIMO.Shape,
  96071. // Calculate the mass information of the shape.
  96072. calculateMassInfo: function (out) {
  96073. OIMO.Error("Shape", "Inheritance error.");
  96074. },
  96075. // Update the proxy of the shape.
  96076. updateProxy: function () {
  96077. OIMO.Error("Shape", "Inheritance error.");
  96078. }
  96079. };
  96080. /**
  96081. * A shape configuration holds common configuration data for constructing a shape.
  96082. * Shape configurations can be reused safely.
  96083. * @author saharan
  96084. */
  96085. OIMO.ShapeConfig = function () {
  96086. // The position of the shape in parent's coordinate system.
  96087. this.relativePosition = new OIMO.Vec3();
  96088. // The rotation matrix of the shape in parent's coordinate system.
  96089. this.relativeRotation = new OIMO.Mat33();
  96090. // The coefficient of friction of the shape.
  96091. this.friction = 0.4;
  96092. // The coefficient of restitution of the shape.
  96093. this.restitution = 0.2;
  96094. // The density of the shape.
  96095. this.density = 1;
  96096. // The bits of the collision groups to which the shape belongs.
  96097. this.belongsTo = 1;
  96098. // The bits of the collision groups with which the shape collides.
  96099. this.collidesWith = 0xffffffff;
  96100. };
  96101. /**
  96102. * A box shape.
  96103. * @author saharan
  96104. * @author lo-th
  96105. */
  96106. OIMO.BoxShape = function (config, Width, Height, Depth) {
  96107. OIMO.Shape.call(this, config);
  96108. this.type = OIMO.SHAPE_BOX;
  96109. // The width of the box.
  96110. this.width = Width;
  96111. // The height of the box.
  96112. this.height = Height;
  96113. // The depth of the box.
  96114. this.depth = Depth;
  96115. // The half-width of the box.
  96116. this.halfWidth = Width * 0.5;
  96117. // The half-height of the box.
  96118. this.halfHeight = Height * 0.5;
  96119. // The half-depth of the box.
  96120. this.halfDepth = Depth * 0.5;
  96121. this.dimentions = new OIMO_ARRAY_TYPE(18);
  96122. this.elements = new OIMO_ARRAY_TYPE(24);
  96123. };
  96124. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  96125. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  96126. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  96127. var mass = this.width * this.height * this.depth * this.density;
  96128. var divid = 1 / 12;
  96129. out.mass = mass;
  96130. out.inertia.set(
  96131. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  96132. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  96133. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  96134. );
  96135. };
  96136. OIMO.BoxShape.prototype.updateProxy = function () {
  96137. var te = this.rotation.elements;
  96138. var di = this.dimentions;
  96139. // Width
  96140. di[0] = te[0];
  96141. di[1] = te[3];
  96142. di[2] = te[6];
  96143. // Height
  96144. di[3] = te[1];
  96145. di[4] = te[4];
  96146. di[5] = te[7];
  96147. // Depth
  96148. di[6] = te[2];
  96149. di[7] = te[5];
  96150. di[8] = te[8];
  96151. // halp Width
  96152. di[9] = te[0] * this.halfWidth;
  96153. di[10] = te[3] * this.halfWidth;
  96154. di[11] = te[6] * this.halfWidth;
  96155. // halp Height
  96156. di[12] = te[1] * this.halfHeight;
  96157. di[13] = te[4] * this.halfHeight;
  96158. di[14] = te[7] * this.halfHeight;
  96159. // halp Depth
  96160. di[15] = te[2] * this.halfDepth;
  96161. di[16] = te[5] * this.halfDepth;
  96162. di[17] = te[8] * this.halfDepth;
  96163. var wx = di[9];
  96164. var wy = di[10];
  96165. var wz = di[11];
  96166. var hx = di[12];
  96167. var hy = di[13];
  96168. var hz = di[14];
  96169. var dx = di[15];
  96170. var dy = di[16];
  96171. var dz = di[17];
  96172. var x = this.position.x;
  96173. var y = this.position.y;
  96174. var z = this.position.z;
  96175. var v = this.elements;
  96176. //v1
  96177. v[0] = x + wx + hx + dx;
  96178. v[1] = y + wy + hy + dy;
  96179. v[2] = z + wz + hz + dz;
  96180. //v2
  96181. v[3] = x + wx + hx - dx;
  96182. v[4] = y + wy + hy - dy;
  96183. v[5] = z + wz + hz - dz;
  96184. //v3
  96185. v[6] = x + wx - hx + dx;
  96186. v[7] = y + wy - hy + dy;
  96187. v[8] = z + wz - hz + dz;
  96188. //v4
  96189. v[9] = x + wx - hx - dx;
  96190. v[10] = y + wy - hy - dy;
  96191. v[11] = z + wz - hz - dz;
  96192. //v5
  96193. v[12] = x - wx + hx + dx;
  96194. v[13] = y - wy + hy + dy;
  96195. v[14] = z - wz + hz + dz;
  96196. //v6
  96197. v[15] = x - wx + hx - dx;
  96198. v[16] = y - wy + hy - dy;
  96199. v[17] = z - wz + hz - dz;
  96200. //v7
  96201. v[18] = x - wx - hx + dx;
  96202. v[19] = y - wy - hy + dy;
  96203. v[20] = z - wz - hz + dz;
  96204. //v8
  96205. v[21] = x - wx - hx - dx;
  96206. v[22] = y - wy - hy - dy;
  96207. v[23] = z - wz - hz - dz;
  96208. var w = di[9] < 0 ? -di[9] : di[9];
  96209. var h = di[10] < 0 ? -di[10] : di[10];
  96210. var d = di[11] < 0 ? -di[11] : di[11];
  96211. w = di[12] < 0 ? w - di[12] : w + di[12];
  96212. h = di[13] < 0 ? h - di[13] : h + di[13];
  96213. d = di[14] < 0 ? d - di[14] : d + di[14];
  96214. w = di[15] < 0 ? w - di[15] : w + di[15];
  96215. h = di[16] < 0 ? h - di[16] : h + di[16];
  96216. d = di[17] < 0 ? d - di[17] : d + di[17];
  96217. var p = OIMO.AABB_PROX;
  96218. this.aabb.set(
  96219. this.position.x - w - p, this.position.x + w + p,
  96220. this.position.y - h - p, this.position.y + h + p,
  96221. this.position.z - d - p, this.position.z + d + p
  96222. );
  96223. if (this.proxy != null) this.proxy.update();
  96224. };
  96225. /**
  96226. * A sphere shape.
  96227. * @author saharan
  96228. * @author lo-th
  96229. */
  96230. OIMO.SphereShape = function (config, radius) {
  96231. OIMO.Shape.call(this, config);
  96232. this.type = OIMO.SHAPE_SPHERE;
  96233. // The radius of the shape.
  96234. this.radius = radius;
  96235. };
  96236. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  96237. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  96238. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  96239. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  96240. out.mass = mass;
  96241. var inertia = mass * this.radius * this.radius * 0.4;
  96242. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  96243. };
  96244. OIMO.SphereShape.prototype.updateProxy = function () {
  96245. var p = OIMO.AABB_PROX;
  96246. this.aabb.set(
  96247. this.position.x - this.radius - p, this.position.x + this.radius + p,
  96248. this.position.y - this.radius - p, this.position.y + this.radius + p,
  96249. this.position.z - this.radius - p, this.position.z + this.radius + p
  96250. );
  96251. if (this.proxy != null) this.proxy.update();
  96252. };
  96253. /**
  96254. * A cylinder shap.
  96255. * @author saharan
  96256. * @author lo-th
  96257. */
  96258. OIMO.CylinderShape = function (config, radius, height) {
  96259. OIMO.Shape.call(this, config);
  96260. this.type = OIMO.SHAPE_CYLINDER;
  96261. this.radius = radius;
  96262. this.height = height;
  96263. this.halfHeight = height * 0.5;
  96264. this.normalDirection = new OIMO.Vec3();
  96265. this.halfDirection = new OIMO.Vec3();
  96266. };
  96267. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  96268. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  96269. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  96270. var rsq = this.radius * this.radius;
  96271. var mass = OIMO.PI * rsq * this.height * this.density;
  96272. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  96273. var inertiaY = 0.5 * rsq;
  96274. out.mass = mass;
  96275. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  96276. };
  96277. OIMO.CylinderShape.prototype.updateProxy = function () {
  96278. var te = this.rotation.elements;
  96279. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  96280. xx = te[1] * te[1];
  96281. yy = te[4] * te[4];
  96282. zz = te[7] * te[7];
  96283. this.normalDirection.set(te[1], te[4], te[7]);
  96284. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  96285. wx = 1 - xx;
  96286. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  96287. if (len > 0) len = this.radius / len;
  96288. wx *= len;
  96289. hy = 1 - yy;
  96290. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  96291. if (len > 0) len = this.radius / len;
  96292. hy *= len;
  96293. dz = 1 - zz;
  96294. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  96295. if (len > 0) len = this.radius / len;
  96296. dz *= len;
  96297. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  96298. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  96299. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  96300. w = wx < 0 ? w - wx : w + wx;
  96301. h = hy < 0 ? h - hy : h + hy;
  96302. d = dz < 0 ? d - dz : d + dz;
  96303. p = OIMO.AABB_PROX;
  96304. this.aabb.set(
  96305. this.position.x - w - p, this.position.x + w + p,
  96306. this.position.y - h - p, this.position.y + h + p,
  96307. this.position.z - d - p, this.position.z + d + p
  96308. );
  96309. if (this.proxy != null) this.proxy.update();
  96310. };
  96311. /**
  96312. * A tetra shape.
  96313. * @author xprogram
  96314. */
  96315. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  96316. OIMO.Shape.call(this, config);
  96317. this.type = OIMO.SHAPE_TETRA;
  96318. // Vertices and faces of tetra
  96319. this.verts = [p1, p2, p3, p4];
  96320. this.faces = [
  96321. mtri(0, 1, 2),
  96322. mtri(1, 2, 3),
  96323. mtri(2, 3, 4),
  96324. mtri(4, 0, 1),
  96325. ];
  96326. };
  96327. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  96328. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  96329. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  96330. // I guess you could calculate box mass and split it
  96331. // in half for the tetra...
  96332. };
  96333. OIMO.TetraShape.prototype.updateProxy = function () {
  96334. this.aabb.setFromPoints(this.verts);
  96335. if (this.proxy !== null)
  96336. this.proxy.update();
  96337. };
  96338. function mtri(a, b, c) {
  96339. return { a: a, b: b, c: c };
  96340. }
  96341. OIMO.CollisionDetector = function () {
  96342. this.flip = false;
  96343. };
  96344. OIMO.CollisionDetector.prototype = {
  96345. constructor: OIMO.CollisionDetector,
  96346. detectCollision: function (shape1, shape2, manifold) {
  96347. OIMO.Error("CollisionDetector", "Inheritance error.");
  96348. }
  96349. };
  96350. /**
  96351. * A collision detector which detects collisions between two boxes.
  96352. * @author saharan
  96353. */
  96354. OIMO.BoxBoxCollisionDetector = function () {
  96355. OIMO.CollisionDetector.call(this);
  96356. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  96357. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  96358. this.used = new OIMO_ARRAY_TYPE(8);
  96359. this.INF = 1 / 0;
  96360. };
  96361. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  96362. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  96363. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  96364. // What you are doing
  96365. // · I to prepare a separate axis of the fifteen
  96366. //-Six in each of three normal vectors of the xyz direction of the box both
  96367. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  96368. // · Calculate the depth to the separation axis
  96369. // Calculates the distance using the inner product and put the amount of embedment
  96370. // · However a vertical separation axis and side to weight a little to avoid vibration
  96371. // And end when there is a separate axis that is remote even one
  96372. // · I look for separation axis with little to dent most
  96373. // Men and if separation axis of the first six - end collision
  96374. // Heng If it separate axis of nine other - side collision
  96375. // Heng - case of a side collision
  96376. // · Find points of two sides on which you made ​​the separation axis
  96377. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  96378. //-Surface - the case of the plane crash
  96379. //-Box A, box B and the other a box of better made ​​a separate axis
  96380. // • 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
  96381. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  96382. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  96383. // • If more than one candidate 5 exists, scraping up to four
  96384. // For potential collision points of all, to examine the distance between the surface A
  96385. // • If you were on the inside surface of A, and the collision point
  96386. var b1;
  96387. var b2;
  96388. if (shape1.id < shape2.id) {
  96389. b1 = (shape1);
  96390. b2 = (shape2);
  96391. } else {
  96392. b1 = (shape2);
  96393. b2 = (shape1);
  96394. }
  96395. var V1 = b1.elements;
  96396. var V2 = b2.elements;
  96397. var D1 = b1.dimentions;
  96398. var D2 = b2.dimentions;
  96399. var p1 = b1.position;
  96400. var p2 = b2.position;
  96401. var p1x = p1.x;
  96402. var p1y = p1.y;
  96403. var p1z = p1.z;
  96404. var p2x = p2.x;
  96405. var p2y = p2.y;
  96406. var p2z = p2.z;
  96407. // diff
  96408. var dx = p2x - p1x;
  96409. var dy = p2y - p1y;
  96410. var dz = p2z - p1z;
  96411. // distance
  96412. var w1 = b1.halfWidth;
  96413. var h1 = b1.halfHeight;
  96414. var d1 = b1.halfDepth;
  96415. var w2 = b2.halfWidth;
  96416. var h2 = b2.halfHeight;
  96417. var d2 = b2.halfDepth;
  96418. // direction
  96419. // ----------------------------
  96420. // 15 separating axes
  96421. // 1~6: face
  96422. // 7~f: edge
  96423. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  96424. // ----------------------------
  96425. var a1x = D1[0];
  96426. var a1y = D1[1];
  96427. var a1z = D1[2];
  96428. var a2x = D1[3];
  96429. var a2y = D1[4];
  96430. var a2z = D1[5];
  96431. var a3x = D1[6];
  96432. var a3y = D1[7];
  96433. var a3z = D1[8];
  96434. var d1x = D1[9];
  96435. var d1y = D1[10];
  96436. var d1z = D1[11];
  96437. var d2x = D1[12];
  96438. var d2y = D1[13];
  96439. var d2z = D1[14];
  96440. var d3x = D1[15];
  96441. var d3y = D1[16];
  96442. var d3z = D1[17];
  96443. var a4x = D2[0];
  96444. var a4y = D2[1];
  96445. var a4z = D2[2];
  96446. var a5x = D2[3];
  96447. var a5y = D2[4];
  96448. var a5z = D2[5];
  96449. var a6x = D2[6];
  96450. var a6y = D2[7];
  96451. var a6z = D2[8];
  96452. var d4x = D2[9];
  96453. var d4y = D2[10];
  96454. var d4z = D2[11];
  96455. var d5x = D2[12];
  96456. var d5y = D2[13];
  96457. var d5z = D2[14];
  96458. var d6x = D2[15];
  96459. var d6y = D2[16];
  96460. var d6z = D2[17];
  96461. var a7x = a1y * a4z - a1z * a4y;
  96462. var a7y = a1z * a4x - a1x * a4z;
  96463. var a7z = a1x * a4y - a1y * a4x;
  96464. var a8x = a1y * a5z - a1z * a5y;
  96465. var a8y = a1z * a5x - a1x * a5z;
  96466. var a8z = a1x * a5y - a1y * a5x;
  96467. var a9x = a1y * a6z - a1z * a6y;
  96468. var a9y = a1z * a6x - a1x * a6z;
  96469. var a9z = a1x * a6y - a1y * a6x;
  96470. var aax = a2y * a4z - a2z * a4y;
  96471. var aay = a2z * a4x - a2x * a4z;
  96472. var aaz = a2x * a4y - a2y * a4x;
  96473. var abx = a2y * a5z - a2z * a5y;
  96474. var aby = a2z * a5x - a2x * a5z;
  96475. var abz = a2x * a5y - a2y * a5x;
  96476. var acx = a2y * a6z - a2z * a6y;
  96477. var acy = a2z * a6x - a2x * a6z;
  96478. var acz = a2x * a6y - a2y * a6x;
  96479. var adx = a3y * a4z - a3z * a4y;
  96480. var ady = a3z * a4x - a3x * a4z;
  96481. var adz = a3x * a4y - a3y * a4x;
  96482. var aex = a3y * a5z - a3z * a5y;
  96483. var aey = a3z * a5x - a3x * a5z;
  96484. var aez = a3x * a5y - a3y * a5x;
  96485. var afx = a3y * a6z - a3z * a6y;
  96486. var afy = a3z * a6x - a3x * a6z;
  96487. var afz = a3x * a6y - a3y * a6x;
  96488. // right or left flags
  96489. var right1;
  96490. var right2;
  96491. var right3;
  96492. var right4;
  96493. var right5;
  96494. var right6;
  96495. var right7;
  96496. var right8;
  96497. var right9;
  96498. var righta;
  96499. var rightb;
  96500. var rightc;
  96501. var rightd;
  96502. var righte;
  96503. var rightf;
  96504. // overlapping distances
  96505. var overlap1;
  96506. var overlap2;
  96507. var overlap3;
  96508. var overlap4;
  96509. var overlap5;
  96510. var overlap6;
  96511. var overlap7;
  96512. var overlap8;
  96513. var overlap9;
  96514. var overlapa;
  96515. var overlapb;
  96516. var overlapc;
  96517. var overlapd;
  96518. var overlape;
  96519. var overlapf;
  96520. // invalid flags
  96521. var invalid7 = false;
  96522. var invalid8 = false;
  96523. var invalid9 = false;
  96524. var invalida = false;
  96525. var invalidb = false;
  96526. var invalidc = false;
  96527. var invalidd = false;
  96528. var invalide = false;
  96529. var invalidf = false;
  96530. // temporary variables
  96531. var len;
  96532. var len1;
  96533. var len2;
  96534. var dot1;
  96535. var dot2;
  96536. var dot3;
  96537. // try axis 1
  96538. len = a1x * dx + a1y * dy + a1z * dz;
  96539. right1 = len > 0;
  96540. if (!right1) len = -len;
  96541. len1 = w1;
  96542. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  96543. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  96544. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  96545. if (dot1 < 0) dot1 = -dot1;
  96546. if (dot2 < 0) dot2 = -dot2;
  96547. if (dot3 < 0) dot3 = -dot3;
  96548. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  96549. overlap1 = len - len1 - len2;
  96550. if (overlap1 > 0) return;
  96551. // try axis 2
  96552. len = a2x * dx + a2y * dy + a2z * dz;
  96553. right2 = len > 0;
  96554. if (!right2) len = -len;
  96555. len1 = h1;
  96556. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  96557. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  96558. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  96559. if (dot1 < 0) dot1 = -dot1;
  96560. if (dot2 < 0) dot2 = -dot2;
  96561. if (dot3 < 0) dot3 = -dot3;
  96562. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  96563. overlap2 = len - len1 - len2;
  96564. if (overlap2 > 0) return;
  96565. // try axis 3
  96566. len = a3x * dx + a3y * dy + a3z * dz;
  96567. right3 = len > 0;
  96568. if (!right3) len = -len;
  96569. len1 = d1;
  96570. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  96571. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  96572. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  96573. if (dot1 < 0) dot1 = -dot1;
  96574. if (dot2 < 0) dot2 = -dot2;
  96575. if (dot3 < 0) dot3 = -dot3;
  96576. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  96577. overlap3 = len - len1 - len2;
  96578. if (overlap3 > 0) return;
  96579. // try axis 4
  96580. len = a4x * dx + a4y * dy + a4z * dz;
  96581. right4 = len > 0;
  96582. if (!right4) len = -len;
  96583. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  96584. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  96585. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  96586. if (dot1 < 0) dot1 = -dot1;
  96587. if (dot2 < 0) dot2 = -dot2;
  96588. if (dot3 < 0) dot3 = -dot3;
  96589. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  96590. len2 = w2;
  96591. overlap4 = (len - len1 - len2) * 1.0;
  96592. if (overlap4 > 0) return;
  96593. // try axis 5
  96594. len = a5x * dx + a5y * dy + a5z * dz;
  96595. right5 = len > 0;
  96596. if (!right5) len = -len;
  96597. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  96598. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  96599. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  96600. if (dot1 < 0) dot1 = -dot1;
  96601. if (dot2 < 0) dot2 = -dot2;
  96602. if (dot3 < 0) dot3 = -dot3;
  96603. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  96604. len2 = h2;
  96605. overlap5 = (len - len1 - len2) * 1.0;
  96606. if (overlap5 > 0) return;
  96607. // try axis 6
  96608. len = a6x * dx + a6y * dy + a6z * dz;
  96609. right6 = len > 0;
  96610. if (!right6) len = -len;
  96611. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  96612. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  96613. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  96614. if (dot1 < 0) dot1 = -dot1;
  96615. if (dot2 < 0) dot2 = -dot2;
  96616. if (dot3 < 0) dot3 = -dot3;
  96617. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  96618. len2 = d2;
  96619. overlap6 = (len - len1 - len2) * 1.0;
  96620. if (overlap6 > 0) return;
  96621. // try axis 7
  96622. len = a7x * a7x + a7y * a7y + a7z * a7z;
  96623. if (len > 1e-5) {
  96624. len = 1 / OIMO.sqrt(len);
  96625. a7x *= len;
  96626. a7y *= len;
  96627. a7z *= len;
  96628. len = a7x * dx + a7y * dy + a7z * dz;
  96629. right7 = len > 0;
  96630. if (!right7) len = -len;
  96631. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  96632. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  96633. if (dot1 < 0) dot1 = -dot1;
  96634. if (dot2 < 0) dot2 = -dot2;
  96635. len1 = dot1 * h1 + dot2 * d1;
  96636. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  96637. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  96638. if (dot1 < 0) dot1 = -dot1;
  96639. if (dot2 < 0) dot2 = -dot2;
  96640. len2 = dot1 * h2 + dot2 * d2;
  96641. overlap7 = len - len1 - len2;
  96642. if (overlap7 > 0) return;
  96643. } else {
  96644. right7 = false;
  96645. overlap7 = 0;
  96646. invalid7 = true;
  96647. }
  96648. // try axis 8
  96649. len = a8x * a8x + a8y * a8y + a8z * a8z;
  96650. if (len > 1e-5) {
  96651. len = 1 / OIMO.sqrt(len);
  96652. a8x *= len;
  96653. a8y *= len;
  96654. a8z *= len;
  96655. len = a8x * dx + a8y * dy + a8z * dz;
  96656. right8 = len > 0;
  96657. if (!right8) len = -len;
  96658. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  96659. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  96660. if (dot1 < 0) dot1 = -dot1;
  96661. if (dot2 < 0) dot2 = -dot2;
  96662. len1 = dot1 * h1 + dot2 * d1;
  96663. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  96664. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  96665. if (dot1 < 0) dot1 = -dot1;
  96666. if (dot2 < 0) dot2 = -dot2;
  96667. len2 = dot1 * w2 + dot2 * d2;
  96668. overlap8 = len - len1 - len2;
  96669. if (overlap8 > 0) return;
  96670. } else {
  96671. right8 = false;
  96672. overlap8 = 0;
  96673. invalid8 = true;
  96674. }
  96675. // try axis 9
  96676. len = a9x * a9x + a9y * a9y + a9z * a9z;
  96677. if (len > 1e-5) {
  96678. len = 1 / OIMO.sqrt(len);
  96679. a9x *= len;
  96680. a9y *= len;
  96681. a9z *= len;
  96682. len = a9x * dx + a9y * dy + a9z * dz;
  96683. right9 = len > 0;
  96684. if (!right9) len = -len;
  96685. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  96686. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  96687. if (dot1 < 0) dot1 = -dot1;
  96688. if (dot2 < 0) dot2 = -dot2;
  96689. len1 = dot1 * h1 + dot2 * d1;
  96690. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  96691. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  96692. if (dot1 < 0) dot1 = -dot1;
  96693. if (dot2 < 0) dot2 = -dot2;
  96694. len2 = dot1 * w2 + dot2 * h2;
  96695. overlap9 = len - len1 - len2;
  96696. if (overlap9 > 0) return;
  96697. } else {
  96698. right9 = false;
  96699. overlap9 = 0;
  96700. invalid9 = true;
  96701. }
  96702. // try axis 10
  96703. len = aax * aax + aay * aay + aaz * aaz;
  96704. if (len > 1e-5) {
  96705. len = 1 / OIMO.sqrt(len);
  96706. aax *= len;
  96707. aay *= len;
  96708. aaz *= len;
  96709. len = aax * dx + aay * dy + aaz * dz;
  96710. righta = len > 0;
  96711. if (!righta) len = -len;
  96712. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  96713. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  96714. if (dot1 < 0) dot1 = -dot1;
  96715. if (dot2 < 0) dot2 = -dot2;
  96716. len1 = dot1 * w1 + dot2 * d1;
  96717. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  96718. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  96719. if (dot1 < 0) dot1 = -dot1;
  96720. if (dot2 < 0) dot2 = -dot2;
  96721. len2 = dot1 * h2 + dot2 * d2;
  96722. overlapa = len - len1 - len2;
  96723. if (overlapa > 0) return;
  96724. } else {
  96725. righta = false;
  96726. overlapa = 0;
  96727. invalida = true;
  96728. }
  96729. // try axis 11
  96730. len = abx * abx + aby * aby + abz * abz;
  96731. if (len > 1e-5) {
  96732. len = 1 / OIMO.sqrt(len);
  96733. abx *= len;
  96734. aby *= len;
  96735. abz *= len;
  96736. len = abx * dx + aby * dy + abz * dz;
  96737. rightb = len > 0;
  96738. if (!rightb) len = -len;
  96739. dot1 = abx * a1x + aby * a1y + abz * a1z;
  96740. dot2 = abx * a3x + aby * a3y + abz * a3z;
  96741. if (dot1 < 0) dot1 = -dot1;
  96742. if (dot2 < 0) dot2 = -dot2;
  96743. len1 = dot1 * w1 + dot2 * d1;
  96744. dot1 = abx * a4x + aby * a4y + abz * a4z;
  96745. dot2 = abx * a6x + aby * a6y + abz * a6z;
  96746. if (dot1 < 0) dot1 = -dot1;
  96747. if (dot2 < 0) dot2 = -dot2;
  96748. len2 = dot1 * w2 + dot2 * d2;
  96749. overlapb = len - len1 - len2;
  96750. if (overlapb > 0) return;
  96751. } else {
  96752. rightb = false;
  96753. overlapb = 0;
  96754. invalidb = true;
  96755. }
  96756. // try axis 12
  96757. len = acx * acx + acy * acy + acz * acz;
  96758. if (len > 1e-5) {
  96759. len = 1 / OIMO.sqrt(len);
  96760. acx *= len;
  96761. acy *= len;
  96762. acz *= len;
  96763. len = acx * dx + acy * dy + acz * dz;
  96764. rightc = len > 0;
  96765. if (!rightc) len = -len;
  96766. dot1 = acx * a1x + acy * a1y + acz * a1z;
  96767. dot2 = acx * a3x + acy * a3y + acz * a3z;
  96768. if (dot1 < 0) dot1 = -dot1;
  96769. if (dot2 < 0) dot2 = -dot2;
  96770. len1 = dot1 * w1 + dot2 * d1;
  96771. dot1 = acx * a4x + acy * a4y + acz * a4z;
  96772. dot2 = acx * a5x + acy * a5y + acz * a5z;
  96773. if (dot1 < 0) dot1 = -dot1;
  96774. if (dot2 < 0) dot2 = -dot2;
  96775. len2 = dot1 * w2 + dot2 * h2;
  96776. overlapc = len - len1 - len2;
  96777. if (overlapc > 0) return;
  96778. } else {
  96779. rightc = false;
  96780. overlapc = 0;
  96781. invalidc = true;
  96782. }
  96783. // try axis 13
  96784. len = adx * adx + ady * ady + adz * adz;
  96785. if (len > 1e-5) {
  96786. len = 1 / OIMO.sqrt(len);
  96787. adx *= len;
  96788. ady *= len;
  96789. adz *= len;
  96790. len = adx * dx + ady * dy + adz * dz;
  96791. rightd = len > 0;
  96792. if (!rightd) len = -len;
  96793. dot1 = adx * a1x + ady * a1y + adz * a1z;
  96794. dot2 = adx * a2x + ady * a2y + adz * a2z;
  96795. if (dot1 < 0) dot1 = -dot1;
  96796. if (dot2 < 0) dot2 = -dot2;
  96797. len1 = dot1 * w1 + dot2 * h1;
  96798. dot1 = adx * a5x + ady * a5y + adz * a5z;
  96799. dot2 = adx * a6x + ady * a6y + adz * a6z;
  96800. if (dot1 < 0) dot1 = -dot1;
  96801. if (dot2 < 0) dot2 = -dot2;
  96802. len2 = dot1 * h2 + dot2 * d2;
  96803. overlapd = len - len1 - len2;
  96804. if (overlapd > 0) return;
  96805. } else {
  96806. rightd = false;
  96807. overlapd = 0;
  96808. invalidd = true;
  96809. }
  96810. // try axis 14
  96811. len = aex * aex + aey * aey + aez * aez;
  96812. if (len > 1e-5) {
  96813. len = 1 / OIMO.sqrt(len);
  96814. aex *= len;
  96815. aey *= len;
  96816. aez *= len;
  96817. len = aex * dx + aey * dy + aez * dz;
  96818. righte = len > 0;
  96819. if (!righte) len = -len;
  96820. dot1 = aex * a1x + aey * a1y + aez * a1z;
  96821. dot2 = aex * a2x + aey * a2y + aez * a2z;
  96822. if (dot1 < 0) dot1 = -dot1;
  96823. if (dot2 < 0) dot2 = -dot2;
  96824. len1 = dot1 * w1 + dot2 * h1;
  96825. dot1 = aex * a4x + aey * a4y + aez * a4z;
  96826. dot2 = aex * a6x + aey * a6y + aez * a6z;
  96827. if (dot1 < 0) dot1 = -dot1;
  96828. if (dot2 < 0) dot2 = -dot2;
  96829. len2 = dot1 * w2 + dot2 * d2;
  96830. overlape = len - len1 - len2;
  96831. if (overlape > 0) return;
  96832. } else {
  96833. righte = false;
  96834. overlape = 0;
  96835. invalide = true;
  96836. }
  96837. // try axis 15
  96838. len = afx * afx + afy * afy + afz * afz;
  96839. if (len > 1e-5) {
  96840. len = 1 / OIMO.sqrt(len);
  96841. afx *= len;
  96842. afy *= len;
  96843. afz *= len;
  96844. len = afx * dx + afy * dy + afz * dz;
  96845. rightf = len > 0;
  96846. if (!rightf) len = -len;
  96847. dot1 = afx * a1x + afy * a1y + afz * a1z;
  96848. dot2 = afx * a2x + afy * a2y + afz * a2z;
  96849. if (dot1 < 0) dot1 = -dot1;
  96850. if (dot2 < 0) dot2 = -dot2;
  96851. len1 = dot1 * w1 + dot2 * h1;
  96852. dot1 = afx * a4x + afy * a4y + afz * a4z;
  96853. dot2 = afx * a5x + afy * a5y + afz * a5z;
  96854. if (dot1 < 0) dot1 = -dot1;
  96855. if (dot2 < 0) dot2 = -dot2;
  96856. len2 = dot1 * w2 + dot2 * h2;
  96857. overlapf = len - len1 - len2;
  96858. if (overlapf > 0) return;
  96859. } else {
  96860. rightf = false;
  96861. overlapf = 0;
  96862. invalidf = true;
  96863. }
  96864. // boxes are overlapping
  96865. var depth = overlap1;
  96866. var depth2 = overlap1;
  96867. var minIndex = 0;
  96868. var right = right1;
  96869. if (overlap2 > depth2) {
  96870. depth = overlap2;
  96871. depth2 = overlap2;
  96872. minIndex = 1;
  96873. right = right2;
  96874. }
  96875. if (overlap3 > depth2) {
  96876. depth = overlap3;
  96877. depth2 = overlap3;
  96878. minIndex = 2;
  96879. right = right3;
  96880. }
  96881. if (overlap4 > depth2) {
  96882. depth = overlap4;
  96883. depth2 = overlap4;
  96884. minIndex = 3;
  96885. right = right4;
  96886. }
  96887. if (overlap5 > depth2) {
  96888. depth = overlap5;
  96889. depth2 = overlap5;
  96890. minIndex = 4;
  96891. right = right5;
  96892. }
  96893. if (overlap6 > depth2) {
  96894. depth = overlap6;
  96895. depth2 = overlap6;
  96896. minIndex = 5;
  96897. right = right6;
  96898. }
  96899. if (overlap7 - 0.01 > depth2 && !invalid7) {
  96900. depth = overlap7;
  96901. depth2 = overlap7 - 0.01;
  96902. minIndex = 6;
  96903. right = right7;
  96904. }
  96905. if (overlap8 - 0.01 > depth2 && !invalid8) {
  96906. depth = overlap8;
  96907. depth2 = overlap8 - 0.01;
  96908. minIndex = 7;
  96909. right = right8;
  96910. }
  96911. if (overlap9 - 0.01 > depth2 && !invalid9) {
  96912. depth = overlap9;
  96913. depth2 = overlap9 - 0.01;
  96914. minIndex = 8;
  96915. right = right9;
  96916. }
  96917. if (overlapa - 0.01 > depth2 && !invalida) {
  96918. depth = overlapa;
  96919. depth2 = overlapa - 0.01;
  96920. minIndex = 9;
  96921. right = righta;
  96922. }
  96923. if (overlapb - 0.01 > depth2 && !invalidb) {
  96924. depth = overlapb;
  96925. depth2 = overlapb - 0.01;
  96926. minIndex = 10;
  96927. right = rightb;
  96928. }
  96929. if (overlapc - 0.01 > depth2 && !invalidc) {
  96930. depth = overlapc;
  96931. depth2 = overlapc - 0.01;
  96932. minIndex = 11;
  96933. right = rightc;
  96934. }
  96935. if (overlapd - 0.01 > depth2 && !invalidd) {
  96936. depth = overlapd;
  96937. depth2 = overlapd - 0.01;
  96938. minIndex = 12;
  96939. right = rightd;
  96940. }
  96941. if (overlape - 0.01 > depth2 && !invalide) {
  96942. depth = overlape;
  96943. depth2 = overlape - 0.01;
  96944. minIndex = 13;
  96945. right = righte;
  96946. }
  96947. if (overlapf - 0.01 > depth2 && !invalidf) {
  96948. depth = overlapf;
  96949. minIndex = 14;
  96950. right = rightf;
  96951. }
  96952. // normal
  96953. var nx = 0;
  96954. var ny = 0;
  96955. var nz = 0;
  96956. // edge line or face side normal
  96957. var n1x = 0;
  96958. var n1y = 0;
  96959. var n1z = 0;
  96960. var n2x = 0;
  96961. var n2y = 0;
  96962. var n2z = 0;
  96963. // center of current face
  96964. var cx = 0;
  96965. var cy = 0;
  96966. var cz = 0;
  96967. // face side
  96968. var s1x = 0;
  96969. var s1y = 0;
  96970. var s1z = 0;
  96971. var s2x = 0;
  96972. var s2y = 0;
  96973. var s2z = 0;
  96974. // swap b1 b2
  96975. var swap = false;
  96976. //_______________________________________
  96977. if (minIndex == 0) {// b1.x * b2
  96978. if (right) {
  96979. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  96980. nx = a1x; ny = a1y; nz = a1z;
  96981. } else {
  96982. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  96983. nx = -a1x; ny = -a1y; nz = -a1z;
  96984. }
  96985. s1x = d2x; s1y = d2y; s1z = d2z;
  96986. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  96987. s2x = d3x; s2y = d3y; s2z = d3z;
  96988. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  96989. }
  96990. else if (minIndex == 1) {// b1.y * b2
  96991. if (right) {
  96992. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  96993. nx = a2x; ny = a2y; nz = a2z;
  96994. } else {
  96995. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  96996. nx = -a2x; ny = -a2y; nz = -a2z;
  96997. }
  96998. s1x = d1x; s1y = d1y; s1z = d1z;
  96999. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  97000. s2x = d3x; s2y = d3y; s2z = d3z;
  97001. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  97002. }
  97003. else if (minIndex == 2) {// b1.z * b2
  97004. if (right) {
  97005. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  97006. nx = a3x; ny = a3y; nz = a3z;
  97007. } else {
  97008. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  97009. nx = -a3x; ny = -a3y; nz = -a3z;
  97010. }
  97011. s1x = d1x; s1y = d1y; s1z = d1z;
  97012. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  97013. s2x = d2x; s2y = d2y; s2z = d2z;
  97014. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  97015. }
  97016. else if (minIndex == 3) {// b2.x * b1
  97017. swap = true;
  97018. if (!right) {
  97019. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  97020. nx = a4x; ny = a4y; nz = a4z;
  97021. } else {
  97022. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  97023. nx = -a4x; ny = -a4y; nz = -a4z;
  97024. }
  97025. s1x = d5x; s1y = d5y; s1z = d5z;
  97026. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  97027. s2x = d6x; s2y = d6y; s2z = d6z;
  97028. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  97029. }
  97030. else if (minIndex == 4) {// b2.y * b1
  97031. swap = true;
  97032. if (!right) {
  97033. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  97034. nx = a5x; ny = a5y; nz = a5z;
  97035. } else {
  97036. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  97037. nx = -a5x; ny = -a5y; nz = -a5z;
  97038. }
  97039. s1x = d4x; s1y = d4y; s1z = d4z;
  97040. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  97041. s2x = d6x; s2y = d6y; s2z = d6z;
  97042. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  97043. }
  97044. else if (minIndex == 5) {// b2.z * b1
  97045. swap = true;
  97046. if (!right) {
  97047. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  97048. nx = a6x; ny = a6y; nz = a6z;
  97049. } else {
  97050. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  97051. nx = -a6x; ny = -a6y; nz = -a6z;
  97052. }
  97053. s1x = d4x; s1y = d4y; s1z = d4z;
  97054. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  97055. s2x = d5x; s2y = d5y; s2z = d5z;
  97056. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  97057. }
  97058. else if (minIndex == 6) {// b1.x * b2.x
  97059. nx = a7x; ny = a7y; nz = a7z;
  97060. n1x = a1x; n1y = a1y; n1z = a1z;
  97061. n2x = a4x; n2y = a4y; n2z = a4z;
  97062. }
  97063. else if (minIndex == 7) {// b1.x * b2.y
  97064. nx = a8x; ny = a8y; nz = a8z;
  97065. n1x = a1x; n1y = a1y; n1z = a1z;
  97066. n2x = a5x; n2y = a5y; n2z = a5z;
  97067. }
  97068. else if (minIndex == 8) {// b1.x * b2.z
  97069. nx = a9x; ny = a9y; nz = a9z;
  97070. n1x = a1x; n1y = a1y; n1z = a1z;
  97071. n2x = a6x; n2y = a6y; n2z = a6z;
  97072. }
  97073. else if (minIndex == 9) {// b1.y * b2.x
  97074. nx = aax; ny = aay; nz = aaz;
  97075. n1x = a2x; n1y = a2y; n1z = a2z;
  97076. n2x = a4x; n2y = a4y; n2z = a4z
  97077. }
  97078. else if (minIndex == 10) {// b1.y * b2.y
  97079. nx = abx; ny = aby; nz = abz;
  97080. n1x = a2x; n1y = a2y; n1z = a2z;
  97081. n2x = a5x; n2y = a5y; n2z = a5z;
  97082. }
  97083. else if (minIndex == 11) {// b1.y * b2.z
  97084. nx = acx; ny = acy; nz = acz;
  97085. n1x = a2x; n1y = a2y; n1z = a2z;
  97086. n2x = a6x; n2y = a6y; n2z = a6z;
  97087. }
  97088. else if (minIndex == 12) {// b1.z * b2.x
  97089. nx = adx; ny = ady; nz = adz;
  97090. n1x = a3x; n1y = a3y; n1z = a3z;
  97091. n2x = a4x; n2y = a4y; n2z = a4z;
  97092. }
  97093. else if (minIndex == 13) {// b1.z * b2.y
  97094. nx = aex; ny = aey; nz = aez;
  97095. n1x = a3x; n1y = a3y; n1z = a3z;
  97096. n2x = a5x; n2y = a5y; n2z = a5z;
  97097. }
  97098. else if (minIndex == 14) {// b1.z * b2.z
  97099. nx = afx; ny = afy; nz = afz;
  97100. n1x = a3x; n1y = a3y; n1z = a3z;
  97101. n2x = a6x; n2y = a6y; n2z = a6z;
  97102. }
  97103. //__________________________________________
  97104. var v;
  97105. if (minIndex > 5) {
  97106. if (!right) {
  97107. nx = -nx; ny = -ny; nz = -nz;
  97108. }
  97109. var distance;
  97110. var maxDistance;
  97111. var vx;
  97112. var vy;
  97113. var vz;
  97114. var v1x;
  97115. var v1y;
  97116. var v1z;
  97117. var v2x;
  97118. var v2y;
  97119. var v2z;
  97120. //vertex1;
  97121. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  97122. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  97123. //vertex2;
  97124. vx = V1[3]; vy = V1[4]; vz = V1[5];
  97125. distance = nx * vx + ny * vy + nz * vz;
  97126. if (distance > maxDistance) {
  97127. maxDistance = distance;
  97128. v1x = vx; v1y = vy; v1z = vz;
  97129. }
  97130. //vertex3;
  97131. vx = V1[6]; vy = V1[7]; vz = V1[8];
  97132. distance = nx * vx + ny * vy + nz * vz;
  97133. if (distance > maxDistance) {
  97134. maxDistance = distance;
  97135. v1x = vx; v1y = vy; v1z = vz;
  97136. }
  97137. //vertex4;
  97138. vx = V1[9]; vy = V1[10]; vz = V1[11];
  97139. distance = nx * vx + ny * vy + nz * vz;
  97140. if (distance > maxDistance) {
  97141. maxDistance = distance;
  97142. v1x = vx; v1y = vy; v1z = vz;
  97143. }
  97144. //vertex5;
  97145. vx = V1[12]; vy = V1[13]; vz = V1[14];
  97146. distance = nx * vx + ny * vy + nz * vz;
  97147. if (distance > maxDistance) {
  97148. maxDistance = distance;
  97149. v1x = vx; v1y = vy; v1z = vz;
  97150. }
  97151. //vertex6;
  97152. vx = V1[15]; vy = V1[16]; vz = V1[17];
  97153. distance = nx * vx + ny * vy + nz * vz;
  97154. if (distance > maxDistance) {
  97155. maxDistance = distance;
  97156. v1x = vx; v1y = vy; v1z = vz;
  97157. }
  97158. //vertex7;
  97159. vx = V1[18]; vy = V1[19]; vz = V1[20];
  97160. distance = nx * vx + ny * vy + nz * vz;
  97161. if (distance > maxDistance) {
  97162. maxDistance = distance;
  97163. v1x = vx; v1y = vy; v1z = vz;
  97164. }
  97165. //vertex8;
  97166. vx = V1[21]; vy = V1[22]; vz = V1[23];
  97167. distance = nx * vx + ny * vy + nz * vz;
  97168. if (distance > maxDistance) {
  97169. maxDistance = distance;
  97170. v1x = vx; v1y = vy; v1z = vz;
  97171. }
  97172. //vertex1;
  97173. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  97174. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  97175. //vertex2;
  97176. vx = V2[3]; vy = V2[4]; vz = V2[5];
  97177. distance = nx * vx + ny * vy + nz * vz;
  97178. if (distance < maxDistance) {
  97179. maxDistance = distance;
  97180. v2x = vx; v2y = vy; v2z = vz;
  97181. }
  97182. //vertex3;
  97183. vx = V2[6]; vy = V2[7]; vz = V2[8];
  97184. distance = nx * vx + ny * vy + nz * vz;
  97185. if (distance < maxDistance) {
  97186. maxDistance = distance;
  97187. v2x = vx; v2y = vy; v2z = vz;
  97188. }
  97189. //vertex4;
  97190. vx = V2[9]; vy = V2[10]; vz = V2[11];
  97191. distance = nx * vx + ny * vy + nz * vz;
  97192. if (distance < maxDistance) {
  97193. maxDistance = distance;
  97194. v2x = vx; v2y = vy; v2z = vz;
  97195. }
  97196. //vertex5;
  97197. vx = V2[12]; vy = V2[13]; vz = V2[14];
  97198. distance = nx * vx + ny * vy + nz * vz;
  97199. if (distance < maxDistance) {
  97200. maxDistance = distance;
  97201. v2x = vx; v2y = vy; v2z = vz;
  97202. }
  97203. //vertex6;
  97204. vx = V2[15]; vy = V2[16]; vz = V2[17];
  97205. distance = nx * vx + ny * vy + nz * vz;
  97206. if (distance < maxDistance) {
  97207. maxDistance = distance;
  97208. v2x = vx; v2y = vy; v2z = vz;
  97209. }
  97210. //vertex7;
  97211. vx = V2[18]; vy = V2[19]; vz = V2[20];
  97212. distance = nx * vx + ny * vy + nz * vz;
  97213. if (distance < maxDistance) {
  97214. maxDistance = distance;
  97215. v2x = vx; v2y = vy; v2z = vz;
  97216. }
  97217. //vertex8;
  97218. vx = V2[21]; vy = V2[22]; vz = V2[23];
  97219. distance = nx * vx + ny * vy + nz * vz;
  97220. if (distance < maxDistance) {
  97221. maxDistance = distance;
  97222. v2x = vx; v2y = vy; v2z = vz;
  97223. }
  97224. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  97225. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  97226. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  97227. 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);
  97228. return;
  97229. }
  97230. // now detect face-face collision...
  97231. // target quad
  97232. var q1x;
  97233. var q1y;
  97234. var q1z;
  97235. var q2x;
  97236. var q2y;
  97237. var q2z;
  97238. var q3x;
  97239. var q3y;
  97240. var q3z;
  97241. var q4x;
  97242. var q4y;
  97243. var q4z;
  97244. // search support face and vertex
  97245. var minDot = 1;
  97246. var dot = 0;
  97247. var minDotIndex = 0;
  97248. if (swap) {
  97249. dot = a1x * nx + a1y * ny + a1z * nz;
  97250. if (dot < minDot) {
  97251. minDot = dot;
  97252. minDotIndex = 0;
  97253. }
  97254. if (-dot < minDot) {
  97255. minDot = -dot;
  97256. minDotIndex = 1;
  97257. }
  97258. dot = a2x * nx + a2y * ny + a2z * nz;
  97259. if (dot < minDot) {
  97260. minDot = dot;
  97261. minDotIndex = 2;
  97262. }
  97263. if (-dot < minDot) {
  97264. minDot = -dot;
  97265. minDotIndex = 3;
  97266. }
  97267. dot = a3x * nx + a3y * ny + a3z * nz;
  97268. if (dot < minDot) {
  97269. minDot = dot;
  97270. minDotIndex = 4;
  97271. }
  97272. if (-dot < minDot) {
  97273. minDot = -dot;
  97274. minDotIndex = 5;
  97275. }
  97276. if (minDotIndex == 0) {// x+ face
  97277. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  97278. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  97279. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  97280. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  97281. }
  97282. else if (minDotIndex == 1) {// x- face
  97283. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  97284. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  97285. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  97286. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  97287. }
  97288. else if (minDotIndex == 2) {// y+ face
  97289. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  97290. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  97291. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  97292. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  97293. }
  97294. else if (minDotIndex == 3) {// y- face
  97295. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  97296. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  97297. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  97298. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  97299. }
  97300. else if (minDotIndex == 4) {// z+ face
  97301. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  97302. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  97303. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  97304. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  97305. }
  97306. else if (minDotIndex == 5) {// z- face
  97307. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  97308. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  97309. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  97310. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  97311. }
  97312. } else {
  97313. dot = a4x * nx + a4y * ny + a4z * nz;
  97314. if (dot < minDot) {
  97315. minDot = dot;
  97316. minDotIndex = 0;
  97317. }
  97318. if (-dot < minDot) {
  97319. minDot = -dot;
  97320. minDotIndex = 1;
  97321. }
  97322. dot = a5x * nx + a5y * ny + a5z * nz;
  97323. if (dot < minDot) {
  97324. minDot = dot;
  97325. minDotIndex = 2;
  97326. }
  97327. if (-dot < minDot) {
  97328. minDot = -dot;
  97329. minDotIndex = 3;
  97330. }
  97331. dot = a6x * nx + a6y * ny + a6z * nz;
  97332. if (dot < minDot) {
  97333. minDot = dot;
  97334. minDotIndex = 4;
  97335. }
  97336. if (-dot < minDot) {
  97337. minDot = -dot;
  97338. minDotIndex = 5;
  97339. }
  97340. //______________________________________________________
  97341. if (minDotIndex == 0) {// x+ face
  97342. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  97343. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  97344. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  97345. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  97346. }
  97347. else if (minDotIndex == 1) {// x- face
  97348. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  97349. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  97350. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  97351. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  97352. }
  97353. else if (minDotIndex == 2) {// y+ face
  97354. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  97355. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  97356. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  97357. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  97358. }
  97359. else if (minDotIndex == 3) {// y- face
  97360. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  97361. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  97362. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  97363. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  97364. }
  97365. else if (minDotIndex == 4) {// z+ face
  97366. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  97367. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  97368. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  97369. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  97370. }
  97371. else if (minDotIndex == 5) {// z- face
  97372. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  97373. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  97374. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  97375. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  97376. }
  97377. }
  97378. // clip vertices
  97379. var numClipVertices;
  97380. var numAddedClipVertices;
  97381. var index;
  97382. var x1;
  97383. var y1;
  97384. var z1;
  97385. var x2;
  97386. var y2;
  97387. var z2;
  97388. this.clipVertices1[0] = q1x;
  97389. this.clipVertices1[1] = q1y;
  97390. this.clipVertices1[2] = q1z;
  97391. this.clipVertices1[3] = q2x;
  97392. this.clipVertices1[4] = q2y;
  97393. this.clipVertices1[5] = q2z;
  97394. this.clipVertices1[6] = q3x;
  97395. this.clipVertices1[7] = q3y;
  97396. this.clipVertices1[8] = q3z;
  97397. this.clipVertices1[9] = q4x;
  97398. this.clipVertices1[10] = q4y;
  97399. this.clipVertices1[11] = q4z;
  97400. numAddedClipVertices = 0;
  97401. x1 = this.clipVertices1[9];
  97402. y1 = this.clipVertices1[10];
  97403. z1 = this.clipVertices1[11];
  97404. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  97405. //var i = 4;
  97406. //while(i--){
  97407. for (var i = 0; i < 4; i++) {
  97408. index = i * 3;
  97409. x2 = this.clipVertices1[index];
  97410. y2 = this.clipVertices1[index + 1];
  97411. z2 = this.clipVertices1[index + 2];
  97412. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  97413. if (dot1 > 0) {
  97414. if (dot2 > 0) {
  97415. index = numAddedClipVertices * 3;
  97416. numAddedClipVertices++;
  97417. this.clipVertices2[index] = x2;
  97418. this.clipVertices2[index + 1] = y2;
  97419. this.clipVertices2[index + 2] = z2;
  97420. } else {
  97421. index = numAddedClipVertices * 3;
  97422. numAddedClipVertices++;
  97423. t = dot1 / (dot1 - dot2);
  97424. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  97425. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  97426. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  97427. }
  97428. } else {
  97429. if (dot2 > 0) {
  97430. index = numAddedClipVertices * 3;
  97431. numAddedClipVertices++;
  97432. t = dot1 / (dot1 - dot2);
  97433. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  97434. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  97435. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  97436. index = numAddedClipVertices * 3;
  97437. numAddedClipVertices++;
  97438. this.clipVertices2[index] = x2;
  97439. this.clipVertices2[index + 1] = y2;
  97440. this.clipVertices2[index + 2] = z2;
  97441. }
  97442. }
  97443. x1 = x2;
  97444. y1 = y2;
  97445. z1 = z2;
  97446. dot1 = dot2;
  97447. }
  97448. numClipVertices = numAddedClipVertices;
  97449. if (numClipVertices == 0) return;
  97450. numAddedClipVertices = 0;
  97451. index = (numClipVertices - 1) * 3;
  97452. x1 = this.clipVertices2[index];
  97453. y1 = this.clipVertices2[index + 1];
  97454. z1 = this.clipVertices2[index + 2];
  97455. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  97456. //i = numClipVertices;
  97457. //while(i--){
  97458. for (i = 0; i < numClipVertices; i++) {
  97459. index = i * 3;
  97460. x2 = this.clipVertices2[index];
  97461. y2 = this.clipVertices2[index + 1];
  97462. z2 = this.clipVertices2[index + 2];
  97463. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  97464. if (dot1 > 0) {
  97465. if (dot2 > 0) {
  97466. index = numAddedClipVertices * 3;
  97467. numAddedClipVertices++;
  97468. this.clipVertices1[index] = x2;
  97469. this.clipVertices1[index + 1] = y2;
  97470. this.clipVertices1[index + 2] = z2;
  97471. } else {
  97472. index = numAddedClipVertices * 3;
  97473. numAddedClipVertices++;
  97474. t = dot1 / (dot1 - dot2);
  97475. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  97476. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  97477. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  97478. }
  97479. } else {
  97480. if (dot2 > 0) {
  97481. index = numAddedClipVertices * 3;
  97482. numAddedClipVertices++;
  97483. t = dot1 / (dot1 - dot2);
  97484. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  97485. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  97486. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  97487. index = numAddedClipVertices * 3;
  97488. numAddedClipVertices++;
  97489. this.clipVertices1[index] = x2;
  97490. this.clipVertices1[index + 1] = y2;
  97491. this.clipVertices1[index + 2] = z2;
  97492. }
  97493. }
  97494. x1 = x2;
  97495. y1 = y2;
  97496. z1 = z2;
  97497. dot1 = dot2;
  97498. }
  97499. numClipVertices = numAddedClipVertices;
  97500. if (numClipVertices == 0) return;
  97501. numAddedClipVertices = 0;
  97502. index = (numClipVertices - 1) * 3;
  97503. x1 = this.clipVertices1[index];
  97504. y1 = this.clipVertices1[index + 1];
  97505. z1 = this.clipVertices1[index + 2];
  97506. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  97507. //i = numClipVertices;
  97508. //while(i--){
  97509. for (i = 0; i < numClipVertices; i++) {
  97510. index = i * 3;
  97511. x2 = this.clipVertices1[index];
  97512. y2 = this.clipVertices1[index + 1];
  97513. z2 = this.clipVertices1[index + 2];
  97514. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  97515. if (dot1 > 0) {
  97516. if (dot2 > 0) {
  97517. index = numAddedClipVertices * 3;
  97518. numAddedClipVertices++;
  97519. this.clipVertices2[index] = x2;
  97520. this.clipVertices2[index + 1] = y2;
  97521. this.clipVertices2[index + 2] = z2;
  97522. } else {
  97523. index = numAddedClipVertices * 3;
  97524. numAddedClipVertices++;
  97525. t = dot1 / (dot1 - dot2);
  97526. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  97527. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  97528. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  97529. }
  97530. } else {
  97531. if (dot2 > 0) {
  97532. index = numAddedClipVertices * 3;
  97533. numAddedClipVertices++;
  97534. t = dot1 / (dot1 - dot2);
  97535. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  97536. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  97537. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  97538. index = numAddedClipVertices * 3;
  97539. numAddedClipVertices++;
  97540. this.clipVertices2[index] = x2;
  97541. this.clipVertices2[index + 1] = y2;
  97542. this.clipVertices2[index + 2] = z2;
  97543. }
  97544. }
  97545. x1 = x2;
  97546. y1 = y2;
  97547. z1 = z2;
  97548. dot1 = dot2;
  97549. }
  97550. numClipVertices = numAddedClipVertices;
  97551. if (numClipVertices == 0) return;
  97552. numAddedClipVertices = 0;
  97553. index = (numClipVertices - 1) * 3;
  97554. x1 = this.clipVertices2[index];
  97555. y1 = this.clipVertices2[index + 1];
  97556. z1 = this.clipVertices2[index + 2];
  97557. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  97558. //i = numClipVertices;
  97559. //while(i--){
  97560. for (i = 0; i < numClipVertices; i++) {
  97561. index = i * 3;
  97562. x2 = this.clipVertices2[index];
  97563. y2 = this.clipVertices2[index + 1];
  97564. z2 = this.clipVertices2[index + 2];
  97565. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  97566. if (dot1 > 0) {
  97567. if (dot2 > 0) {
  97568. index = numAddedClipVertices * 3;
  97569. numAddedClipVertices++;
  97570. this.clipVertices1[index] = x2;
  97571. this.clipVertices1[index + 1] = y2;
  97572. this.clipVertices1[index + 2] = z2;
  97573. } else {
  97574. index = numAddedClipVertices * 3;
  97575. numAddedClipVertices++;
  97576. t = dot1 / (dot1 - dot2);
  97577. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  97578. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  97579. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  97580. }
  97581. } else {
  97582. if (dot2 > 0) {
  97583. index = numAddedClipVertices * 3;
  97584. numAddedClipVertices++;
  97585. t = dot1 / (dot1 - dot2);
  97586. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  97587. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  97588. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  97589. index = numAddedClipVertices * 3;
  97590. numAddedClipVertices++;
  97591. this.clipVertices1[index] = x2;
  97592. this.clipVertices1[index + 1] = y2;
  97593. this.clipVertices1[index + 2] = z2;
  97594. }
  97595. }
  97596. x1 = x2;
  97597. y1 = y2;
  97598. z1 = z2;
  97599. dot1 = dot2;
  97600. }
  97601. numClipVertices = numAddedClipVertices;
  97602. if (swap) {
  97603. var tb = b1;
  97604. b1 = b2;
  97605. b2 = tb;
  97606. }
  97607. if (numClipVertices == 0) return;
  97608. var flipped = b1 != shape1;
  97609. if (numClipVertices > 4) {
  97610. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  97611. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  97612. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  97613. n1x = q1x - x1;
  97614. n1y = q1y - y1;
  97615. n1z = q1z - z1;
  97616. n2x = q2x - x1;
  97617. n2y = q2y - y1;
  97618. n2z = q2z - z1;
  97619. var index1 = 0;
  97620. var index2 = 0;
  97621. var index3 = 0;
  97622. var index4 = 0;
  97623. var maxDot = -this.INF;
  97624. minDot = this.INF;
  97625. //i = numClipVertices;
  97626. //while(i--){
  97627. for (i = 0; i < numClipVertices; i++) {
  97628. this.used[i] = false;
  97629. index = i * 3;
  97630. x1 = this.clipVertices1[index];
  97631. y1 = this.clipVertices1[index + 1];
  97632. z1 = this.clipVertices1[index + 2];
  97633. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  97634. if (dot < minDot) {
  97635. minDot = dot;
  97636. index1 = i;
  97637. }
  97638. if (dot > maxDot) {
  97639. maxDot = dot;
  97640. index3 = i;
  97641. }
  97642. }
  97643. this.used[index1] = true;
  97644. this.used[index3] = true;
  97645. maxDot = -this.INF;
  97646. minDot = this.INF;
  97647. //i = numClipVertices;
  97648. //while(i--){
  97649. for (i = 0; i < numClipVertices; i++) {
  97650. if (this.used[i]) continue;
  97651. index = i * 3;
  97652. x1 = this.clipVertices1[index];
  97653. y1 = this.clipVertices1[index + 1];
  97654. z1 = this.clipVertices1[index + 2];
  97655. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  97656. if (dot < minDot) {
  97657. minDot = dot;
  97658. index2 = i;
  97659. }
  97660. if (dot > maxDot) {
  97661. maxDot = dot;
  97662. index4 = i;
  97663. }
  97664. }
  97665. index = index1 * 3;
  97666. x1 = this.clipVertices1[index];
  97667. y1 = this.clipVertices1[index + 1];
  97668. z1 = this.clipVertices1[index + 2];
  97669. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  97670. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  97671. index = index2 * 3;
  97672. x1 = this.clipVertices1[index];
  97673. y1 = this.clipVertices1[index + 1];
  97674. z1 = this.clipVertices1[index + 2];
  97675. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  97676. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  97677. index = index3 * 3;
  97678. x1 = this.clipVertices1[index];
  97679. y1 = this.clipVertices1[index + 1];
  97680. z1 = this.clipVertices1[index + 2];
  97681. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  97682. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  97683. index = index4 * 3;
  97684. x1 = this.clipVertices1[index];
  97685. y1 = this.clipVertices1[index + 1];
  97686. z1 = this.clipVertices1[index + 2];
  97687. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  97688. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  97689. } else {
  97690. //i = numClipVertices;
  97691. //while(i--){
  97692. for (i = 0; i < numClipVertices; i++) {
  97693. index = i * 3;
  97694. x1 = this.clipVertices1[index];
  97695. y1 = this.clipVertices1[index + 1];
  97696. z1 = this.clipVertices1[index + 2];
  97697. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  97698. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  97699. }
  97700. }
  97701. };
  97702. /**
  97703. * A collision detector which detects collisions between sphere and box.
  97704. * @author saharan
  97705. */
  97706. OIMO.SphereBoxCollisionDetector = function (flip) {
  97707. OIMO.CollisionDetector.call(this);
  97708. this.flip = flip;
  97709. };
  97710. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  97711. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  97712. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  97713. var s;
  97714. var b;
  97715. if (this.flip) {
  97716. s = (shape2);
  97717. b = (shape1);
  97718. } else {
  97719. s = (shape1);
  97720. b = (shape2);
  97721. }
  97722. var D = b.dimentions;
  97723. var ps = s.position;
  97724. var psx = ps.x;
  97725. var psy = ps.y;
  97726. var psz = ps.z;
  97727. var pb = b.position;
  97728. var pbx = pb.x;
  97729. var pby = pb.y;
  97730. var pbz = pb.z;
  97731. var rad = s.radius;
  97732. var hw = b.halfWidth;
  97733. var hh = b.halfHeight;
  97734. var hd = b.halfDepth;
  97735. var dx = psx - pbx;
  97736. var dy = psy - pby;
  97737. var dz = psz - pbz;
  97738. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  97739. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  97740. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  97741. var cx;
  97742. var cy;
  97743. var cz;
  97744. var len;
  97745. var invLen;
  97746. var overlap = 0;
  97747. if (sx > hw) {
  97748. sx = hw;
  97749. } else if (sx < -hw) {
  97750. sx = -hw;
  97751. } else {
  97752. overlap = 1;
  97753. }
  97754. if (sy > hh) {
  97755. sy = hh;
  97756. } else if (sy < -hh) {
  97757. sy = -hh;
  97758. } else {
  97759. overlap |= 2;
  97760. }
  97761. if (sz > hd) {
  97762. sz = hd;
  97763. } else if (sz < -hd) {
  97764. sz = -hd;
  97765. } else {
  97766. overlap |= 4;
  97767. }
  97768. if (overlap == 7) {
  97769. // center of sphere is in the box
  97770. if (sx < 0) {
  97771. dx = hw + sx;
  97772. } else {
  97773. dx = hw - sx;
  97774. }
  97775. if (sy < 0) {
  97776. dy = hh + sy;
  97777. } else {
  97778. dy = hh - sy;
  97779. }
  97780. if (sz < 0) {
  97781. dz = hd + sz;
  97782. } else {
  97783. dz = hd - sz;
  97784. }
  97785. if (dx < dy) {
  97786. if (dx < dz) {
  97787. len = dx - hw;
  97788. if (sx < 0) {
  97789. sx = -hw;
  97790. dx = D[0];
  97791. dy = D[1];
  97792. dz = D[2];
  97793. } else {
  97794. sx = hw;
  97795. dx = -D[0];
  97796. dy = -D[1];
  97797. dz = -D[2];
  97798. }
  97799. } else {
  97800. len = dz - hd;
  97801. if (sz < 0) {
  97802. sz = -hd;
  97803. dx = D[6];
  97804. dy = D[7];
  97805. dz = D[8];
  97806. } else {
  97807. sz = hd;
  97808. dx = -D[6];
  97809. dy = -D[7];
  97810. dz = -D[8];
  97811. }
  97812. }
  97813. } else {
  97814. if (dy < dz) {
  97815. len = dy - hh;
  97816. if (sy < 0) {
  97817. sy = -hh;
  97818. dx = D[3];
  97819. dy = D[4];
  97820. dz = D[5];
  97821. } else {
  97822. sy = hh;
  97823. dx = -D[3];
  97824. dy = -D[4];
  97825. dz = -D[5];
  97826. }
  97827. } else {
  97828. len = dz - hd;
  97829. if (sz < 0) {
  97830. sz = -hd;
  97831. dx = D[6];
  97832. dy = D[7];
  97833. dz = D[8];
  97834. } else {
  97835. sz = hd;
  97836. dx = -D[6];
  97837. dy = -D[7];
  97838. dz = -D[8];
  97839. }
  97840. }
  97841. }
  97842. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  97843. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  97844. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  97845. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  97846. } else {
  97847. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  97848. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  97849. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  97850. dx = cx - ps.x;
  97851. dy = cy - ps.y;
  97852. dz = cz - ps.z;
  97853. len = dx * dx + dy * dy + dz * dz;
  97854. if (len > 0 && len < rad * rad) {
  97855. len = OIMO.sqrt(len);
  97856. invLen = 1 / len;
  97857. dx *= invLen;
  97858. dy *= invLen;
  97859. dz *= invLen;
  97860. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  97861. }
  97862. }
  97863. };
  97864. /**
  97865. * A collision detector which detects collisions between two spheres.
  97866. * @author saharan
  97867. */
  97868. OIMO.SphereSphereCollisionDetector = function () {
  97869. OIMO.CollisionDetector.call(this);
  97870. };
  97871. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  97872. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  97873. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  97874. var s1 = shape1;
  97875. var s2 = shape2;
  97876. var p1 = s1.position;
  97877. var p2 = s2.position;
  97878. var dx = p2.x - p1.x;
  97879. var dy = p2.y - p1.y;
  97880. var dz = p2.z - p1.z;
  97881. var len = dx * dx + dy * dy + dz * dz;
  97882. var r1 = s1.radius;
  97883. var r2 = s2.radius;
  97884. var rad = r1 + r2;
  97885. if (len > 0 && len < rad * rad) {
  97886. len = OIMO.sqrt(len);
  97887. var invLen = 1 / len;
  97888. dx *= invLen;
  97889. dy *= invLen;
  97890. dz *= invLen;
  97891. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  97892. }
  97893. };
  97894. OIMO.BoxCylinderCollisionDetector = function (flip) {
  97895. OIMO.CollisionDetector.call(this);
  97896. this.flip = flip;
  97897. };
  97898. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  97899. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  97900. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  97901. var t1x;
  97902. var t1y;
  97903. var t1z;
  97904. var t2x;
  97905. var t2y;
  97906. var t2z;
  97907. var sup = new OIMO.Vec3();
  97908. var len;
  97909. var p1x;
  97910. var p1y;
  97911. var p1z;
  97912. var p2x;
  97913. var p2y;
  97914. var p2z;
  97915. var v01x = c1.position.x;
  97916. var v01y = c1.position.y;
  97917. var v01z = c1.position.z;
  97918. var v02x = c2.position.x;
  97919. var v02y = c2.position.y;
  97920. var v02z = c2.position.z;
  97921. var v0x = v02x - v01x;
  97922. var v0y = v02y - v01y;
  97923. var v0z = v02z - v01z;
  97924. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  97925. var nx = -v0x;
  97926. var ny = -v0y;
  97927. var nz = -v0z;
  97928. this.supportPointB(c1, -nx, -ny, -nz, sup);
  97929. var v11x = sup.x;
  97930. var v11y = sup.y;
  97931. var v11z = sup.z;
  97932. this.supportPointC(c2, nx, ny, nz, sup);
  97933. var v12x = sup.x;
  97934. var v12y = sup.y;
  97935. var v12z = sup.z;
  97936. var v1x = v12x - v11x;
  97937. var v1y = v12y - v11y;
  97938. var v1z = v12z - v11z;
  97939. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  97940. return false;
  97941. }
  97942. nx = v1y * v0z - v1z * v0y;
  97943. ny = v1z * v0x - v1x * v0z;
  97944. nz = v1x * v0y - v1y * v0x;
  97945. if (nx * nx + ny * ny + nz * nz == 0) {
  97946. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  97947. sep.normalize(sep);
  97948. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  97949. return true;
  97950. }
  97951. this.supportPointB(c1, -nx, -ny, -nz, sup);
  97952. var v21x = sup.x;
  97953. var v21y = sup.y;
  97954. var v21z = sup.z;
  97955. this.supportPointC(c2, nx, ny, nz, sup);
  97956. var v22x = sup.x;
  97957. var v22y = sup.y;
  97958. var v22z = sup.z;
  97959. var v2x = v22x - v21x;
  97960. var v2y = v22y - v21y;
  97961. var v2z = v22z - v21z;
  97962. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  97963. return false;
  97964. }
  97965. t1x = v1x - v0x;
  97966. t1y = v1y - v0y;
  97967. t1z = v1z - v0z;
  97968. t2x = v2x - v0x;
  97969. t2y = v2y - v0y;
  97970. t2z = v2z - v0z;
  97971. nx = t1y * t2z - t1z * t2y;
  97972. ny = t1z * t2x - t1x * t2z;
  97973. nz = t1x * t2y - t1y * t2x;
  97974. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  97975. t1x = v1x;
  97976. t1y = v1y;
  97977. t1z = v1z;
  97978. v1x = v2x;
  97979. v1y = v2y;
  97980. v1z = v2z;
  97981. v2x = t1x;
  97982. v2y = t1y;
  97983. v2z = t1z;
  97984. t1x = v11x;
  97985. t1y = v11y;
  97986. t1z = v11z;
  97987. v11x = v21x;
  97988. v11y = v21y;
  97989. v11z = v21z;
  97990. v21x = t1x;
  97991. v21y = t1y;
  97992. v21z = t1z;
  97993. t1x = v12x;
  97994. t1y = v12y;
  97995. t1z = v12z;
  97996. v12x = v22x;
  97997. v12y = v22y;
  97998. v12z = v22z;
  97999. v22x = t1x;
  98000. v22y = t1y;
  98001. v22z = t1z;
  98002. nx = -nx;
  98003. ny = -ny;
  98004. nz = -nz;
  98005. }
  98006. var iterations = 0;
  98007. while (true) {
  98008. if (++iterations > 100) {
  98009. return false;
  98010. }
  98011. this.supportPointB(c1, -nx, -ny, -nz, sup);
  98012. var v31x = sup.x;
  98013. var v31y = sup.y;
  98014. var v31z = sup.z;
  98015. this.supportPointC(c2, nx, ny, nz, sup);
  98016. var v32x = sup.x;
  98017. var v32y = sup.y;
  98018. var v32z = sup.z;
  98019. var v3x = v32x - v31x;
  98020. var v3y = v32y - v31y;
  98021. var v3z = v32z - v31z;
  98022. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  98023. return false;
  98024. }
  98025. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  98026. v2x = v3x;
  98027. v2y = v3y;
  98028. v2z = v3z;
  98029. v21x = v31x;
  98030. v21y = v31y;
  98031. v21z = v31z;
  98032. v22x = v32x;
  98033. v22y = v32y;
  98034. v22z = v32z;
  98035. t1x = v1x - v0x;
  98036. t1y = v1y - v0y;
  98037. t1z = v1z - v0z;
  98038. t2x = v3x - v0x;
  98039. t2y = v3y - v0y;
  98040. t2z = v3z - v0z;
  98041. nx = t1y * t2z - t1z * t2y;
  98042. ny = t1z * t2x - t1x * t2z;
  98043. nz = t1x * t2y - t1y * t2x;
  98044. continue;
  98045. }
  98046. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  98047. v1x = v3x;
  98048. v1y = v3y;
  98049. v1z = v3z;
  98050. v11x = v31x;
  98051. v11y = v31y;
  98052. v11z = v31z;
  98053. v12x = v32x;
  98054. v12y = v32y;
  98055. v12z = v32z;
  98056. t1x = v3x - v0x;
  98057. t1y = v3y - v0y;
  98058. t1z = v3z - v0z;
  98059. t2x = v2x - v0x;
  98060. t2y = v2y - v0y;
  98061. t2z = v2z - v0z;
  98062. nx = t1y * t2z - t1z * t2y;
  98063. ny = t1z * t2x - t1x * t2z;
  98064. nz = t1x * t2y - t1y * t2x;
  98065. continue;
  98066. }
  98067. var hit = false;
  98068. while (true) {
  98069. t1x = v2x - v1x;
  98070. t1y = v2y - v1y;
  98071. t1z = v2z - v1z;
  98072. t2x = v3x - v1x;
  98073. t2y = v3y - v1y;
  98074. t2z = v3z - v1z;
  98075. nx = t1y * t2z - t1z * t2y;
  98076. ny = t1z * t2x - t1x * t2z;
  98077. nz = t1x * t2y - t1y * t2x;
  98078. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  98079. nx *= len;
  98080. ny *= len;
  98081. nz *= len;
  98082. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  98083. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  98084. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  98085. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  98086. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  98087. var sum = b0 + b1 + b2 + b3;
  98088. if (sum <= 0) {
  98089. b0 = 0;
  98090. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  98091. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  98092. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  98093. sum = b1 + b2 + b3;
  98094. }
  98095. var inv = 1 / sum;
  98096. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  98097. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  98098. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  98099. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  98100. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  98101. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  98102. hit = true;
  98103. }
  98104. this.supportPointB(c1, -nx, -ny, -nz, sup);
  98105. var v41x = sup.x;
  98106. var v41y = sup.y;
  98107. var v41z = sup.z;
  98108. this.supportPointC(c2, nx, ny, nz, sup);
  98109. var v42x = sup.x;
  98110. var v42y = sup.y;
  98111. var v42z = sup.z;
  98112. var v4x = v42x - v41x;
  98113. var v4y = v42y - v41y;
  98114. var v4z = v42z - v41z;
  98115. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  98116. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  98117. if (hit) {
  98118. sep.init(-nx, -ny, -nz);
  98119. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  98120. dep.x = separation;
  98121. return true;
  98122. }
  98123. return false;
  98124. }
  98125. if (
  98126. (v4y * v1z - v4z * v1y) * v0x +
  98127. (v4z * v1x - v4x * v1z) * v0y +
  98128. (v4x * v1y - v4y * v1x) * v0z < 0
  98129. ) {
  98130. if (
  98131. (v4y * v2z - v4z * v2y) * v0x +
  98132. (v4z * v2x - v4x * v2z) * v0y +
  98133. (v4x * v2y - v4y * v2x) * v0z < 0
  98134. ) {
  98135. v1x = v4x;
  98136. v1y = v4y;
  98137. v1z = v4z;
  98138. v11x = v41x;
  98139. v11y = v41y;
  98140. v11z = v41z;
  98141. v12x = v42x;
  98142. v12y = v42y;
  98143. v12z = v42z;
  98144. } else {
  98145. v3x = v4x;
  98146. v3y = v4y;
  98147. v3z = v4z;
  98148. v31x = v41x;
  98149. v31y = v41y;
  98150. v31z = v41z;
  98151. v32x = v42x;
  98152. v32y = v42y;
  98153. v32z = v42z;
  98154. }
  98155. } else {
  98156. if (
  98157. (v4y * v3z - v4z * v3y) * v0x +
  98158. (v4z * v3x - v4x * v3z) * v0y +
  98159. (v4x * v3y - v4y * v3x) * v0z < 0
  98160. ) {
  98161. v2x = v4x;
  98162. v2y = v4y;
  98163. v2z = v4z;
  98164. v21x = v41x;
  98165. v21y = v41y;
  98166. v21z = v41z;
  98167. v22x = v42x;
  98168. v22y = v42y;
  98169. v22z = v42z;
  98170. } else {
  98171. v1x = v4x;
  98172. v1y = v4y;
  98173. v1z = v4z;
  98174. v11x = v41x;
  98175. v11y = v41y;
  98176. v11z = v41z;
  98177. v12x = v42x;
  98178. v12y = v42y;
  98179. v12z = v42z;
  98180. }
  98181. }
  98182. }
  98183. }
  98184. //return false;
  98185. };
  98186. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  98187. var rot = c.rotation.elements;
  98188. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  98189. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  98190. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  98191. var w = c.halfWidth;
  98192. var h = c.halfHeight;
  98193. var d = c.halfDepth;
  98194. var ox;
  98195. var oy;
  98196. var oz;
  98197. if (ldx < 0) ox = -w;
  98198. else ox = w;
  98199. if (ldy < 0) oy = -h;
  98200. else oy = h;
  98201. if (ldz < 0) oz = -d;
  98202. else oz = d;
  98203. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  98204. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  98205. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  98206. out.init(ldx, ldy, ldz);
  98207. };
  98208. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  98209. var rot = c.rotation.elements;
  98210. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  98211. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  98212. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  98213. var radx = ldx;
  98214. var radz = ldz;
  98215. var len = radx * radx + radz * radz;
  98216. var rad = c.radius;
  98217. var hh = c.halfHeight;
  98218. var ox;
  98219. var oy;
  98220. var oz;
  98221. if (len == 0) {
  98222. if (ldy < 0) {
  98223. ox = rad;
  98224. oy = -hh;
  98225. oz = 0;
  98226. } else {
  98227. ox = rad;
  98228. oy = hh;
  98229. oz = 0;
  98230. }
  98231. } else {
  98232. len = c.radius / OIMO.sqrt(len);
  98233. if (ldy < 0) {
  98234. ox = radx * len;
  98235. oy = -hh;
  98236. oz = radz * len;
  98237. } else {
  98238. ox = radx * len;
  98239. oy = hh;
  98240. oz = radz * len;
  98241. }
  98242. }
  98243. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  98244. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  98245. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  98246. out.init(ldx, ldy, ldz);
  98247. };
  98248. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  98249. var b;
  98250. var c;
  98251. if (this.flip) {
  98252. b = shape2;
  98253. c = shape1;
  98254. } else {
  98255. b = shape1;
  98256. c = shape2;
  98257. }
  98258. var sep = new OIMO.Vec3();
  98259. var pos = new OIMO.Vec3();
  98260. var dep = new OIMO.Vec3();
  98261. var co;
  98262. if (!this.getSep(b, c, sep, pos, dep)) return;
  98263. var pbx = b.position.x;
  98264. var pby = b.position.y;
  98265. var pbz = b.position.z;
  98266. var pcx = c.position.x;
  98267. var pcy = c.position.y;
  98268. var pcz = c.position.z;
  98269. var bw = b.halfWidth;
  98270. var bh = b.halfHeight;
  98271. var bd = b.halfDepth;
  98272. var ch = c.halfHeight;
  98273. var r = c.radius;
  98274. var D = b.dimentions;
  98275. var nwx = D[0];//b.normalDirectionWidth.x;
  98276. var nwy = D[1];//b.normalDirectionWidth.y;
  98277. var nwz = D[2];//b.normalDirectionWidth.z;
  98278. var nhx = D[3];//b.normalDirectionHeight.x;
  98279. var nhy = D[4];//b.normalDirectionHeight.y;
  98280. var nhz = D[5];//b.normalDirectionHeight.z;
  98281. var ndx = D[6];//b.normalDirectionDepth.x;
  98282. var ndy = D[7];//b.normalDirectionDepth.y;
  98283. var ndz = D[8];//b.normalDirectionDepth.z;
  98284. var dwx = D[9];//b.halfDirectionWidth.x;
  98285. var dwy = D[10];//b.halfDirectionWidth.y;
  98286. var dwz = D[11];//b.halfDirectionWidth.z;
  98287. var dhx = D[12];//b.halfDirectionHeight.x;
  98288. var dhy = D[13];//b.halfDirectionHeight.y;
  98289. var dhz = D[14];//b.halfDirectionHeight.z;
  98290. var ddx = D[15];//b.halfDirectionDepth.x;
  98291. var ddy = D[16];//b.halfDirectionDepth.y;
  98292. var ddz = D[17];//b.halfDirectionDepth.z;
  98293. var ncx = c.normalDirection.x;
  98294. var ncy = c.normalDirection.y;
  98295. var ncz = c.normalDirection.z;
  98296. var dcx = c.halfDirection.x;
  98297. var dcy = c.halfDirection.y;
  98298. var dcz = c.halfDirection.z;
  98299. var nx = sep.x;
  98300. var ny = sep.y;
  98301. var nz = sep.z;
  98302. var dotw = nx * nwx + ny * nwy + nz * nwz;
  98303. var doth = nx * nhx + ny * nhy + nz * nhz;
  98304. var dotd = nx * ndx + ny * ndy + nz * ndz;
  98305. var dotc = nx * ncx + ny * ncy + nz * ncz;
  98306. var right1 = dotw > 0;
  98307. var right2 = doth > 0;
  98308. var right3 = dotd > 0;
  98309. var right4 = dotc > 0;
  98310. if (!right1) dotw = -dotw;
  98311. if (!right2) doth = -doth;
  98312. if (!right3) dotd = -dotd;
  98313. if (!right4) dotc = -dotc;
  98314. var state = 0;
  98315. if (dotc > 0.999) {
  98316. if (dotw > 0.999) {
  98317. if (dotw > dotc) state = 1;
  98318. else state = 4;
  98319. } else if (doth > 0.999) {
  98320. if (doth > dotc) state = 2;
  98321. else state = 4;
  98322. } else if (dotd > 0.999) {
  98323. if (dotd > dotc) state = 3;
  98324. else state = 4;
  98325. } else state = 4;
  98326. } else {
  98327. if (dotw > 0.999) state = 1;
  98328. else if (doth > 0.999) state = 2;
  98329. else if (dotd > 0.999) state = 3;
  98330. }
  98331. var cbx;
  98332. var cby;
  98333. var cbz;
  98334. var ccx;
  98335. var ccy;
  98336. var ccz;
  98337. var r00;
  98338. var r01;
  98339. var r02;
  98340. var r10;
  98341. var r11;
  98342. var r12;
  98343. var r20;
  98344. var r21;
  98345. var r22;
  98346. var px;
  98347. var py;
  98348. var pz;
  98349. var pd;
  98350. var dot;
  98351. var len;
  98352. var tx;
  98353. var ty;
  98354. var tz;
  98355. var td;
  98356. var dx;
  98357. var dy;
  98358. var dz;
  98359. var d1x;
  98360. var d1y;
  98361. var d1z;
  98362. var d2x;
  98363. var d2y;
  98364. var d2z;
  98365. var sx;
  98366. var sy;
  98367. var sz;
  98368. var sd;
  98369. var ex;
  98370. var ey;
  98371. var ez;
  98372. var ed;
  98373. var dot1;
  98374. var dot2;
  98375. var t1;
  98376. var t2;
  98377. var dir1x;
  98378. var dir1y;
  98379. var dir1z;
  98380. var dir2x;
  98381. var dir2y;
  98382. var dir2z;
  98383. var dir1l;
  98384. var dir2l;
  98385. if (state == 0) {
  98386. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  98387. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  98388. } else if (state == 4) {
  98389. if (right4) {
  98390. ccx = pcx - dcx;
  98391. ccy = pcy - dcy;
  98392. ccz = pcz - dcz;
  98393. nx = -ncx;
  98394. ny = -ncy;
  98395. nz = -ncz;
  98396. } else {
  98397. ccx = pcx + dcx;
  98398. ccy = pcy + dcy;
  98399. ccz = pcz + dcz;
  98400. nx = ncx;
  98401. ny = ncy;
  98402. nz = ncz;
  98403. }
  98404. var v1x;
  98405. var v1y;
  98406. var v1z;
  98407. var v2x;
  98408. var v2y;
  98409. var v2z;
  98410. var v3x;
  98411. var v3y;
  98412. var v3z;
  98413. var v4x;
  98414. var v4y;
  98415. var v4z;
  98416. dot = 1;
  98417. state = 0;
  98418. dot1 = nwx * nx + nwy * ny + nwz * nz;
  98419. if (dot1 < dot) {
  98420. dot = dot1;
  98421. state = 0;
  98422. }
  98423. if (-dot1 < dot) {
  98424. dot = -dot1;
  98425. state = 1;
  98426. }
  98427. dot1 = nhx * nx + nhy * ny + nhz * nz;
  98428. if (dot1 < dot) {
  98429. dot = dot1;
  98430. state = 2;
  98431. }
  98432. if (-dot1 < dot) {
  98433. dot = -dot1;
  98434. state = 3;
  98435. }
  98436. dot1 = ndx * nx + ndy * ny + ndz * nz;
  98437. if (dot1 < dot) {
  98438. dot = dot1;
  98439. state = 4;
  98440. }
  98441. if (-dot1 < dot) {
  98442. dot = -dot1;
  98443. state = 5;
  98444. }
  98445. var v = b.elements;
  98446. switch (state) {
  98447. case 0:
  98448. //v=b.vertex1;
  98449. v1x = v[0];//v.x;
  98450. v1y = v[1];//v.y;
  98451. v1z = v[2];//v.z;
  98452. //v=b.vertex3;
  98453. v2x = v[6];//v.x;
  98454. v2y = v[7];//v.y;
  98455. v2z = v[8];//v.z;
  98456. //v=b.vertex4;
  98457. v3x = v[9];//v.x;
  98458. v3y = v[10];//v.y;
  98459. v3z = v[11];//v.z;
  98460. //v=b.vertex2;
  98461. v4x = v[3];//v.x;
  98462. v4y = v[4];//v.y;
  98463. v4z = v[5];//v.z;
  98464. break;
  98465. case 1:
  98466. //v=b.vertex6;
  98467. v1x = v[15];//v.x;
  98468. v1y = v[16];//v.y;
  98469. v1z = v[17];//v.z;
  98470. //v=b.vertex8;
  98471. v2x = v[21];//v.x;
  98472. v2y = v[22];//v.y;
  98473. v2z = v[23];//v.z;
  98474. //v=b.vertex7;
  98475. v3x = v[18];//v.x;
  98476. v3y = v[19];//v.y;
  98477. v3z = v[20];//v.z;
  98478. //v=b.vertex5;
  98479. v4x = v[12];//v.x;
  98480. v4y = v[13];//v.y;
  98481. v4z = v[14];//v.z;
  98482. break;
  98483. case 2:
  98484. //v=b.vertex5;
  98485. v1x = v[12];//v.x;
  98486. v1y = v[13];//v.y;
  98487. v1z = v[14];//v.z;
  98488. //v=b.vertex1;
  98489. v2x = v[0];//v.x;
  98490. v2y = v[1];//v.y;
  98491. v2z = v[2];//v.z;
  98492. //v=b.vertex2;
  98493. v3x = v[3];//v.x;
  98494. v3y = v[4];//v.y;
  98495. v3z = v[5];//v.z;
  98496. //v=b.vertex6;
  98497. v4x = v[15];//v.x;
  98498. v4y = v[16];//v.y;
  98499. v4z = v[17];//v.z;
  98500. break;
  98501. case 3:
  98502. //v=b.vertex8;
  98503. v1x = v[21];//v.x;
  98504. v1y = v[22];//v.y;
  98505. v1z = v[23];//v.z;
  98506. //v=b.vertex4;
  98507. v2x = v[9];//v.x;
  98508. v2y = v[10];//v.y;
  98509. v2z = v[11];//v.z;
  98510. //v=b.vertex3;
  98511. v3x = v[6];//v.x;
  98512. v3y = v[7];//v.y;
  98513. v3z = v[8];//v.z;
  98514. //v=b.vertex7;
  98515. v4x = v[18];//v.x;
  98516. v4y = v[19];//v.y;
  98517. v4z = v[20];//v.z;
  98518. break;
  98519. case 4:
  98520. //v=b.vertex5;
  98521. v1x = v[12];//v.x;
  98522. v1y = v[13];//v.y;
  98523. v1z = v[14];//v.z;
  98524. //v=b.vertex7;
  98525. v2x = v[18];//v.x;
  98526. v2y = v[19];//v.y;
  98527. v2z = v[20];//v.z;
  98528. //v=b.vertex3;
  98529. v3x = v[6];//v.x;
  98530. v3y = v[7];//v.y;
  98531. v3z = v[8];//v.z;
  98532. //v=b.vertex1;
  98533. v4x = v[0];//v.x;
  98534. v4y = v[1];//v.y;
  98535. v4z = v[2];//v.z;
  98536. break;
  98537. case 5:
  98538. //v=b.vertex2;
  98539. v1x = v[3];//v.x;
  98540. v1y = v[4];//v.y;
  98541. v1z = v[5];//v.z;
  98542. //v=b.vertex4;
  98543. v2x = v[9];//v.x;
  98544. v2y = v[10];//v.y;
  98545. v2z = v[11];//v.z;
  98546. //v=b.vertex8;
  98547. v3x = v[21];//v.x;
  98548. v3y = v[22];//v.y;
  98549. v3z = v[23];//v.z;
  98550. //v=b.vertex6;
  98551. v4x = v[15];//v.x;
  98552. v4y = v[16];//v.y;
  98553. v4z = v[17];//v.z;
  98554. break;
  98555. }
  98556. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  98557. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  98558. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  98559. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  98560. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  98561. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  98562. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  98563. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  98564. } else {
  98565. switch (state) {
  98566. case 1:
  98567. if (right1) {
  98568. cbx = pbx + dwx;
  98569. cby = pby + dwy;
  98570. cbz = pbz + dwz;
  98571. nx = nwx;
  98572. ny = nwy;
  98573. nz = nwz;
  98574. } else {
  98575. cbx = pbx - dwx;
  98576. cby = pby - dwy;
  98577. cbz = pbz - dwz;
  98578. nx = -nwx;
  98579. ny = -nwy;
  98580. nz = -nwz;
  98581. }
  98582. dir1x = nhx;
  98583. dir1y = nhy;
  98584. dir1z = nhz;
  98585. dir1l = bh;
  98586. dir2x = ndx;
  98587. dir2y = ndy;
  98588. dir2z = ndz;
  98589. dir2l = bd;
  98590. break;
  98591. case 2:
  98592. if (right2) {
  98593. cbx = pbx + dhx;
  98594. cby = pby + dhy;
  98595. cbz = pbz + dhz;
  98596. nx = nhx;
  98597. ny = nhy;
  98598. nz = nhz;
  98599. } else {
  98600. cbx = pbx - dhx;
  98601. cby = pby - dhy;
  98602. cbz = pbz - dhz;
  98603. nx = -nhx;
  98604. ny = -nhy;
  98605. nz = -nhz;
  98606. }
  98607. dir1x = nwx;
  98608. dir1y = nwy;
  98609. dir1z = nwz;
  98610. dir1l = bw;
  98611. dir2x = ndx;
  98612. dir2y = ndy;
  98613. dir2z = ndz;
  98614. dir2l = bd;
  98615. break;
  98616. case 3:
  98617. if (right3) {
  98618. cbx = pbx + ddx;
  98619. cby = pby + ddy;
  98620. cbz = pbz + ddz;
  98621. nx = ndx;
  98622. ny = ndy;
  98623. nz = ndz;
  98624. } else {
  98625. cbx = pbx - ddx;
  98626. cby = pby - ddy;
  98627. cbz = pbz - ddz;
  98628. nx = -ndx;
  98629. ny = -ndy;
  98630. nz = -ndz;
  98631. }
  98632. dir1x = nwx;
  98633. dir1y = nwy;
  98634. dir1z = nwz;
  98635. dir1l = bw;
  98636. dir2x = nhx;
  98637. dir2y = nhy;
  98638. dir2z = nhz;
  98639. dir2l = bh;
  98640. break;
  98641. }
  98642. dot = nx * ncx + ny * ncy + nz * ncz;
  98643. if (dot < 0) len = ch;
  98644. else len = -ch;
  98645. ccx = pcx + len * ncx;
  98646. ccy = pcy + len * ncy;
  98647. ccz = pcz + len * ncz;
  98648. if (dotc >= 0.999999) {
  98649. tx = -ny;
  98650. ty = nz;
  98651. tz = nx;
  98652. } else {
  98653. tx = nx;
  98654. ty = ny;
  98655. tz = nz;
  98656. }
  98657. len = tx * ncx + ty * ncy + tz * ncz;
  98658. dx = len * ncx - tx;
  98659. dy = len * ncy - ty;
  98660. dz = len * ncz - tz;
  98661. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  98662. if (len == 0) return;
  98663. len = r / len;
  98664. dx *= len;
  98665. dy *= len;
  98666. dz *= len;
  98667. tx = ccx + dx;
  98668. ty = ccy + dy;
  98669. tz = ccz + dz;
  98670. if (dot < -0.96 || dot > 0.96) {
  98671. r00 = ncx * ncx * 1.5 - 0.5;
  98672. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  98673. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  98674. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  98675. r11 = ncy * ncy * 1.5 - 0.5;
  98676. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  98677. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  98678. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  98679. r22 = ncz * ncz * 1.5 - 0.5;
  98680. px = tx;
  98681. py = ty;
  98682. pz = tz;
  98683. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  98684. tx = px - pd * nx - cbx;
  98685. ty = py - pd * ny - cby;
  98686. tz = pz - pd * nz - cbz;
  98687. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  98688. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  98689. if (sd < -dir1l) sd = -dir1l;
  98690. else if (sd > dir1l) sd = dir1l;
  98691. if (ed < -dir2l) ed = -dir2l;
  98692. else if (ed > dir2l) ed = dir2l;
  98693. tx = sd * dir1x + ed * dir2x;
  98694. ty = sd * dir1y + ed * dir2y;
  98695. tz = sd * dir1z + ed * dir2z;
  98696. px = cbx + tx;
  98697. py = cby + ty;
  98698. pz = cbz + tz;
  98699. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  98700. px = dx * r00 + dy * r01 + dz * r02;
  98701. py = dx * r10 + dy * r11 + dz * r12;
  98702. pz = dx * r20 + dy * r21 + dz * r22;
  98703. px = (dx = px) + ccx;
  98704. py = (dy = py) + ccy;
  98705. pz = (dz = pz) + ccz;
  98706. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  98707. if (pd <= 0) {
  98708. tx = px - pd * nx - cbx;
  98709. ty = py - pd * ny - cby;
  98710. tz = pz - pd * nz - cbz;
  98711. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  98712. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  98713. if (sd < -dir1l) sd = -dir1l;
  98714. else if (sd > dir1l) sd = dir1l;
  98715. if (ed < -dir2l) ed = -dir2l;
  98716. else if (ed > dir2l) ed = dir2l;
  98717. tx = sd * dir1x + ed * dir2x;
  98718. ty = sd * dir1y + ed * dir2y;
  98719. tz = sd * dir1z + ed * dir2z;
  98720. px = cbx + tx;
  98721. py = cby + ty;
  98722. pz = cbz + tz;
  98723. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  98724. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  98725. }
  98726. px = dx * r00 + dy * r01 + dz * r02;
  98727. py = dx * r10 + dy * r11 + dz * r12;
  98728. pz = dx * r20 + dy * r21 + dz * r22;
  98729. px = (dx = px) + ccx;
  98730. py = (dy = py) + ccy;
  98731. pz = (dz = pz) + ccz;
  98732. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  98733. if (pd <= 0) {
  98734. tx = px - pd * nx - cbx;
  98735. ty = py - pd * ny - cby;
  98736. tz = pz - pd * nz - cbz;
  98737. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  98738. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  98739. if (sd < -dir1l) sd = -dir1l;
  98740. else if (sd > dir1l) sd = dir1l;
  98741. if (ed < -dir2l) ed = -dir2l;
  98742. else if (ed > dir2l) ed = dir2l;
  98743. tx = sd * dir1x + ed * dir2x;
  98744. ty = sd * dir1y + ed * dir2y;
  98745. tz = sd * dir1z + ed * dir2z;
  98746. px = cbx + tx;
  98747. py = cby + ty;
  98748. pz = cbz + tz;
  98749. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  98750. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  98751. }
  98752. } else {
  98753. sx = tx;
  98754. sy = ty;
  98755. sz = tz;
  98756. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  98757. sx -= sd * nx;
  98758. sy -= sd * ny;
  98759. sz -= sd * nz;
  98760. if (dot > 0) {
  98761. ex = tx + dcx * 2;
  98762. ey = ty + dcy * 2;
  98763. ez = tz + dcz * 2;
  98764. } else {
  98765. ex = tx - dcx * 2;
  98766. ey = ty - dcy * 2;
  98767. ez = tz - dcz * 2;
  98768. }
  98769. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  98770. ex -= ed * nx;
  98771. ey -= ed * ny;
  98772. ez -= ed * nz;
  98773. d1x = sx - cbx;
  98774. d1y = sy - cby;
  98775. d1z = sz - cbz;
  98776. d2x = ex - cbx;
  98777. d2y = ey - cby;
  98778. d2z = ez - cbz;
  98779. tx = ex - sx;
  98780. ty = ey - sy;
  98781. tz = ez - sz;
  98782. td = ed - sd;
  98783. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  98784. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  98785. dot1 = dotw - dir1l;
  98786. dot2 = doth - dir1l;
  98787. if (dot1 > 0) {
  98788. if (dot2 > 0) return;
  98789. t1 = dot1 / (dot1 - dot2);
  98790. sx = sx + tx * t1;
  98791. sy = sy + ty * t1;
  98792. sz = sz + tz * t1;
  98793. sd = sd + td * t1;
  98794. d1x = sx - cbx;
  98795. d1y = sy - cby;
  98796. d1z = sz - cbz;
  98797. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  98798. tx = ex - sx;
  98799. ty = ey - sy;
  98800. tz = ez - sz;
  98801. td = ed - sd;
  98802. } else if (dot2 > 0) {
  98803. t1 = dot1 / (dot1 - dot2);
  98804. ex = sx + tx * t1;
  98805. ey = sy + ty * t1;
  98806. ez = sz + tz * t1;
  98807. ed = sd + td * t1;
  98808. d2x = ex - cbx;
  98809. d2y = ey - cby;
  98810. d2z = ez - cbz;
  98811. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  98812. tx = ex - sx;
  98813. ty = ey - sy;
  98814. tz = ez - sz;
  98815. td = ed - sd;
  98816. }
  98817. dot1 = dotw + dir1l;
  98818. dot2 = doth + dir1l;
  98819. if (dot1 < 0) {
  98820. if (dot2 < 0) return;
  98821. t1 = dot1 / (dot1 - dot2);
  98822. sx = sx + tx * t1;
  98823. sy = sy + ty * t1;
  98824. sz = sz + tz * t1;
  98825. sd = sd + td * t1;
  98826. d1x = sx - cbx;
  98827. d1y = sy - cby;
  98828. d1z = sz - cbz;
  98829. tx = ex - sx;
  98830. ty = ey - sy;
  98831. tz = ez - sz;
  98832. td = ed - sd;
  98833. } else if (dot2 < 0) {
  98834. t1 = dot1 / (dot1 - dot2);
  98835. ex = sx + tx * t1;
  98836. ey = sy + ty * t1;
  98837. ez = sz + tz * t1;
  98838. ed = sd + td * t1;
  98839. d2x = ex - cbx;
  98840. d2y = ey - cby;
  98841. d2z = ez - cbz;
  98842. tx = ex - sx;
  98843. ty = ey - sy;
  98844. tz = ez - sz;
  98845. td = ed - sd;
  98846. }
  98847. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  98848. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  98849. dot1 = dotw - dir2l;
  98850. dot2 = doth - dir2l;
  98851. if (dot1 > 0) {
  98852. if (dot2 > 0) return;
  98853. t1 = dot1 / (dot1 - dot2);
  98854. sx = sx + tx * t1;
  98855. sy = sy + ty * t1;
  98856. sz = sz + tz * t1;
  98857. sd = sd + td * t1;
  98858. d1x = sx - cbx;
  98859. d1y = sy - cby;
  98860. d1z = sz - cbz;
  98861. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  98862. tx = ex - sx;
  98863. ty = ey - sy;
  98864. tz = ez - sz;
  98865. td = ed - sd;
  98866. } else if (dot2 > 0) {
  98867. t1 = dot1 / (dot1 - dot2);
  98868. ex = sx + tx * t1;
  98869. ey = sy + ty * t1;
  98870. ez = sz + tz * t1;
  98871. ed = sd + td * t1;
  98872. d2x = ex - cbx;
  98873. d2y = ey - cby;
  98874. d2z = ez - cbz;
  98875. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  98876. tx = ex - sx;
  98877. ty = ey - sy;
  98878. tz = ez - sz;
  98879. td = ed - sd;
  98880. }
  98881. dot1 = dotw + dir2l;
  98882. dot2 = doth + dir2l;
  98883. if (dot1 < 0) {
  98884. if (dot2 < 0) return;
  98885. t1 = dot1 / (dot1 - dot2);
  98886. sx = sx + tx * t1;
  98887. sy = sy + ty * t1;
  98888. sz = sz + tz * t1;
  98889. sd = sd + td * t1;
  98890. } else if (dot2 < 0) {
  98891. t1 = dot1 / (dot1 - dot2);
  98892. ex = sx + tx * t1;
  98893. ey = sy + ty * t1;
  98894. ez = sz + tz * t1;
  98895. ed = sd + td * t1;
  98896. }
  98897. if (sd < 0) {
  98898. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  98899. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  98900. }
  98901. if (ed < 0) {
  98902. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  98903. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  98904. }
  98905. }
  98906. }
  98907. };
  98908. OIMO.CylinderCylinderCollisionDetector = function () {
  98909. OIMO.CollisionDetector.call(this);
  98910. };
  98911. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  98912. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  98913. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  98914. var t1x;
  98915. var t1y;
  98916. var t1z;
  98917. var t2x;
  98918. var t2y;
  98919. var t2z;
  98920. var sup = new OIMO.Vec3();
  98921. var len;
  98922. var p1x;
  98923. var p1y;
  98924. var p1z;
  98925. var p2x;
  98926. var p2y;
  98927. var p2z;
  98928. var v01x = c1.position.x;
  98929. var v01y = c1.position.y;
  98930. var v01z = c1.position.z;
  98931. var v02x = c2.position.x;
  98932. var v02y = c2.position.y;
  98933. var v02z = c2.position.z;
  98934. var v0x = v02x - v01x;
  98935. var v0y = v02y - v01y;
  98936. var v0z = v02z - v01z;
  98937. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  98938. var nx = -v0x;
  98939. var ny = -v0y;
  98940. var nz = -v0z;
  98941. this.supportPoint(c1, -nx, -ny, -nz, sup);
  98942. var v11x = sup.x;
  98943. var v11y = sup.y;
  98944. var v11z = sup.z;
  98945. this.supportPoint(c2, nx, ny, nz, sup);
  98946. var v12x = sup.x;
  98947. var v12y = sup.y;
  98948. var v12z = sup.z;
  98949. var v1x = v12x - v11x;
  98950. var v1y = v12y - v11y;
  98951. var v1z = v12z - v11z;
  98952. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  98953. return false;
  98954. }
  98955. nx = v1y * v0z - v1z * v0y;
  98956. ny = v1z * v0x - v1x * v0z;
  98957. nz = v1x * v0y - v1y * v0x;
  98958. if (nx * nx + ny * ny + nz * nz == 0) {
  98959. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  98960. sep.normalize(sep);
  98961. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  98962. return true;
  98963. }
  98964. this.supportPoint(c1, -nx, -ny, -nz, sup);
  98965. var v21x = sup.x;
  98966. var v21y = sup.y;
  98967. var v21z = sup.z;
  98968. this.supportPoint(c2, nx, ny, nz, sup);
  98969. var v22x = sup.x;
  98970. var v22y = sup.y;
  98971. var v22z = sup.z;
  98972. var v2x = v22x - v21x;
  98973. var v2y = v22y - v21y;
  98974. var v2z = v22z - v21z;
  98975. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  98976. return false;
  98977. }
  98978. t1x = v1x - v0x;
  98979. t1y = v1y - v0y;
  98980. t1z = v1z - v0z;
  98981. t2x = v2x - v0x;
  98982. t2y = v2y - v0y;
  98983. t2z = v2z - v0z;
  98984. nx = t1y * t2z - t1z * t2y;
  98985. ny = t1z * t2x - t1x * t2z;
  98986. nz = t1x * t2y - t1y * t2x;
  98987. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  98988. t1x = v1x;
  98989. t1y = v1y;
  98990. t1z = v1z;
  98991. v1x = v2x;
  98992. v1y = v2y;
  98993. v1z = v2z;
  98994. v2x = t1x;
  98995. v2y = t1y;
  98996. v2z = t1z;
  98997. t1x = v11x;
  98998. t1y = v11y;
  98999. t1z = v11z;
  99000. v11x = v21x;
  99001. v11y = v21y;
  99002. v11z = v21z;
  99003. v21x = t1x;
  99004. v21y = t1y;
  99005. v21z = t1z;
  99006. t1x = v12x;
  99007. t1y = v12y;
  99008. t1z = v12z;
  99009. v12x = v22x;
  99010. v12y = v22y;
  99011. v12z = v22z;
  99012. v22x = t1x;
  99013. v22y = t1y;
  99014. v22z = t1z;
  99015. nx = -nx;
  99016. ny = -ny;
  99017. nz = -nz;
  99018. }
  99019. var iterations = 0;
  99020. while (true) {
  99021. if (++iterations > 100) {
  99022. return false;
  99023. }
  99024. this.supportPoint(c1, -nx, -ny, -nz, sup);
  99025. var v31x = sup.x;
  99026. var v31y = sup.y;
  99027. var v31z = sup.z;
  99028. this.supportPoint(c2, nx, ny, nz, sup);
  99029. var v32x = sup.x;
  99030. var v32y = sup.y;
  99031. var v32z = sup.z;
  99032. var v3x = v32x - v31x;
  99033. var v3y = v32y - v31y;
  99034. var v3z = v32z - v31z;
  99035. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  99036. return false;
  99037. }
  99038. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  99039. v2x = v3x;
  99040. v2y = v3y;
  99041. v2z = v3z;
  99042. v21x = v31x;
  99043. v21y = v31y;
  99044. v21z = v31z;
  99045. v22x = v32x;
  99046. v22y = v32y;
  99047. v22z = v32z;
  99048. t1x = v1x - v0x;
  99049. t1y = v1y - v0y;
  99050. t1z = v1z - v0z;
  99051. t2x = v3x - v0x;
  99052. t2y = v3y - v0y;
  99053. t2z = v3z - v0z;
  99054. nx = t1y * t2z - t1z * t2y;
  99055. ny = t1z * t2x - t1x * t2z;
  99056. nz = t1x * t2y - t1y * t2x;
  99057. continue;
  99058. }
  99059. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  99060. v1x = v3x;
  99061. v1y = v3y;
  99062. v1z = v3z;
  99063. v11x = v31x;
  99064. v11y = v31y;
  99065. v11z = v31z;
  99066. v12x = v32x;
  99067. v12y = v32y;
  99068. v12z = v32z;
  99069. t1x = v3x - v0x;
  99070. t1y = v3y - v0y;
  99071. t1z = v3z - v0z;
  99072. t2x = v2x - v0x;
  99073. t2y = v2y - v0y;
  99074. t2z = v2z - v0z;
  99075. nx = t1y * t2z - t1z * t2y;
  99076. ny = t1z * t2x - t1x * t2z;
  99077. nz = t1x * t2y - t1y * t2x;
  99078. continue;
  99079. }
  99080. var hit = false;
  99081. while (true) {
  99082. t1x = v2x - v1x;
  99083. t1y = v2y - v1y;
  99084. t1z = v2z - v1z;
  99085. t2x = v3x - v1x;
  99086. t2y = v3y - v1y;
  99087. t2z = v3z - v1z;
  99088. nx = t1y * t2z - t1z * t2y;
  99089. ny = t1z * t2x - t1x * t2z;
  99090. nz = t1x * t2y - t1y * t2x;
  99091. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  99092. nx *= len;
  99093. ny *= len;
  99094. nz *= len;
  99095. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  99096. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  99097. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  99098. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  99099. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  99100. var sum = b0 + b1 + b2 + b3;
  99101. if (sum <= 0) {
  99102. b0 = 0;
  99103. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  99104. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  99105. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  99106. sum = b1 + b2 + b3;
  99107. }
  99108. var inv = 1 / sum;
  99109. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  99110. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  99111. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  99112. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  99113. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  99114. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  99115. hit = true;
  99116. }
  99117. this.supportPoint(c1, -nx, -ny, -nz, sup);
  99118. var v41x = sup.x;
  99119. var v41y = sup.y;
  99120. var v41z = sup.z;
  99121. this.supportPoint(c2, nx, ny, nz, sup);
  99122. var v42x = sup.x;
  99123. var v42y = sup.y;
  99124. var v42z = sup.z;
  99125. var v4x = v42x - v41x;
  99126. var v4y = v42y - v41y;
  99127. var v4z = v42z - v41z;
  99128. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  99129. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  99130. if (hit) {
  99131. sep.init(-nx, -ny, -nz);
  99132. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  99133. dep.x = separation;
  99134. return true;
  99135. }
  99136. return false;
  99137. }
  99138. if (
  99139. (v4y * v1z - v4z * v1y) * v0x +
  99140. (v4z * v1x - v4x * v1z) * v0y +
  99141. (v4x * v1y - v4y * v1x) * v0z < 0
  99142. ) {
  99143. if (
  99144. (v4y * v2z - v4z * v2y) * v0x +
  99145. (v4z * v2x - v4x * v2z) * v0y +
  99146. (v4x * v2y - v4y * v2x) * v0z < 0
  99147. ) {
  99148. v1x = v4x;
  99149. v1y = v4y;
  99150. v1z = v4z;
  99151. v11x = v41x;
  99152. v11y = v41y;
  99153. v11z = v41z;
  99154. v12x = v42x;
  99155. v12y = v42y;
  99156. v12z = v42z;
  99157. } else {
  99158. v3x = v4x;
  99159. v3y = v4y;
  99160. v3z = v4z;
  99161. v31x = v41x;
  99162. v31y = v41y;
  99163. v31z = v41z;
  99164. v32x = v42x;
  99165. v32y = v42y;
  99166. v32z = v42z;
  99167. }
  99168. } else {
  99169. if (
  99170. (v4y * v3z - v4z * v3y) * v0x +
  99171. (v4z * v3x - v4x * v3z) * v0y +
  99172. (v4x * v3y - v4y * v3x) * v0z < 0
  99173. ) {
  99174. v2x = v4x;
  99175. v2y = v4y;
  99176. v2z = v4z;
  99177. v21x = v41x;
  99178. v21y = v41y;
  99179. v21z = v41z;
  99180. v22x = v42x;
  99181. v22y = v42y;
  99182. v22z = v42z;
  99183. } else {
  99184. v1x = v4x;
  99185. v1y = v4y;
  99186. v1z = v4z;
  99187. v11x = v41x;
  99188. v11y = v41y;
  99189. v11z = v41z;
  99190. v12x = v42x;
  99191. v12y = v42y;
  99192. v12z = v42z;
  99193. }
  99194. }
  99195. }
  99196. }
  99197. //return false;
  99198. };
  99199. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  99200. var rot = c.rotation.elements;
  99201. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  99202. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  99203. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  99204. var radx = ldx;
  99205. var radz = ldz;
  99206. var len = radx * radx + radz * radz;
  99207. var rad = c.radius;
  99208. var hh = c.halfHeight;
  99209. var ox;
  99210. var oy;
  99211. var oz;
  99212. if (len == 0) {
  99213. if (ldy < 0) {
  99214. ox = rad;
  99215. oy = -hh;
  99216. oz = 0;
  99217. } else {
  99218. ox = rad;
  99219. oy = hh;
  99220. oz = 0;
  99221. }
  99222. } else {
  99223. len = c.radius / OIMO.sqrt(len);
  99224. if (ldy < 0) {
  99225. ox = radx * len;
  99226. oy = -hh;
  99227. oz = radz * len;
  99228. } else {
  99229. ox = radx * len;
  99230. oy = hh;
  99231. oz = radz * len;
  99232. }
  99233. }
  99234. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  99235. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  99236. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  99237. out.init(ldx, ldy, ldz);
  99238. };
  99239. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99240. var c1;
  99241. var c2;
  99242. if (shape1.id < shape2.id) {
  99243. c1 = shape1;
  99244. c2 = shape2;
  99245. } else {
  99246. c1 = shape2;
  99247. c2 = shape1;
  99248. }
  99249. var p1 = c1.position;
  99250. var p2 = c2.position;
  99251. var p1x = p1.x;
  99252. var p1y = p1.y;
  99253. var p1z = p1.z;
  99254. var p2x = p2.x;
  99255. var p2y = p2.y;
  99256. var p2z = p2.z;
  99257. var h1 = c1.halfHeight;
  99258. var h2 = c2.halfHeight;
  99259. var n1 = c1.normalDirection;
  99260. var n2 = c2.normalDirection;
  99261. var d1 = c1.halfDirection;
  99262. var d2 = c2.halfDirection;
  99263. var r1 = c1.radius;
  99264. var r2 = c2.radius;
  99265. var n1x = n1.x;
  99266. var n1y = n1.y;
  99267. var n1z = n1.z;
  99268. var n2x = n2.x;
  99269. var n2y = n2.y;
  99270. var n2z = n2.z;
  99271. var d1x = d1.x;
  99272. var d1y = d1.y;
  99273. var d1z = d1.z;
  99274. var d2x = d2.x;
  99275. var d2y = d2.y;
  99276. var d2z = d2.z;
  99277. var dx = p1x - p2x;
  99278. var dy = p1y - p2y;
  99279. var dz = p1z - p2z;
  99280. var len;
  99281. var len1;
  99282. var len2;
  99283. var c;
  99284. var c1x;
  99285. var c1y;
  99286. var c1z;
  99287. var c2x;
  99288. var c2y;
  99289. var c2z;
  99290. var tx;
  99291. var ty;
  99292. var tz;
  99293. var sx;
  99294. var sy;
  99295. var sz;
  99296. var ex;
  99297. var ey;
  99298. var ez;
  99299. var depth1;
  99300. var depth2;
  99301. var dot;
  99302. var t1;
  99303. var t2;
  99304. var sep = new OIMO.Vec3();
  99305. var pos = new OIMO.Vec3();
  99306. var dep = new OIMO.Vec3();
  99307. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  99308. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  99309. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  99310. var right1 = dot1 > 0;
  99311. var right2 = dot2 > 0;
  99312. if (!right1) dot1 = -dot1;
  99313. if (!right2) dot2 = -dot2;
  99314. var state = 0;
  99315. if (dot1 > 0.999 || dot2 > 0.999) {
  99316. if (dot1 > dot2) state = 1;
  99317. else state = 2;
  99318. }
  99319. var nx;
  99320. var ny;
  99321. var nz;
  99322. var depth = dep.x;
  99323. var r00;
  99324. var r01;
  99325. var r02;
  99326. var r10;
  99327. var r11;
  99328. var r12;
  99329. var r20;
  99330. var r21;
  99331. var r22;
  99332. var px;
  99333. var py;
  99334. var pz;
  99335. var pd;
  99336. var a;
  99337. var b;
  99338. var e;
  99339. var f;
  99340. nx = sep.x;
  99341. ny = sep.y;
  99342. nz = sep.z;
  99343. switch (state) {
  99344. case 0:
  99345. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  99346. break;
  99347. case 1:
  99348. if (right1) {
  99349. c1x = p1x + d1x;
  99350. c1y = p1y + d1y;
  99351. c1z = p1z + d1z;
  99352. nx = n1x;
  99353. ny = n1y;
  99354. nz = n1z;
  99355. } else {
  99356. c1x = p1x - d1x;
  99357. c1y = p1y - d1y;
  99358. c1z = p1z - d1z;
  99359. nx = -n1x;
  99360. ny = -n1y;
  99361. nz = -n1z;
  99362. }
  99363. dot = nx * n2x + ny * n2y + nz * n2z;
  99364. if (dot < 0) len = h2;
  99365. else len = -h2;
  99366. c2x = p2x + len * n2x;
  99367. c2y = p2y + len * n2y;
  99368. c2z = p2z + len * n2z;
  99369. if (dot2 >= 0.999999) {
  99370. tx = -ny;
  99371. ty = nz;
  99372. tz = nx;
  99373. } else {
  99374. tx = nx;
  99375. ty = ny;
  99376. tz = nz;
  99377. }
  99378. len = tx * n2x + ty * n2y + tz * n2z;
  99379. dx = len * n2x - tx;
  99380. dy = len * n2y - ty;
  99381. dz = len * n2z - tz;
  99382. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  99383. if (len == 0) break;
  99384. len = r2 / len;
  99385. dx *= len;
  99386. dy *= len;
  99387. dz *= len;
  99388. tx = c2x + dx;
  99389. ty = c2y + dy;
  99390. tz = c2z + dz;
  99391. if (dot < -0.96 || dot > 0.96) {
  99392. r00 = n2x * n2x * 1.5 - 0.5;
  99393. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  99394. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  99395. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  99396. r11 = n2y * n2y * 1.5 - 0.5;
  99397. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  99398. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  99399. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  99400. r22 = n2z * n2z * 1.5 - 0.5;
  99401. px = tx;
  99402. py = ty;
  99403. pz = tz;
  99404. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  99405. tx = px - pd * nx - c1x;
  99406. ty = py - pd * ny - c1y;
  99407. tz = pz - pd * nz - c1z;
  99408. len = tx * tx + ty * ty + tz * tz;
  99409. if (len > r1 * r1) {
  99410. len = r1 / OIMO.sqrt(len);
  99411. tx *= len;
  99412. ty *= len;
  99413. tz *= len;
  99414. }
  99415. px = c1x + tx;
  99416. py = c1y + ty;
  99417. pz = c1z + tz;
  99418. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  99419. px = dx * r00 + dy * r01 + dz * r02;
  99420. py = dx * r10 + dy * r11 + dz * r12;
  99421. pz = dx * r20 + dy * r21 + dz * r22;
  99422. px = (dx = px) + c2x;
  99423. py = (dy = py) + c2y;
  99424. pz = (dz = pz) + c2z;
  99425. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  99426. if (pd <= 0) {
  99427. tx = px - pd * nx - c1x;
  99428. ty = py - pd * ny - c1y;
  99429. tz = pz - pd * nz - c1z;
  99430. len = tx * tx + ty * ty + tz * tz;
  99431. if (len > r1 * r1) {
  99432. len = r1 / OIMO.sqrt(len);
  99433. tx *= len;
  99434. ty *= len;
  99435. tz *= len;
  99436. }
  99437. px = c1x + tx;
  99438. py = c1y + ty;
  99439. pz = c1z + tz;
  99440. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  99441. }
  99442. px = dx * r00 + dy * r01 + dz * r02;
  99443. py = dx * r10 + dy * r11 + dz * r12;
  99444. pz = dx * r20 + dy * r21 + dz * r22;
  99445. px = (dx = px) + c2x;
  99446. py = (dy = py) + c2y;
  99447. pz = (dz = pz) + c2z;
  99448. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  99449. if (pd <= 0) {
  99450. tx = px - pd * nx - c1x;
  99451. ty = py - pd * ny - c1y;
  99452. tz = pz - pd * nz - c1z;
  99453. len = tx * tx + ty * ty + tz * tz;
  99454. if (len > r1 * r1) {
  99455. len = r1 / OIMO.sqrt(len);
  99456. tx *= len;
  99457. ty *= len;
  99458. tz *= len;
  99459. }
  99460. px = c1x + tx;
  99461. py = c1y + ty;
  99462. pz = c1z + tz;
  99463. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  99464. }
  99465. } else {
  99466. sx = tx;
  99467. sy = ty;
  99468. sz = tz;
  99469. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  99470. sx -= depth1 * nx;
  99471. sy -= depth1 * ny;
  99472. sz -= depth1 * nz;
  99473. if (dot > 0) {
  99474. ex = tx + n2x * h2 * 2;
  99475. ey = ty + n2y * h2 * 2;
  99476. ez = tz + n2z * h2 * 2;
  99477. } else {
  99478. ex = tx - n2x * h2 * 2;
  99479. ey = ty - n2y * h2 * 2;
  99480. ez = tz - n2z * h2 * 2;
  99481. }
  99482. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  99483. ex -= depth2 * nx;
  99484. ey -= depth2 * ny;
  99485. ez -= depth2 * nz;
  99486. dx = c1x - sx;
  99487. dy = c1y - sy;
  99488. dz = c1z - sz;
  99489. tx = ex - sx;
  99490. ty = ey - sy;
  99491. tz = ez - sz;
  99492. a = dx * dx + dy * dy + dz * dz;
  99493. b = dx * tx + dy * ty + dz * tz;
  99494. e = tx * tx + ty * ty + tz * tz;
  99495. f = b * b - e * (a - r1 * r1);
  99496. if (f < 0) break;
  99497. f = OIMO.sqrt(f);
  99498. t1 = (b + f) / e;
  99499. t2 = (b - f) / e;
  99500. if (t2 < t1) {
  99501. len = t1;
  99502. t1 = t2;
  99503. t2 = len;
  99504. }
  99505. if (t2 > 1) t2 = 1;
  99506. if (t1 < 0) t1 = 0;
  99507. tx = sx + (ex - sx) * t1;
  99508. ty = sy + (ey - sy) * t1;
  99509. tz = sz + (ez - sz) * t1;
  99510. ex = sx + (ex - sx) * t2;
  99511. ey = sy + (ey - sy) * t2;
  99512. ez = sz + (ez - sz) * t2;
  99513. sx = tx;
  99514. sy = ty;
  99515. sz = tz;
  99516. len = depth1 + (depth2 - depth1) * t1;
  99517. depth2 = depth1 + (depth2 - depth1) * t2;
  99518. depth1 = len;
  99519. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  99520. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  99521. }
  99522. break;
  99523. case 2:
  99524. if (right2) {
  99525. c2x = p2x - d2x;
  99526. c2y = p2y - d2y;
  99527. c2z = p2z - d2z;
  99528. nx = -n2x;
  99529. ny = -n2y;
  99530. nz = -n2z;
  99531. } else {
  99532. c2x = p2x + d2x;
  99533. c2y = p2y + d2y;
  99534. c2z = p2z + d2z;
  99535. nx = n2x;
  99536. ny = n2y;
  99537. nz = n2z;
  99538. }
  99539. dot = nx * n1x + ny * n1y + nz * n1z;
  99540. if (dot < 0) len = h1;
  99541. else len = -h1;
  99542. c1x = p1x + len * n1x;
  99543. c1y = p1y + len * n1y;
  99544. c1z = p1z + len * n1z;
  99545. if (dot1 >= 0.999999) {
  99546. tx = -ny;
  99547. ty = nz;
  99548. tz = nx;
  99549. } else {
  99550. tx = nx;
  99551. ty = ny;
  99552. tz = nz;
  99553. }
  99554. len = tx * n1x + ty * n1y + tz * n1z;
  99555. dx = len * n1x - tx;
  99556. dy = len * n1y - ty;
  99557. dz = len * n1z - tz;
  99558. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  99559. if (len == 0) break;
  99560. len = r1 / len;
  99561. dx *= len;
  99562. dy *= len;
  99563. dz *= len;
  99564. tx = c1x + dx;
  99565. ty = c1y + dy;
  99566. tz = c1z + dz;
  99567. if (dot < -0.96 || dot > 0.96) {
  99568. r00 = n1x * n1x * 1.5 - 0.5;
  99569. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  99570. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  99571. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  99572. r11 = n1y * n1y * 1.5 - 0.5;
  99573. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  99574. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  99575. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  99576. r22 = n1z * n1z * 1.5 - 0.5;
  99577. px = tx;
  99578. py = ty;
  99579. pz = tz;
  99580. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  99581. tx = px - pd * nx - c2x;
  99582. ty = py - pd * ny - c2y;
  99583. tz = pz - pd * nz - c2z;
  99584. len = tx * tx + ty * ty + tz * tz;
  99585. if (len > r2 * r2) {
  99586. len = r2 / OIMO.sqrt(len);
  99587. tx *= len;
  99588. ty *= len;
  99589. tz *= len;
  99590. }
  99591. px = c2x + tx;
  99592. py = c2y + ty;
  99593. pz = c2z + tz;
  99594. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  99595. px = dx * r00 + dy * r01 + dz * r02;
  99596. py = dx * r10 + dy * r11 + dz * r12;
  99597. pz = dx * r20 + dy * r21 + dz * r22;
  99598. px = (dx = px) + c1x;
  99599. py = (dy = py) + c1y;
  99600. pz = (dz = pz) + c1z;
  99601. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  99602. if (pd <= 0) {
  99603. tx = px - pd * nx - c2x;
  99604. ty = py - pd * ny - c2y;
  99605. tz = pz - pd * nz - c2z;
  99606. len = tx * tx + ty * ty + tz * tz;
  99607. if (len > r2 * r2) {
  99608. len = r2 / OIMO.sqrt(len);
  99609. tx *= len;
  99610. ty *= len;
  99611. tz *= len;
  99612. }
  99613. px = c2x + tx;
  99614. py = c2y + ty;
  99615. pz = c2z + tz;
  99616. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  99617. }
  99618. px = dx * r00 + dy * r01 + dz * r02;
  99619. py = dx * r10 + dy * r11 + dz * r12;
  99620. pz = dx * r20 + dy * r21 + dz * r22;
  99621. px = (dx = px) + c1x;
  99622. py = (dy = py) + c1y;
  99623. pz = (dz = pz) + c1z;
  99624. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  99625. if (pd <= 0) {
  99626. tx = px - pd * nx - c2x;
  99627. ty = py - pd * ny - c2y;
  99628. tz = pz - pd * nz - c2z;
  99629. len = tx * tx + ty * ty + tz * tz;
  99630. if (len > r2 * r2) {
  99631. len = r2 / OIMO.sqrt(len);
  99632. tx *= len;
  99633. ty *= len;
  99634. tz *= len;
  99635. }
  99636. px = c2x + tx;
  99637. py = c2y + ty;
  99638. pz = c2z + tz;
  99639. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  99640. }
  99641. } else {
  99642. sx = tx;
  99643. sy = ty;
  99644. sz = tz;
  99645. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  99646. sx -= depth1 * nx;
  99647. sy -= depth1 * ny;
  99648. sz -= depth1 * nz;
  99649. if (dot > 0) {
  99650. ex = tx + n1x * h1 * 2;
  99651. ey = ty + n1y * h1 * 2;
  99652. ez = tz + n1z * h1 * 2;
  99653. } else {
  99654. ex = tx - n1x * h1 * 2;
  99655. ey = ty - n1y * h1 * 2;
  99656. ez = tz - n1z * h1 * 2;
  99657. }
  99658. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  99659. ex -= depth2 * nx;
  99660. ey -= depth2 * ny;
  99661. ez -= depth2 * nz;
  99662. dx = c2x - sx;
  99663. dy = c2y - sy;
  99664. dz = c2z - sz;
  99665. tx = ex - sx;
  99666. ty = ey - sy;
  99667. tz = ez - sz;
  99668. a = dx * dx + dy * dy + dz * dz;
  99669. b = dx * tx + dy * ty + dz * tz;
  99670. e = tx * tx + ty * ty + tz * tz;
  99671. f = b * b - e * (a - r2 * r2);
  99672. if (f < 0) break;
  99673. f = OIMO.sqrt(f);
  99674. t1 = (b + f) / e;
  99675. t2 = (b - f) / e;
  99676. if (t2 < t1) {
  99677. len = t1;
  99678. t1 = t2;
  99679. t2 = len;
  99680. }
  99681. if (t2 > 1) t2 = 1;
  99682. if (t1 < 0) t1 = 0;
  99683. tx = sx + (ex - sx) * t1;
  99684. ty = sy + (ey - sy) * t1;
  99685. tz = sz + (ez - sz) * t1;
  99686. ex = sx + (ex - sx) * t2;
  99687. ey = sy + (ey - sy) * t2;
  99688. ez = sz + (ez - sz) * t2;
  99689. sx = tx;
  99690. sy = ty;
  99691. sz = tz;
  99692. len = depth1 + (depth2 - depth1) * t1;
  99693. depth2 = depth1 + (depth2 - depth1) * t2;
  99694. depth1 = len;
  99695. if (depth1 < 0) {
  99696. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  99697. }
  99698. if (depth2 < 0) {
  99699. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  99700. }
  99701. }
  99702. break;
  99703. }
  99704. };
  99705. OIMO.SphereCylinderCollisionDetector = function (flip) {
  99706. OIMO.CollisionDetector.call(this);
  99707. this.flip = flip;
  99708. };
  99709. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99710. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  99711. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99712. var s;
  99713. var c;
  99714. if (this.flip) {
  99715. s = shape2;
  99716. c = shape1;
  99717. } else {
  99718. s = shape1;
  99719. c = shape2;
  99720. }
  99721. var ps = s.position;
  99722. var psx = ps.x;
  99723. var psy = ps.y;
  99724. var psz = ps.z;
  99725. var pc = c.position;
  99726. var pcx = pc.x;
  99727. var pcy = pc.y;
  99728. var pcz = pc.z;
  99729. var dirx = c.normalDirection.x;
  99730. var diry = c.normalDirection.y;
  99731. var dirz = c.normalDirection.z;
  99732. var rads = s.radius;
  99733. var radc = c.radius;
  99734. var rad2 = rads + radc;
  99735. var halfh = c.halfHeight;
  99736. var dx = psx - pcx;
  99737. var dy = psy - pcy;
  99738. var dz = psz - pcz;
  99739. var dot = dx * dirx + dy * diry + dz * dirz;
  99740. if (dot < -halfh - rads || dot > halfh + rads) return;
  99741. var cx = pcx + dot * dirx;
  99742. var cy = pcy + dot * diry;
  99743. var cz = pcz + dot * dirz;
  99744. var d2x = psx - cx;
  99745. var d2y = psy - cy;
  99746. var d2z = psz - cz;
  99747. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  99748. if (len > rad2 * rad2) return;
  99749. if (len > radc * radc) {
  99750. len = radc / OIMO.sqrt(len);
  99751. d2x *= len;
  99752. d2y *= len;
  99753. d2z *= len;
  99754. }
  99755. if (dot < -halfh) dot = -halfh;
  99756. else if (dot > halfh) dot = halfh;
  99757. cx = pcx + dot * dirx + d2x;
  99758. cy = pcy + dot * diry + d2y;
  99759. cz = pcz + dot * dirz + d2z;
  99760. dx = cx - psx;
  99761. dy = cy - psy;
  99762. dz = cz - psz;
  99763. len = dx * dx + dy * dy + dz * dz;
  99764. var invLen;
  99765. if (len > 0 && len < rads * rads) {
  99766. len = OIMO.sqrt(len);
  99767. invLen = 1 / len;
  99768. dx *= invLen;
  99769. dy *= invLen;
  99770. dz *= invLen;
  99771. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  99772. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  99773. }
  99774. };
  99775. /**
  99776. * Class for checking collisions between 2 tetras,
  99777. * a shape that is made with 4 vertices and 4 faces
  99778. * arranged in triangles. With this algorigthm, soft
  99779. * body physics are possible and easier to implement.
  99780. * @author xprogram
  99781. */
  99782. OIMO.TetraTetraCollisionDetector = function () {
  99783. OIMO.CollisionDetector.call(this);
  99784. };
  99785. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99786. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  99787. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  99788. /*
  99789. * What we are doing:
  99790. * Each tetra is represented by four 3D triangles. The only
  99791. * quick way of finding if another tetra is within the other
  99792. * tetra is to see if a single vertex is within the triangles
  99793. * of the other tetra. So, for example, a tetra is represented
  99794. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  99795. * There is another tetra with a vertex A which was detected for
  99796. * collision by the broadphase. Now, if the point A is between ALL
  99797. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  99798. * is valid and we can pass point A to the manifold. Since the only
  99799. * points on the tetra are the 4 vertices, collision detection is
  99800. * not so complex. However, it can be time-consuming because we
  99801. * need to split the 3D triangles into three 2D triangles each for
  99802. * collision detection.
  99803. */
  99804. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  99805. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  99806. // fs is undeclared
  99807. var fs = fs1;
  99808. for (i = 0; i < 4; i++) {
  99809. vec = vs1[i];
  99810. for (j = 0; j < 4; j++) {
  99811. j1 = vs2[fs[i].a];
  99812. j2 = vs2[fs[i].b];
  99813. j3 = vs2[fs[i].c];
  99814. if (
  99815. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  99816. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  99817. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  99818. )
  99819. ts++;
  99820. if (ts === 4) // Only add point if it is inside all 4 triangles
  99821. manifold.addPoint(vec);
  99822. }
  99823. }
  99824. };
  99825. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  99826. function tricheck(p, p0, p1, p2) {
  99827. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  99828. var sg = A < 0 ? -1 : 1;
  99829. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  99830. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  99831. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  99832. }
  99833. function pt(x, y) { return { x: x, y: y }; }
  99834. /**
  99835. * An axis-aligned bounding box.
  99836. * @author saharan
  99837. * @author lo-th
  99838. */
  99839. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  99840. this.elements = new OIMO_ARRAY_TYPE(6);
  99841. var te = this.elements;
  99842. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  99843. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  99844. };
  99845. OIMO.AABB.prototype = {
  99846. constructor: OIMO.AABB,
  99847. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  99848. var te = this.elements;
  99849. te[0] = minX; te[3] = maxX;
  99850. te[1] = minY; te[4] = maxY;
  99851. te[2] = minZ; te[5] = maxZ;
  99852. return this;
  99853. },
  99854. intersectTest: function (aabb) {
  99855. var te = this.elements;
  99856. var ue = aabb.elements;
  99857. 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];
  99858. },
  99859. intersectTestTwo: function (aabb) {
  99860. var te = this.elements;
  99861. var ue = aabb.elements;
  99862. 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];
  99863. },
  99864. clone: function () {
  99865. return new this.constructor().fromArray(this.elements);
  99866. },
  99867. copy: function (aabb, margin) {
  99868. var m = margin || 0;
  99869. var me = aabb.elements;
  99870. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  99871. return this;
  99872. },
  99873. fromArray: function (array) {
  99874. this.elements.set(array);
  99875. return this;
  99876. },
  99877. // Set this AABB to the combined AABB of aabb1 and aabb2.
  99878. combine: function (aabb1, aabb2) {
  99879. var a = aabb1.elements;
  99880. var b = aabb2.elements;
  99881. var te = this.elements;
  99882. te[0] = a[0] < b[0] ? a[0] : b[0];
  99883. te[1] = a[1] < b[1] ? a[1] : b[1];
  99884. te[2] = a[2] < b[2] ? a[2] : b[2];
  99885. te[3] = a[3] > b[3] ? a[3] : b[3];
  99886. te[4] = a[4] > b[4] ? a[4] : b[4];
  99887. te[5] = a[5] > b[5] ? a[5] : b[5];
  99888. return this;
  99889. },
  99890. // Get the surface area.
  99891. surfaceArea: function () {
  99892. var te = this.elements;
  99893. var a = te[3] - te[0];
  99894. var h = te[4] - te[1];
  99895. var d = te[5] - te[2];
  99896. return 2 * (a * (h + d) + h * d);
  99897. },
  99898. // Get whether the AABB intersects with the point or not.
  99899. intersectsWithPoint: function (x, y, z) {
  99900. var te = this.elements;
  99901. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  99902. },
  99903. /**
  99904. * Set the AABB from an array
  99905. * of vertices. From THREE.
  99906. * @author mrdoob
  99907. * @author xprogram
  99908. */
  99909. setFromPoints: function (arr) {
  99910. this.makeEmpty();
  99911. for (var i = 0; i < arr.length; i++) {
  99912. this.expandByPoint(arr[i]);
  99913. }
  99914. },
  99915. makeEmpty: function () {
  99916. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  99917. },
  99918. expandByPoint: function (pt) {
  99919. var te = this.elements;
  99920. this.set(
  99921. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  99922. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  99923. );
  99924. }
  99925. };
  99926. /**
  99927. * A proxy is used for broad-phase collecting pairs that can be colliding.
  99928. */
  99929. OIMO.Proxy = function (shape) {
  99930. // The parent shape.
  99931. this.shape = shape;
  99932. // The axis-aligned bounding box.
  99933. this.aabb = shape.aabb;
  99934. };
  99935. OIMO.Proxy.prototype = {
  99936. constructor: OIMO.Proxy,
  99937. // Update the proxy.
  99938. update: function () {
  99939. OIMO.Error("Proxy", "Inheritance error.");
  99940. }
  99941. };
  99942. /**
  99943. * A basic implementation of proxies.
  99944. * @author saharan
  99945. */
  99946. OIMO.BasicProxy = function (shape) {
  99947. OIMO.Proxy.call(this, shape);
  99948. this.id = OIMO.proxyID++;
  99949. };
  99950. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  99951. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  99952. OIMO.BasicProxy.prototype.update = function () {
  99953. };
  99954. /**
  99955. * The broad-phase is used for collecting all possible pairs for collision.
  99956. */
  99957. OIMO.BroadPhase = function () {
  99958. this.types = OIMO.BR_NULL;
  99959. this.numPairChecks = 0;
  99960. this.numPairs = 0;
  99961. this.pairs = [];
  99962. };
  99963. OIMO.BroadPhase.prototype = {
  99964. constructor: OIMO.BroadPhase,
  99965. /**
  99966. * Create a new proxy.
  99967. * @param shape
  99968. * @return
  99969. */
  99970. createProxy: function (shape) {
  99971. OIMO.Error("BroadPhase", "Inheritance error.");
  99972. },
  99973. /**
  99974. * Add the proxy into the broad-phase.
  99975. * @param proxy
  99976. */
  99977. addProxy: function (proxy) {
  99978. OIMO.Error("BroadPhase", "Inheritance error.");
  99979. },
  99980. /**
  99981. * Remove the proxy from the broad-phase.
  99982. * @param proxy
  99983. */
  99984. removeProxy: function (proxy) {
  99985. OIMO.Error("BroadPhase", "Inheritance error.");
  99986. },
  99987. /**
  99988. * Returns whether the pair is available or not.
  99989. * @param s1
  99990. * @param s2
  99991. * @return
  99992. */
  99993. isAvailablePair: function (s1, s2) {
  99994. var b1 = s1.parent;
  99995. var b2 = s2.parent;
  99996. if (b1 == b2 || // same parents
  99997. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  99998. (s1.belongsTo & s2.collidesWith) == 0 ||
  99999. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  100000. ) { return false; }
  100001. var js;
  100002. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  100003. else js = b2.jointLink;
  100004. while (js !== null) {
  100005. var joint = js.joint;
  100006. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  100007. js = js.next;
  100008. }
  100009. return true;
  100010. },
  100011. // Detect overlapping pairs.
  100012. detectPairs: function () {
  100013. // clear old
  100014. this.pairs = [];
  100015. this.numPairs = 0;
  100016. this.numPairChecks = 0;
  100017. this.collectPairs();
  100018. },
  100019. collectPairs: function () {
  100020. OIMO.Error("BroadPhase", "Inheritance error.");
  100021. },
  100022. addPair: function (s1, s2) {
  100023. var pair = new OIMO.Pair(s1, s2);
  100024. this.pairs.push(pair);
  100025. this.numPairs++;
  100026. }
  100027. };
  100028. /**
  100029. * A broad-phase algorithm with brute-force search.
  100030. * This always checks for all possible pairs.
  100031. */
  100032. OIMO.BruteForceBroadPhase = function () {
  100033. OIMO.BroadPhase.call(this);
  100034. this.types = OIMO.BR_BRUTE_FORCE;;
  100035. //this.numProxies=0;
  100036. ///this.maxProxies = 256;
  100037. this.proxies = [];
  100038. //this.proxies.length = 256;
  100039. };
  100040. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  100041. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  100042. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  100043. return new OIMO.BasicProxy(shape);
  100044. };
  100045. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  100046. /*if(this.numProxies==this.maxProxies){
  100047. //this.maxProxies<<=1;
  100048. this.maxProxies*=2;
  100049. var newProxies=[];
  100050. newProxies.length = this.maxProxies;
  100051. var i = this.numProxies;
  100052. while(i--){
  100053. //for(var i=0, l=this.numProxies;i<l;i++){
  100054. newProxies[i]=this.proxies[i];
  100055. }
  100056. this.proxies=newProxies;
  100057. }*/
  100058. //this.proxies[this.numProxies++] = proxy;
  100059. this.proxies.push(proxy);
  100060. //this.numProxies++;
  100061. };
  100062. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  100063. var n = this.proxies.indexOf(proxy);
  100064. if (n > -1) {
  100065. this.proxies.splice(n, 1);
  100066. //this.numProxies--;
  100067. }
  100068. /*var i = this.numProxies;
  100069. while(i--){
  100070. //for(var i=0, l=this.numProxies;i<l;i++){
  100071. if(this.proxies[i] == proxy){
  100072. this.proxies[i] = this.proxies[--this.numProxies];
  100073. this.proxies[this.numProxies] = null;
  100074. return;
  100075. }
  100076. }*/
  100077. };
  100078. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  100079. var i = 0, j, p1, p2;
  100080. var px = this.proxies;
  100081. var l = px.length;//this.numProxies;
  100082. //var ar1 = [];
  100083. //var ar2 = [];
  100084. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  100085. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  100086. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  100087. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  100088. this.numPairChecks = l * (l - 1) >> 1;
  100089. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  100090. while (i < l) {
  100091. p1 = px[i++];
  100092. j = i + 1;
  100093. while (j < l) {
  100094. p2 = px[j++];
  100095. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  100096. this.addPair(p1.shape, p2.shape);
  100097. }
  100098. }
  100099. };
  100100. /**
  100101. * A pair of shapes that may collide.
  100102. * @author saharan
  100103. */
  100104. OIMO.Pair = function (s1, s2) {
  100105. // The first shape.
  100106. this.shape1 = s1 || null;
  100107. // The second shape.
  100108. this.shape2 = s2 || null;
  100109. };
  100110. /**
  100111. * A projection axis for sweep and prune broad-phase.
  100112. * @author saharan
  100113. */
  100114. OIMO.SAPAxis = function () {
  100115. this.numElements = 0;
  100116. this.bufferSize = 256;
  100117. this.elements = [];
  100118. this.elements.length = this.bufferSize;
  100119. this.stack = new OIMO_ARRAY_TYPE(64);
  100120. };
  100121. OIMO.SAPAxis.prototype = {
  100122. constructor: OIMO.SAPAxis,
  100123. addElements: function (min, max) {
  100124. if (this.numElements + 2 >= this.bufferSize) {
  100125. //this.bufferSize<<=1;
  100126. this.bufferSize *= 2;
  100127. var newElements = [];
  100128. var i = this.numElements;
  100129. while (i--) {
  100130. //for(var i=0, l=this.numElements; i<l; i++){
  100131. newElements[i] = this.elements[i];
  100132. }
  100133. }
  100134. this.elements[this.numElements++] = min;
  100135. this.elements[this.numElements++] = max;
  100136. },
  100137. removeElements: function (min, max) {
  100138. var minIndex = -1;
  100139. var maxIndex = -1;
  100140. for (var i = 0, l = this.numElements; i < l; i++) {
  100141. var e = this.elements[i];
  100142. if (e == min || e == max) {
  100143. if (minIndex == -1) {
  100144. minIndex = i;
  100145. } else {
  100146. maxIndex = i;
  100147. break;
  100148. }
  100149. }
  100150. }
  100151. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  100152. this.elements[i - 1] = this.elements[i];
  100153. }
  100154. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  100155. this.elements[i - 2] = this.elements[i];
  100156. }
  100157. this.elements[--this.numElements] = null;
  100158. this.elements[--this.numElements] = null;
  100159. },
  100160. sort: function () {
  100161. var count = 0;
  100162. var threshold = 1;
  100163. while ((this.numElements >> threshold) != 0) threshold++;
  100164. threshold = threshold * this.numElements >> 2;
  100165. count = 0;
  100166. var giveup = false;
  100167. var elements = this.elements;
  100168. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  100169. var tmp = elements[i];
  100170. var pivot = tmp.value;
  100171. var tmp2 = elements[i - 1];
  100172. if (tmp2.value > pivot) {
  100173. var j = i;
  100174. do {
  100175. elements[j] = tmp2;
  100176. if (--j == 0) break;
  100177. tmp2 = elements[j - 1];
  100178. } while (tmp2.value > pivot);
  100179. elements[j] = tmp;
  100180. count += i - j;
  100181. if (count > threshold) {
  100182. giveup = true; // stop and use quick sort
  100183. break;
  100184. }
  100185. }
  100186. }
  100187. if (!giveup) return;
  100188. count = 2; var stack = this.stack;
  100189. stack[0] = 0;
  100190. stack[1] = this.numElements - 1;
  100191. while (count > 0) {
  100192. var right = stack[--count];
  100193. var left = stack[--count];
  100194. var diff = right - left;
  100195. if (diff > 16) { // quick sort
  100196. //var mid=left+(diff>>1);
  100197. var mid = left + (OIMO.floor(diff * 0.5));
  100198. tmp = elements[mid];
  100199. elements[mid] = elements[right];
  100200. elements[right] = tmp;
  100201. pivot = tmp.value;
  100202. i = left - 1;
  100203. j = right;
  100204. while (true) {
  100205. var ei;
  100206. var ej;
  100207. do { ei = elements[++i]; } while (ei.value < pivot);
  100208. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  100209. if (i >= j) break;
  100210. elements[i] = ej;
  100211. elements[j] = ei;
  100212. }
  100213. elements[right] = elements[i];
  100214. elements[i] = tmp;
  100215. if (i - left > right - i) {
  100216. stack[count++] = left;
  100217. stack[count++] = i - 1;
  100218. stack[count++] = i + 1;
  100219. stack[count++] = right;
  100220. } else {
  100221. stack[count++] = i + 1;
  100222. stack[count++] = right;
  100223. stack[count++] = left;
  100224. stack[count++] = i - 1;
  100225. }
  100226. } else {
  100227. for (i = left + 1; i <= right; i++) {
  100228. tmp = elements[i];
  100229. pivot = tmp.value;
  100230. tmp2 = elements[i - 1];
  100231. if (tmp2.value > pivot) {
  100232. j = i;
  100233. do {
  100234. elements[j] = tmp2;
  100235. if (--j == 0) break;
  100236. tmp2 = elements[j - 1];
  100237. } while (tmp2.value > pivot);
  100238. elements[j] = tmp;
  100239. }
  100240. }
  100241. }
  100242. }
  100243. },
  100244. calculateTestCount: function () {
  100245. var num = 1;
  100246. var sum = 0;
  100247. for (var i = 1, l = this.numElements; i < l; i++) {
  100248. if (this.elements[i].max) {
  100249. num--;
  100250. } else {
  100251. sum += num;
  100252. num++;
  100253. }
  100254. }
  100255. return sum;
  100256. }
  100257. }
  100258. /**
  100259. * A broad-phase collision detection algorithm using sweep and prune.
  100260. * @author saharan
  100261. * @author lo-th
  100262. */
  100263. OIMO.SAPBroadPhase = function () {
  100264. OIMO.BroadPhase.call(this);
  100265. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  100266. this.numElementsD = 0;
  100267. this.numElementsS = 0;
  100268. // dynamic proxies
  100269. this.axesD = [
  100270. new OIMO.SAPAxis(),
  100271. new OIMO.SAPAxis(),
  100272. new OIMO.SAPAxis()
  100273. ];
  100274. // static or sleeping proxies
  100275. this.axesS = [
  100276. new OIMO.SAPAxis(),
  100277. new OIMO.SAPAxis(),
  100278. new OIMO.SAPAxis()
  100279. ];
  100280. this.index1 = 0;
  100281. this.index2 = 1;
  100282. };
  100283. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  100284. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  100285. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  100286. return new OIMO.SAPProxy(this, shape);
  100287. };
  100288. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  100289. var p = proxy;
  100290. if (p.isDynamic()) {
  100291. this.axesD[0].addElements(p.min[0], p.max[0]);
  100292. this.axesD[1].addElements(p.min[1], p.max[1]);
  100293. this.axesD[2].addElements(p.min[2], p.max[2]);
  100294. p.belongsTo = 1;
  100295. this.numElementsD += 2;
  100296. } else {
  100297. this.axesS[0].addElements(p.min[0], p.max[0]);
  100298. this.axesS[1].addElements(p.min[1], p.max[1]);
  100299. this.axesS[2].addElements(p.min[2], p.max[2]);
  100300. p.belongsTo = 2;
  100301. this.numElementsS += 2;
  100302. }
  100303. };
  100304. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  100305. var p = proxy;
  100306. if (p.belongsTo == 0) return;
  100307. /*else if ( p.belongsTo == 1 ) {
  100308. this.axesD[0].removeElements( p.min[0], p.max[0] );
  100309. this.axesD[1].removeElements( p.min[1], p.max[1] );
  100310. this.axesD[2].removeElements( p.min[2], p.max[2] );
  100311. this.numElementsD -= 2;
  100312. } else if ( p.belongsTo == 2 ) {
  100313. this.axesS[0].removeElements( p.min[0], p.max[0] );
  100314. this.axesS[1].removeElements( p.min[1], p.max[1] );
  100315. this.axesS[2].removeElements( p.min[2], p.max[2] );
  100316. this.numElementsS -= 2;
  100317. }*/
  100318. switch (p.belongsTo) {
  100319. case 1:
  100320. this.axesD[0].removeElements(p.min[0], p.max[0]);
  100321. this.axesD[1].removeElements(p.min[1], p.max[1]);
  100322. this.axesD[2].removeElements(p.min[2], p.max[2]);
  100323. this.numElementsD -= 2;
  100324. break;
  100325. case 2:
  100326. this.axesS[0].removeElements(p.min[0], p.max[0]);
  100327. this.axesS[1].removeElements(p.min[1], p.max[1]);
  100328. this.axesS[2].removeElements(p.min[2], p.max[2]);
  100329. this.numElementsS -= 2;
  100330. break;
  100331. }
  100332. p.belongsTo = 0;
  100333. };
  100334. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  100335. if (this.numElementsD == 0) return;
  100336. var axis1 = this.axesD[this.index1];
  100337. var axis2 = this.axesD[this.index2];
  100338. axis1.sort();
  100339. axis2.sort();
  100340. var count1 = axis1.calculateTestCount();
  100341. var count2 = axis2.calculateTestCount();
  100342. var elementsD;
  100343. var elementsS;
  100344. if (count1 <= count2) {// select the best axis
  100345. axis2 = this.axesS[this.index1];
  100346. axis2.sort();
  100347. elementsD = axis1.elements;
  100348. elementsS = axis2.elements;
  100349. } else {
  100350. axis1 = this.axesS[this.index2];
  100351. axis1.sort();
  100352. elementsD = axis2.elements;
  100353. elementsS = axis1.elements;
  100354. this.index1 ^= this.index2;
  100355. this.index2 ^= this.index1;
  100356. this.index1 ^= this.index2;
  100357. }
  100358. var activeD;
  100359. var activeS;
  100360. var p = 0;
  100361. var q = 0;
  100362. while (p < this.numElementsD) {
  100363. var e1;
  100364. var dyn;
  100365. if (q == this.numElementsS) {
  100366. e1 = elementsD[p];
  100367. dyn = true;
  100368. p++;
  100369. } else {
  100370. var d = elementsD[p];
  100371. var s = elementsS[q];
  100372. if (d.value < s.value) {
  100373. e1 = d;
  100374. dyn = true;
  100375. p++;
  100376. } else {
  100377. e1 = s;
  100378. dyn = false;
  100379. q++;
  100380. }
  100381. }
  100382. if (!e1.max) {
  100383. var s1 = e1.proxy.shape;
  100384. var min1 = e1.min1.value;
  100385. var max1 = e1.max1.value;
  100386. var min2 = e1.min2.value;
  100387. var max2 = e1.max2.value;
  100388. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  100389. var s2 = e2.proxy.shape;
  100390. this.numPairChecks++;
  100391. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  100392. this.addPair(s1, s2);
  100393. }
  100394. if (dyn) {
  100395. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  100396. s2 = e2.proxy.shape;
  100397. this.numPairChecks++;
  100398. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  100399. this.addPair(s1, s2);
  100400. }
  100401. e1.pair = activeD;
  100402. activeD = e1;
  100403. } else {
  100404. e1.pair = activeS;
  100405. activeS = e1;
  100406. }
  100407. } else {
  100408. var min = e1.pair;
  100409. if (dyn) {
  100410. if (min == activeD) {
  100411. activeD = activeD.pair;
  100412. continue;
  100413. } else {
  100414. e1 = activeD;
  100415. }
  100416. } else {
  100417. if (min == activeS) {
  100418. activeS = activeS.pair;
  100419. continue;
  100420. } else {
  100421. e1 = activeS;
  100422. }
  100423. }
  100424. do {
  100425. e2 = e1.pair;
  100426. if (e2 == min) {
  100427. e1.pair = e2.pair;
  100428. break;
  100429. }
  100430. e1 = e2;
  100431. } while (e1 != null);
  100432. }
  100433. }
  100434. this.index2 = (this.index1 | this.index2) ^ 3;
  100435. };
  100436. /**
  100437. * An element of proxies.
  100438. * @author saharan
  100439. */
  100440. OIMO.SAPElement = function (proxy, max) {
  100441. // The parent proxy
  100442. this.proxy = proxy;
  100443. // The pair element.
  100444. this.pair = null;
  100445. // The minimum element on other axis.
  100446. this.min1 = null;
  100447. // The maximum element on other axis.
  100448. this.max1 = null;
  100449. // The minimum element on other axis.
  100450. this.min2 = null;
  100451. // The maximum element on other axis.
  100452. this.max2 = null;
  100453. // Whether the element has maximum value or not.
  100454. this.max = max;
  100455. // The value of the element.
  100456. this.value = 0;
  100457. };
  100458. /**
  100459. * A proxy for sweep and prune broad-phase.
  100460. * @author saharan
  100461. * @author lo-th
  100462. */
  100463. OIMO.SAPProxy = function (sap, shape) {
  100464. OIMO.Proxy.call(this, shape);
  100465. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  100466. this.belongsTo = 0;
  100467. // The maximum elements on each axis.
  100468. this.max = [];
  100469. // The minimum elements on each axis.
  100470. this.min = [];
  100471. this.sap = sap;
  100472. this.min[0] = new OIMO.SAPElement(this, false);
  100473. this.max[0] = new OIMO.SAPElement(this, true);
  100474. this.min[1] = new OIMO.SAPElement(this, false);
  100475. this.max[1] = new OIMO.SAPElement(this, true);
  100476. this.min[2] = new OIMO.SAPElement(this, false);
  100477. this.max[2] = new OIMO.SAPElement(this, true);
  100478. this.max[0].pair = this.min[0];
  100479. this.max[1].pair = this.min[1];
  100480. this.max[2].pair = this.min[2];
  100481. this.min[0].min1 = this.min[1];
  100482. this.min[0].max1 = this.max[1];
  100483. this.min[0].min2 = this.min[2];
  100484. this.min[0].max2 = this.max[2];
  100485. this.min[1].min1 = this.min[0];
  100486. this.min[1].max1 = this.max[0];
  100487. this.min[1].min2 = this.min[2];
  100488. this.min[1].max2 = this.max[2];
  100489. this.min[2].min1 = this.min[0];
  100490. this.min[2].max1 = this.max[0];
  100491. this.min[2].min2 = this.min[1];
  100492. this.min[2].max2 = this.max[1];
  100493. };
  100494. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  100495. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  100496. // Returns whether the proxy is dynamic or not.
  100497. OIMO.SAPProxy.prototype.isDynamic = function () {
  100498. var body = this.shape.parent;
  100499. return body.isDynamic && !body.sleeping;
  100500. };
  100501. OIMO.SAPProxy.prototype.update = function () {
  100502. var te = this.aabb.elements;
  100503. this.min[0].value = te[0];
  100504. this.min[1].value = te[1];
  100505. this.min[2].value = te[2];
  100506. this.max[0].value = te[3];
  100507. this.max[1].value = te[4];
  100508. this.max[2].value = te[5];
  100509. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  100510. this.sap.removeProxy(this);
  100511. this.sap.addProxy(this);
  100512. }
  100513. };
  100514. /**
  100515. * A dynamic bounding volume tree for the broad-phase algorithm.
  100516. * @author saharan
  100517. * @author lo-th
  100518. */
  100519. OIMO.DBVT = function () {
  100520. // The root of the tree.
  100521. this.root = null;
  100522. this.freeNodes = [];
  100523. this.freeNodes.length = 16384;
  100524. this.numFreeNodes = 0;
  100525. this.aabb = new OIMO.AABB();
  100526. };
  100527. OIMO.DBVT.prototype = {
  100528. constructor: OIMO.DBVT,
  100529. /**
  100530. * Move a leaf.
  100531. * @param leaf
  100532. */
  100533. moveLeaf: function (leaf) {
  100534. this.deleteLeaf(leaf);
  100535. this.insertLeaf(leaf);
  100536. },
  100537. /**
  100538. * Insert a leaf to the tree.
  100539. * @param node
  100540. */
  100541. insertLeaf: function (leaf) {
  100542. if (this.root == null) {
  100543. this.root = leaf;
  100544. return;
  100545. }
  100546. var lb = leaf.aabb;
  100547. var sibling = this.root;
  100548. var oldArea;
  100549. var newArea;
  100550. while (sibling.proxy == null) { // descend the node to search the best pair
  100551. var c1 = sibling.child1;
  100552. var c2 = sibling.child2;
  100553. var b = sibling.aabb;
  100554. var c1b = c1.aabb;
  100555. var c2b = c2.aabb;
  100556. oldArea = b.surfaceArea();
  100557. this.aabb.combine(lb, b);
  100558. newArea = this.aabb.surfaceArea();
  100559. var creatingCost = newArea * 2;
  100560. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  100561. var discendingCost1 = incrementalCost;
  100562. this.aabb.combine(lb, c1b);
  100563. if (c1.proxy != null) {
  100564. // leaf cost = area(combined aabb)
  100565. discendingCost1 += this.aabb.surfaceArea();
  100566. } else {
  100567. // node cost = area(combined aabb) - area(old aabb)
  100568. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  100569. }
  100570. var discendingCost2 = incrementalCost;
  100571. this.aabb.combine(lb, c2b);
  100572. if (c2.proxy != null) {
  100573. // leaf cost = area(combined aabb)
  100574. discendingCost2 += this.aabb.surfaceArea();
  100575. } else {
  100576. // node cost = area(combined aabb) - area(old aabb)
  100577. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  100578. }
  100579. if (discendingCost1 < discendingCost2) {
  100580. if (creatingCost < discendingCost1) {
  100581. break;// stop descending
  100582. } else {
  100583. sibling = c1;// descend into first child
  100584. }
  100585. } else {
  100586. if (creatingCost < discendingCost2) {
  100587. break;// stop descending
  100588. } else {
  100589. sibling = c2;// descend into second child
  100590. }
  100591. }
  100592. }
  100593. var oldParent = sibling.parent;
  100594. var newParent;
  100595. if (this.numFreeNodes > 0) {
  100596. newParent = this.freeNodes[--this.numFreeNodes];
  100597. } else {
  100598. newParent = new OIMO.DBVTNode();
  100599. }
  100600. newParent.parent = oldParent;
  100601. newParent.child1 = leaf;
  100602. newParent.child2 = sibling;
  100603. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  100604. newParent.height = sibling.height + 1;
  100605. sibling.parent = newParent;
  100606. leaf.parent = newParent;
  100607. if (sibling == this.root) {
  100608. // replace root
  100609. this.root = newParent;
  100610. } else {
  100611. // replace child
  100612. if (oldParent.child1 == sibling) {
  100613. oldParent.child1 = newParent;
  100614. } else {
  100615. oldParent.child2 = newParent;
  100616. }
  100617. }
  100618. // update whole tree
  100619. do {
  100620. newParent = this.balance(newParent);
  100621. this.fix(newParent);
  100622. newParent = newParent.parent;
  100623. } while (newParent != null);
  100624. },
  100625. getBalance: function (node) {
  100626. if (node.proxy != null) return 0;
  100627. return node.child1.height - node.child2.height;
  100628. },
  100629. /*print:function(node,indent,text){
  100630. var hasChild=node.proxy==null;
  100631. if(hasChild)text=this.print(node.child1,indent+1,text);
  100632. for(var i=indent*2;i>=0;i--){
  100633. text+=" ";
  100634. }
  100635. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  100636. if(hasChild)text=this.print(node.child2,indent+1,text);
  100637. return text;
  100638. },*/
  100639. /**
  100640. * Delete a leaf from the tree.
  100641. * @param node
  100642. */
  100643. deleteLeaf: function (leaf) {
  100644. if (leaf == this.root) {
  100645. this.root = null;
  100646. return;
  100647. }
  100648. var parent = leaf.parent;
  100649. var sibling;
  100650. if (parent.child1 == leaf) {
  100651. sibling = parent.child2;
  100652. } else {
  100653. sibling = parent.child1;
  100654. }
  100655. if (parent == this.root) {
  100656. this.root = sibling;
  100657. sibling.parent = null;
  100658. return;
  100659. }
  100660. var grandParent = parent.parent;
  100661. sibling.parent = grandParent;
  100662. if (grandParent.child1 == parent) {
  100663. grandParent.child1 = sibling;
  100664. } else {
  100665. grandParent.child2 = sibling;
  100666. }
  100667. if (this.numFreeNodes < 16384) {
  100668. this.freeNodes[this.numFreeNodes++] = parent;
  100669. }
  100670. do {
  100671. grandParent = this.balance(grandParent);
  100672. this.fix(grandParent);
  100673. grandParent = grandParent.parent;
  100674. } while (grandParent != null);
  100675. },
  100676. balance: function (node) {
  100677. var nh = node.height;
  100678. if (nh < 2) {
  100679. return node;
  100680. }
  100681. var p = node.parent;
  100682. var l = node.child1;
  100683. var r = node.child2;
  100684. var lh = l.height;
  100685. var rh = r.height;
  100686. var balance = lh - rh;
  100687. var t;// for bit operation
  100688. // [ N ]
  100689. // / \
  100690. // [ L ] [ R ]
  100691. // / \ / \
  100692. // [L-L] [L-R] [R-L] [R-R]
  100693. // Is the tree balanced?
  100694. if (balance > 1) {
  100695. var ll = l.child1;
  100696. var lr = l.child2;
  100697. var llh = ll.height;
  100698. var lrh = lr.height;
  100699. // Is L-L higher than L-R?
  100700. if (llh > lrh) {
  100701. // set N to L-R
  100702. l.child2 = node;
  100703. node.parent = l;
  100704. // [ L ]
  100705. // / \
  100706. // [L-L] [ N ]
  100707. // / \ / \
  100708. // [...] [...] [ L ] [ R ]
  100709. // set L-R
  100710. node.child1 = lr;
  100711. lr.parent = node;
  100712. // [ L ]
  100713. // / \
  100714. // [L-L] [ N ]
  100715. // / \ / \
  100716. // [...] [...] [L-R] [ R ]
  100717. // fix bounds and heights
  100718. node.aabb.combine(lr.aabb, r.aabb);
  100719. t = lrh - rh;
  100720. node.height = lrh - (t & t >> 31) + 1;
  100721. l.aabb.combine(ll.aabb, node.aabb);
  100722. t = llh - nh;
  100723. l.height = llh - (t & t >> 31) + 1;
  100724. } else {
  100725. // set N to L-L
  100726. l.child1 = node;
  100727. node.parent = l;
  100728. // [ L ]
  100729. // / \
  100730. // [ N ] [L-R]
  100731. // / \ / \
  100732. // [ L ] [ R ] [...] [...]
  100733. // set L-L
  100734. node.child1 = ll;
  100735. ll.parent = node;
  100736. // [ L ]
  100737. // / \
  100738. // [ N ] [L-R]
  100739. // / \ / \
  100740. // [L-L] [ R ] [...] [...]
  100741. // fix bounds and heights
  100742. node.aabb.combine(ll.aabb, r.aabb);
  100743. t = llh - rh;
  100744. node.height = llh - (t & t >> 31) + 1;
  100745. l.aabb.combine(node.aabb, lr.aabb);
  100746. t = nh - lrh;
  100747. l.height = nh - (t & t >> 31) + 1;
  100748. }
  100749. // set new parent of L
  100750. if (p != null) {
  100751. if (p.child1 == node) {
  100752. p.child1 = l;
  100753. } else {
  100754. p.child2 = l;
  100755. }
  100756. } else {
  100757. this.root = l;
  100758. }
  100759. l.parent = p;
  100760. return l;
  100761. } else if (balance < -1) {
  100762. var rl = r.child1;
  100763. var rr = r.child2;
  100764. var rlh = rl.height;
  100765. var rrh = rr.height;
  100766. // Is R-L higher than R-R?
  100767. if (rlh > rrh) {
  100768. // set N to R-R
  100769. r.child2 = node;
  100770. node.parent = r;
  100771. // [ R ]
  100772. // / \
  100773. // [R-L] [ N ]
  100774. // / \ / \
  100775. // [...] [...] [ L ] [ R ]
  100776. // set R-R
  100777. node.child2 = rr;
  100778. rr.parent = node;
  100779. // [ R ]
  100780. // / \
  100781. // [R-L] [ N ]
  100782. // / \ / \
  100783. // [...] [...] [ L ] [R-R]
  100784. // fix bounds and heights
  100785. node.aabb.combine(l.aabb, rr.aabb);
  100786. t = lh - rrh;
  100787. node.height = lh - (t & t >> 31) + 1;
  100788. r.aabb.combine(rl.aabb, node.aabb);
  100789. t = rlh - nh;
  100790. r.height = rlh - (t & t >> 31) + 1;
  100791. } else {
  100792. // set N to R-L
  100793. r.child1 = node;
  100794. node.parent = r;
  100795. // [ R ]
  100796. // / \
  100797. // [ N ] [R-R]
  100798. // / \ / \
  100799. // [ L ] [ R ] [...] [...]
  100800. // set R-L
  100801. node.child2 = rl;
  100802. rl.parent = node;
  100803. // [ R ]
  100804. // / \
  100805. // [ N ] [R-R]
  100806. // / \ / \
  100807. // [ L ] [R-L] [...] [...]
  100808. // fix bounds and heights
  100809. node.aabb.combine(l.aabb, rl.aabb);
  100810. t = lh - rlh;
  100811. node.height = lh - (t & t >> 31) + 1;
  100812. r.aabb.combine(node.aabb, rr.aabb);
  100813. t = nh - rrh;
  100814. r.height = nh - (t & t >> 31) + 1;
  100815. }
  100816. // set new parent of R
  100817. if (p != null) {
  100818. if (p.child1 == node) {
  100819. p.child1 = r;
  100820. } else {
  100821. p.child2 = r;
  100822. }
  100823. } else {
  100824. this.root = r;
  100825. }
  100826. r.parent = p;
  100827. return r;
  100828. }
  100829. return node;
  100830. },
  100831. fix: function (node) {
  100832. var c1 = node.child1;
  100833. var c2 = node.child2;
  100834. node.aabb.combine(c1.aabb, c2.aabb);
  100835. //var h1 = c1.height;
  100836. //var h2 = c2.height;
  100837. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  100838. /*if( h1 < h2 ) {
  100839. node.height = h2+1;
  100840. }else{
  100841. node.height = h1+1;
  100842. }*/
  100843. }
  100844. }
  100845. /**
  100846. * A broad-phase algorithm using dynamic bounding volume tree.
  100847. * @author saharan
  100848. * @author lo-th
  100849. */
  100850. OIMO.DBVTBroadPhase = function () {
  100851. OIMO.BroadPhase.call(this);
  100852. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  100853. this.tree = new OIMO.DBVT();
  100854. this.stack = [];
  100855. this.leaves = [];
  100856. this.numLeaves = 0;
  100857. };
  100858. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  100859. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  100860. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  100861. return new OIMO.DBVTProxy(shape);
  100862. };
  100863. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  100864. this.tree.insertLeaf(proxy.leaf);
  100865. this.leaves.push(proxy.leaf);
  100866. this.numLeaves++;
  100867. };
  100868. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  100869. this.tree.deleteLeaf(proxy.leaf);
  100870. var n = this.leaves.indexOf(proxy.leaf);
  100871. if (n > -1) {
  100872. this.leaves.splice(n, 1);
  100873. this.numLeaves--;
  100874. }
  100875. };
  100876. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  100877. if (this.numLeaves < 2) return;
  100878. var leaf, margin = 0.1, i = this.numLeaves;
  100879. while (i--) {
  100880. leaf = this.leaves[i];
  100881. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  100882. leaf.aabb.copy(leaf.proxy.aabb, margin);
  100883. this.tree.deleteLeaf(leaf);
  100884. this.tree.insertLeaf(leaf);
  100885. this.collide(leaf, this.tree.root);
  100886. }
  100887. }
  100888. };
  100889. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  100890. var stackCount = 2;
  100891. var s1, s2, n1, n2, l1, l2;
  100892. this.stack[0] = node1;
  100893. this.stack[1] = node2;
  100894. while (stackCount > 0) {
  100895. n1 = this.stack[--stackCount];
  100896. n2 = this.stack[--stackCount];
  100897. l1 = n1.proxy != null;
  100898. l2 = n2.proxy != null;
  100899. this.numPairChecks++;
  100900. if (l1 && l2) {
  100901. s1 = n1.proxy.shape;
  100902. s2 = n2.proxy.shape;
  100903. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  100904. this.addPair(s1, s2);
  100905. } else {
  100906. if (n1.aabb.intersectTest(n2.aabb)) continue;
  100907. /*if(stackCount+4>=this.maxStack){// expand the stack
  100908. //this.maxStack<<=1;
  100909. this.maxStack*=2;
  100910. var newStack = [];// vector
  100911. newStack.length = this.maxStack;
  100912. for(var i=0;i<stackCount;i++){
  100913. newStack[i] = this.stack[i];
  100914. }
  100915. this.stack = newStack;
  100916. }*/
  100917. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  100918. this.stack[stackCount++] = n1.child1;
  100919. this.stack[stackCount++] = n2;
  100920. this.stack[stackCount++] = n1.child2;
  100921. this.stack[stackCount++] = n2;
  100922. } else {
  100923. this.stack[stackCount++] = n1;
  100924. this.stack[stackCount++] = n2.child1;
  100925. this.stack[stackCount++] = n1;
  100926. this.stack[stackCount++] = n2.child2;
  100927. }
  100928. }
  100929. }
  100930. };
  100931. /**
  100932. * A node of the dynamic bounding volume tree.
  100933. * @author saharan
  100934. */
  100935. OIMO.DBVTNode = function () {
  100936. // The first child node of this node.
  100937. this.child1 = null;
  100938. // The second child node of this node.
  100939. this.child2 = null;
  100940. // The parent node of this tree.
  100941. this.parent = null;
  100942. // The proxy of this node. This has no value if this node is not leaf.
  100943. this.proxy = null;
  100944. // The maximum distance from leaf nodes.
  100945. this.height = 0;
  100946. // The AABB of this node.
  100947. this.aabb = new OIMO.AABB();
  100948. };
  100949. /**
  100950. * A proxy for dynamic bounding volume tree broad-phase.
  100951. * @author saharan
  100952. */
  100953. OIMO.DBVTProxy = function (shape) {
  100954. OIMO.Proxy.call(this, shape);
  100955. // The leaf of the proxy.
  100956. this.leaf = new OIMO.DBVTNode();
  100957. this.leaf.proxy = this;
  100958. };
  100959. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  100960. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  100961. OIMO.DBVTProxy.prototype.update = function () {
  100962. };
  100963. OIMO.World.prototype.add = function (obj) {
  100964. obj = obj || {};
  100965. var type = obj.type || "box";
  100966. if (typeof type === 'string') type = [type];// single shape
  100967. if (type[0].substring(0, 5) == 'joint') { // is joint
  100968. if (type[0] === 'joint') type[0] = 'jointHinge';
  100969. var axe1 = obj.axe1 || [1, 0, 0];
  100970. var axe2 = obj.axe2 || [1, 0, 0];
  100971. var pos1 = obj.pos1 || [0, 0, 0];
  100972. var pos2 = obj.pos2 || [0, 0, 0];
  100973. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  100974. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  100975. var min, max;
  100976. if (type[0] === "jointDistance") {
  100977. min = obj.min || 0;
  100978. max = obj.max || 10;
  100979. min = min * OIMO.INV_SCALE;
  100980. max = max * OIMO.INV_SCALE;
  100981. } else {
  100982. min = obj.min || 57.29578;
  100983. max = obj.max || 0;
  100984. min = min * OIMO.degtorad;
  100985. max = max * OIMO.degtorad;
  100986. }
  100987. var limit = obj.limit || null;
  100988. var spring = obj.spring || null;
  100989. var motor = obj.motor || null;
  100990. // joint setting
  100991. var jc = new OIMO.JointConfig();
  100992. jc.allowCollision = obj.collision || false;;
  100993. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  100994. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  100995. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  100996. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  100997. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  100998. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  100999. jc.body1 = obj.body1;
  101000. jc.body2 = obj.body2;
  101001. var joint;
  101002. switch (type[0]) {
  101003. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  101004. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  101005. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  101006. break;
  101007. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  101008. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  101009. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  101010. break;
  101011. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  101012. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  101013. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  101014. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  101015. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  101016. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  101017. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  101018. break;
  101019. }
  101020. joint.name = obj.name || '';
  101021. // finaly add to physics world
  101022. this.addJoint(joint);
  101023. return joint;
  101024. } else { // is body
  101025. // I'm dynamique or not
  101026. var move = obj.move || false;
  101027. // I can sleep or not
  101028. var noSleep = obj.noSleep || false;
  101029. // My start position
  101030. var p = obj.pos || [0, 0, 0];
  101031. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  101032. // My size
  101033. var s = obj.size || [1, 1, 1];
  101034. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  101035. // My rotation in degre
  101036. var rot = obj.rot || [0, 0, 0];
  101037. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  101038. var r = [];
  101039. for (var i = 0; i < rot.length / 3; i++) {
  101040. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  101041. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  101042. }
  101043. // My physics setting
  101044. var sc = new OIMO.ShapeConfig();
  101045. if (obj.sc !== undefined) sc = obj.sc;
  101046. if (obj.config) {
  101047. // The density of the shape.
  101048. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  101049. // The coefficient of friction of the shape.
  101050. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  101051. // The coefficient of restitution of the shape.
  101052. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  101053. // The bits of the collision groups to which the shape belongs.
  101054. sc.belongsTo = obj.config[3] || 1;
  101055. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  101056. // The bits of the collision groups with which the shape collides.
  101057. sc.collidesWith = obj.config[4] || 0xffffffff;
  101058. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  101059. }
  101060. // direct physics setting
  101061. if (obj.density !== undefined) sc.density = obj.density;
  101062. if (obj.friction !== undefined) sc.friction = obj.friction;
  101063. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  101064. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  101065. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  101066. if (obj.massPos) {
  101067. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  101068. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  101069. }
  101070. if (obj.massRot) {
  101071. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  101072. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  101073. }
  101074. // My rigidbody
  101075. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  101076. // My shapes
  101077. var shapes = [];
  101078. //if( typeof type === 'string' ) type = [type];// single shape
  101079. var n, n2;
  101080. for (var i = 0; i < type.length; i++) {
  101081. n = i * 3;
  101082. n2 = i * 4;
  101083. switch (type[i]) {
  101084. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  101085. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  101086. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  101087. }
  101088. body.addShape(shapes[i]);
  101089. if (i > 0) {
  101090. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  101091. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  101092. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  101093. }
  101094. }
  101095. // I'm static or i move
  101096. if (move) {
  101097. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  101098. else body.setupMass(0x1, true);
  101099. if (noSleep) body.allowSleep = false;
  101100. else body.allowSleep = true;
  101101. } else {
  101102. body.setupMass(0x2);
  101103. }
  101104. body.name = obj.name || ' ';
  101105. // finaly add to physics world
  101106. this.addRigidBody(body);
  101107. return body;
  101108. }
  101109. }
  101110. //UMD simplified
  101111. var root = this;
  101112. if (!root['OIMO']) {
  101113. if (true)
  101114. module.exports = OIMO;
  101115. else if (typeof define === 'function' && define.amd)
  101116. define([], function () {
  101117. return OIMO;
  101118. });
  101119. else if (typeof exports === 'object')
  101120. exports["OIMO"] = OIMO;
  101121. else {
  101122. root["OIMO"] = OIMO;
  101123. }
  101124. }
  101125. /***/ }),
  101126. /* 17 */
  101127. /***/ (function(module, exports, __webpack_require__) {
  101128. "use strict";
  101129. Object.defineProperty(exports, "__esModule", { value: true });
  101130. var babylonjs_1 = __webpack_require__(0);
  101131. var helper_1 = __webpack_require__(3);
  101132. var TemplateManager = (function () {
  101133. function TemplateManager(containerElement) {
  101134. this.containerElement = containerElement;
  101135. this.templates = {};
  101136. this.onInit = new babylonjs_1.Observable();
  101137. this.onLoaded = new babylonjs_1.Observable();
  101138. this.onStateChange = new babylonjs_1.Observable();
  101139. this.onAllLoaded = new babylonjs_1.Observable();
  101140. }
  101141. TemplateManager.prototype.initTemplate = function (templates) {
  101142. var _this = this;
  101143. var internalInit = function (dependencyMap, name, parentTemplate) {
  101144. var template = _this.templates[name];
  101145. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  101146. return internalInit(dependencyMap[childName], childName, template);
  101147. });
  101148. var addToParent = function () {
  101149. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  101150. template.appendTo(containingElement);
  101151. _this.checkLoadedState();
  101152. };
  101153. if (parentTemplate && !parentTemplate.parent) {
  101154. parentTemplate.onAppended.add(function () {
  101155. addToParent();
  101156. });
  101157. }
  101158. else {
  101159. addToParent();
  101160. }
  101161. return template;
  101162. };
  101163. this.buildHTMLTree(templates).then(function (htmlTree) {
  101164. internalInit(htmlTree, 'main');
  101165. });
  101166. };
  101167. TemplateManager.prototype.buildHTMLTree = function (templates) {
  101168. var _this = this;
  101169. var promises = Object.keys(templates).map(function (name) {
  101170. var template = new Template(name, templates[name]);
  101171. _this.templates[name] = template;
  101172. return template.initPromise;
  101173. });
  101174. return Promise.all(promises).then(function () {
  101175. var templateStructure = {};
  101176. var buildTree = function (parentObject, name) {
  101177. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  101178. childNodes.forEach(function (element) {
  101179. parentObject[element] = {};
  101180. buildTree(parentObject[element], element);
  101181. });
  101182. };
  101183. buildTree(templateStructure, "main");
  101184. return templateStructure;
  101185. });
  101186. };
  101187. TemplateManager.prototype.getCanvas = function () {
  101188. return this.containerElement.querySelector('canvas');
  101189. };
  101190. TemplateManager.prototype.getTemplate = function (name) {
  101191. return this.templates[name];
  101192. };
  101193. TemplateManager.prototype.checkLoadedState = function () {
  101194. var _this = this;
  101195. var done = Object.keys(this.templates).every(function (key) {
  101196. return _this.templates[key].isLoaded && !!_this.templates[key].parent;
  101197. });
  101198. if (done) {
  101199. this.onAllLoaded.notifyObservers(this);
  101200. }
  101201. };
  101202. return TemplateManager;
  101203. }());
  101204. exports.TemplateManager = TemplateManager;
  101205. var Handlebars = __webpack_require__(18);
  101206. var Template = (function () {
  101207. function Template(name, _configuration) {
  101208. var _this = this;
  101209. this.name = name;
  101210. this._configuration = _configuration;
  101211. this.onInit = new babylonjs_1.Observable();
  101212. this.onLoaded = new babylonjs_1.Observable();
  101213. this.onAppended = new babylonjs_1.Observable();
  101214. this.onStateChange = new babylonjs_1.Observable();
  101215. this.onEventTriggered = new babylonjs_1.Observable();
  101216. this.isLoaded = false;
  101217. this.onInit.notifyObservers(this);
  101218. var htmlContentPromise = getTemplateAsHtml(_configuration);
  101219. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  101220. if (htmlTemplate) {
  101221. var compiledTemplate = Handlebars.compile(htmlTemplate);
  101222. var config = _this._configuration.params || {};
  101223. var rawHtml = compiledTemplate(config);
  101224. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  101225. _this.isLoaded = true;
  101226. _this.onLoaded.notifyObservers(_this);
  101227. }
  101228. return _this;
  101229. });
  101230. }
  101231. Object.defineProperty(Template.prototype, "configuration", {
  101232. get: function () {
  101233. return this._configuration;
  101234. },
  101235. enumerable: true,
  101236. configurable: true
  101237. });
  101238. Template.prototype.getChildElements = function () {
  101239. var childrenArray = [];
  101240. var children = this.fragment.children;
  101241. if (!children) {
  101242. children = this.fragment.querySelectorAll('*');
  101243. }
  101244. for (var i = 0; i < children.length; ++i) {
  101245. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  101246. }
  101247. return childrenArray;
  101248. };
  101249. Template.prototype.appendTo = function (parent) {
  101250. var _this = this;
  101251. if (this.parent) {
  101252. console.error('Already appanded to ', this.parent);
  101253. }
  101254. else {
  101255. this.parent = parent;
  101256. if (this._configuration.id) {
  101257. this.parent.id = this._configuration.id;
  101258. }
  101259. this.parent.appendChild(this.fragment);
  101260. setTimeout(function () {
  101261. _this.registerEvents();
  101262. _this.onAppended.notifyObservers(_this);
  101263. });
  101264. }
  101265. };
  101266. Template.prototype.show = function (visibilityFunction) {
  101267. var _this = this;
  101268. if (visibilityFunction) {
  101269. return visibilityFunction(this).then(function () {
  101270. _this.onStateChange.notifyObservers(_this);
  101271. return _this;
  101272. });
  101273. }
  101274. else {
  101275. this.parent.style.display = 'flex';
  101276. this.onStateChange.notifyObservers(this);
  101277. return Promise.resolve(this);
  101278. }
  101279. };
  101280. Template.prototype.hide = function (visibilityFunction) {
  101281. var _this = this;
  101282. if (visibilityFunction) {
  101283. return visibilityFunction(this).then(function () {
  101284. _this.onStateChange.notifyObservers(_this);
  101285. return _this;
  101286. });
  101287. }
  101288. else {
  101289. this.parent.style.display = 'none';
  101290. this.onStateChange.notifyObservers(this);
  101291. return Promise.resolve(this);
  101292. }
  101293. };
  101294. Template.prototype.registerEvents = function () {
  101295. var _this = this;
  101296. if (this._configuration.events) {
  101297. var _loop_1 = function (eventName) {
  101298. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  101299. var functionToFire_1 = function (selector, event) {
  101300. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  101301. };
  101302. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  101303. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  101304. }
  101305. else if (typeof this_1._configuration.events[eventName] === 'object') {
  101306. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  101307. var event_1 = this_1._configuration.events[eventName] || {};
  101308. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  101309. if (selector.indexOf('#') !== 0) {
  101310. selector = '#' + selector;
  101311. }
  101312. var htmlElement = _this.parent.querySelector(selector);
  101313. htmlElement && htmlElement.addEventListener(eventName, functionToFire_1.bind(_this, selector), false);
  101314. });
  101315. }
  101316. }
  101317. };
  101318. var this_1 = this;
  101319. for (var eventName in this._configuration.events) {
  101320. _loop_1(eventName);
  101321. }
  101322. }
  101323. };
  101324. return Template;
  101325. }());
  101326. exports.Template = Template;
  101327. function getTemplateAsHtml(templateConfig) {
  101328. if (!templateConfig) {
  101329. return Promise.reject('No templateConfig provided');
  101330. }
  101331. else if (templateConfig.html) {
  101332. return Promise.resolve(templateConfig.html);
  101333. }
  101334. else {
  101335. var location_1 = getTemplateLocation(templateConfig);
  101336. if (helper_1.isUrl(location_1)) {
  101337. return helper_1.loadFile(location_1);
  101338. }
  101339. else {
  101340. location_1 = location_1.replace('#', '');
  101341. var element = document.getElementById(location_1);
  101342. if (element) {
  101343. return Promise.resolve(element.innerHTML);
  101344. }
  101345. else {
  101346. return Promise.reject('Template ID not found');
  101347. }
  101348. }
  101349. }
  101350. }
  101351. exports.getTemplateAsHtml = getTemplateAsHtml;
  101352. function getTemplateLocation(templateConfig) {
  101353. if (!templateConfig || typeof templateConfig === 'string') {
  101354. return templateConfig;
  101355. }
  101356. else {
  101357. return templateConfig.location;
  101358. }
  101359. }
  101360. exports.getTemplateLocation = getTemplateLocation;
  101361. /***/ }),
  101362. /* 18 */
  101363. /***/ (function(module, exports, __webpack_require__) {
  101364. /**!
  101365. @license
  101366. handlebars v4.0.11
  101367. Copyright (C) 2011-2017 by Yehuda Katz
  101368. Permission is hereby granted, free of charge, to any person obtaining a copy
  101369. of this software and associated documentation files (the "Software"), to deal
  101370. in the Software without restriction, including without limitation the rights
  101371. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  101372. copies of the Software, and to permit persons to whom the Software is
  101373. furnished to do so, subject to the following conditions:
  101374. The above copyright notice and this permission notice shall be included in
  101375. all copies or substantial portions of the Software.
  101376. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  101377. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  101378. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  101379. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  101380. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  101381. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  101382. THE SOFTWARE.
  101383. */
  101384. !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],
  101385. 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){
  101386. 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"]}])});
  101387. /***/ }),
  101388. /* 19 */
  101389. /***/ (function(module, exports, __webpack_require__) {
  101390. "use strict";
  101391. Object.defineProperty(exports, "__esModule", { value: true });
  101392. var mappers_1 = __webpack_require__(2);
  101393. var types_1 = __webpack_require__(20);
  101394. var deepmerge_1 = __webpack_require__(27);
  101395. var ConfigurationLoader = (function () {
  101396. function ConfigurationLoader() {
  101397. }
  101398. ConfigurationLoader.prototype.loadConfiguration = function (initConfig) {
  101399. if (initConfig === void 0) { initConfig = {}; }
  101400. var loadedConfig = deepmerge_1.default({}, initConfig);
  101401. var extendedConfiguration = types_1.getConfigurationType(loadedConfig && loadedConfig.extends);
  101402. loadedConfig = deepmerge_1.default(extendedConfiguration, loadedConfig);
  101403. if (loadedConfig.configuration) {
  101404. var mapperType = "json";
  101405. var url = loadedConfig.configuration;
  101406. if (loadedConfig.configuration.url) {
  101407. url = loadedConfig.configuration.url;
  101408. mapperType = loadedConfig.configuration.mapper;
  101409. if (!mapperType) {
  101410. mapperType = loadedConfig.configuration.url.split('.').pop();
  101411. }
  101412. }
  101413. var mapper_1 = mappers_1.mapperManager.getMapper(mapperType);
  101414. return this.loadFile(url).then(function (data) {
  101415. var parsed = mapper_1.map(data);
  101416. return deepmerge_1.default(loadedConfig, parsed);
  101417. });
  101418. }
  101419. else {
  101420. return Promise.resolve(loadedConfig);
  101421. }
  101422. };
  101423. ConfigurationLoader.prototype.getConfigurationType = function (type) {
  101424. };
  101425. ConfigurationLoader.prototype.loadFile = function (url) {
  101426. var cacheReference = this.configurationCache;
  101427. if (cacheReference[url]) {
  101428. return Promise.resolve(cacheReference[url]);
  101429. }
  101430. return new Promise(function (resolve, reject) {
  101431. var xhr = new XMLHttpRequest();
  101432. xhr.open('GET', url);
  101433. xhr.send();
  101434. xhr.onreadystatechange = function () {
  101435. var DONE = 4;
  101436. var OK = 200;
  101437. if (xhr.readyState === DONE) {
  101438. if (xhr.status === OK) {
  101439. cacheReference[url] = xhr.responseText;
  101440. resolve(xhr.responseText);
  101441. }
  101442. }
  101443. else {
  101444. console.log('Error: ' + xhr.status, url);
  101445. reject('Error: ' + xhr.status);
  101446. }
  101447. };
  101448. });
  101449. };
  101450. return ConfigurationLoader;
  101451. }());
  101452. exports.ConfigurationLoader = ConfigurationLoader;
  101453. exports.configurationLoader = new ConfigurationLoader();
  101454. exports.default = exports.configurationLoader;
  101455. /***/ }),
  101456. /* 20 */
  101457. /***/ (function(module, exports, __webpack_require__) {
  101458. "use strict";
  101459. Object.defineProperty(exports, "__esModule", { value: true });
  101460. var minimal_1 = __webpack_require__(21);
  101461. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  101462. var default_1 = __webpack_require__(22);
  101463. exports.defaultConfiguration = default_1.defaultConfiguration;
  101464. var getConfigurationType = function (type) {
  101465. switch (type) {
  101466. case 'default':
  101467. return default_1.defaultConfiguration;
  101468. case 'minimal':
  101469. return minimal_1.minimalConfiguration;
  101470. default:
  101471. return default_1.defaultConfiguration;
  101472. }
  101473. };
  101474. exports.getConfigurationType = getConfigurationType;
  101475. /***/ }),
  101476. /* 21 */
  101477. /***/ (function(module, exports, __webpack_require__) {
  101478. "use strict";
  101479. Object.defineProperty(exports, "__esModule", { value: true });
  101480. exports.minimalConfiguration = {
  101481. version: "0.1",
  101482. templates: {
  101483. main: {
  101484. html: __webpack_require__(7)
  101485. },
  101486. loadingScreen: {
  101487. html: __webpack_require__(8),
  101488. params: {
  101489. backgroundColor: "#000000",
  101490. loadingImage: __webpack_require__(9)
  101491. }
  101492. },
  101493. viewer: {
  101494. html: __webpack_require__(10),
  101495. },
  101496. overlay: {
  101497. html: __webpack_require__(11),
  101498. params: {
  101499. closeImage: __webpack_require__(12),
  101500. closeText: 'Close'
  101501. }
  101502. },
  101503. error: {
  101504. html: __webpack_require__(13)
  101505. }
  101506. },
  101507. engine: {
  101508. antialiasing: true
  101509. }
  101510. };
  101511. /***/ }),
  101512. /* 22 */
  101513. /***/ (function(module, exports, __webpack_require__) {
  101514. "use strict";
  101515. Object.defineProperty(exports, "__esModule", { value: true });
  101516. exports.defaultConfiguration = {
  101517. version: "0.1",
  101518. templates: {
  101519. main: {
  101520. html: __webpack_require__(7)
  101521. },
  101522. loadingScreen: {
  101523. html: __webpack_require__(8),
  101524. params: {
  101525. backgroundColor: "#000000",
  101526. loadingImage: __webpack_require__(9)
  101527. }
  101528. },
  101529. viewer: {
  101530. html: __webpack_require__(10),
  101531. },
  101532. navBar: {
  101533. html: __webpack_require__(23),
  101534. params: {
  101535. buttons: [
  101536. {
  101537. id: 'fullscreen-button',
  101538. altText: "Fullscreen",
  101539. image: __webpack_require__(24)
  101540. },
  101541. ],
  101542. visibilityTimeout: 2000
  101543. },
  101544. events: {
  101545. pointerdown: { 'fullscreen-button': true }
  101546. }
  101547. },
  101548. overlay: {
  101549. html: __webpack_require__(11),
  101550. params: {
  101551. closeImage: __webpack_require__(12),
  101552. closeText: 'Close'
  101553. }
  101554. },
  101555. help: {
  101556. html: __webpack_require__(25)
  101557. },
  101558. share: {
  101559. html: __webpack_require__(26)
  101560. },
  101561. error: {
  101562. html: __webpack_require__(13)
  101563. }
  101564. },
  101565. camera: {
  101566. behaviors: {
  101567. autoRotate: 0,
  101568. framing: {
  101569. type: 2,
  101570. zoomOnBoundingInfo: true,
  101571. zoomStopsAnimation: false
  101572. }
  101573. }
  101574. },
  101575. skybox: {
  101576. cubeTexture: {
  101577. url: 'https://playground.babylonjs.com/textures/environment.dds',
  101578. gammaSpace: false
  101579. },
  101580. pbr: true,
  101581. blur: 0.7,
  101582. infiniteDIstance: false,
  101583. material: {
  101584. imageProcessingConfiguration: {
  101585. colorCurves: {
  101586. globalDensity: 89,
  101587. globalHue: 58.88,
  101588. globalSaturation: 94
  101589. },
  101590. colorCurvesEnabled: true,
  101591. exposure: 1.5,
  101592. contrast: 1.66,
  101593. toneMappingEnabled: true,
  101594. vignetteEnabled: true,
  101595. vignetteWeight: 5,
  101596. vignetteColor: { r: 0.8, g: 0.6, b: 0.4 },
  101597. vignetteM: true
  101598. }
  101599. }
  101600. },
  101601. ground: true,
  101602. engine: {
  101603. antialiasing: true
  101604. },
  101605. scene: {
  101606. imageProcessingConfiguration: {
  101607. exposure: 1.4,
  101608. contrast: 1.66,
  101609. toneMappingEnabled: true
  101610. }
  101611. }
  101612. };
  101613. /***/ }),
  101614. /* 23 */
  101615. /***/ (function(module, exports) {
  101616. module.exports = "<style>\r\n nav-bar {\r\n position: absolute;\r\n height: 160px;\r\n width: 100%;\r\n bottom: 0;\r\n background-color: rgba(0, 0, 0, 0.3);\r\n color: white;\r\n transition: 1s;\r\n align-items: flex-start;\r\n justify-content: space-around;\r\n display: flex;\r\n\r\n flex-direction: column;\r\n }\r\n\r\n /* Big screens have room for the entire navbar */\r\n\r\n @media screen and (min-width: 768px) {\r\n nav-bar {\r\n align-items: center;\r\n flex-direction: row;\r\n justify-content: space-between;\r\n height: 80px;\r\n }\r\n }\r\n\r\n div.flex-container {\r\n display: flex;\r\n width: 100%;\r\n }\r\n\r\n div.thumbnail {\r\n position: relative;\r\n overflow: hidden;\r\n display: block;\r\n width: 40px;\r\n height: 40px;\r\n background-size: cover;\r\n background-position: center;\r\n border-radius: 20px;\r\n margin: 0 10px;\r\n }\r\n\r\n div.title-container {\r\n flex-direction: column;\r\n display: flex;\r\n justify-content: space-between;\r\n }\r\n\r\n span.model-title {\r\n font-size: 125%;\r\n }\r\n\r\n span.model-subtitle {\r\n font-size: 90%;\r\n }\r\n\r\n div.button-container {\r\n align-items: center;\r\n justify-content: flex-end;\r\n }\r\n\r\n div.button {\r\n cursor: pointer;\r\n height: 30px;\r\n margin: 0 10px;\r\n }\r\n\r\n div.button img {\r\n height: 100%;\r\n }\r\n</style>\r\n\r\n{{#if disableOnFullscreen}}\r\n<style>\r\n viewer:fullscreen nav-bar {\r\n display: none;\r\n }\r\n\r\n viewer:-moz-full-screen nav-bar {\r\n display: none;\r\n }\r\n\r\n viewer:-webkit-full-screen nav-bar {\r\n display: none;\r\n }\r\n</style>\r\n{{/if}}\r\n\r\n<div class=\"flex-container\" id=\"model-metadata\">\r\n <!-- holding the description -->\r\n <div class=\"thumbnail\">\r\n <!-- holding the thumbnail \r\n <img src=\"{{thumbnail}}\" alt=\"{{title}}\">-->\r\n </div>\r\n <div class=\"title-container\">\r\n\r\n <span class=\"model-title\">{{#if title}}{{title}}{{/if}}</span>\r\n <span class=\"model-subtitle\"> {{#if subtitle}}{{subtitle}} {{/if}}</span>\r\n </div>\r\n</div>\r\n<div class=\"button-container flex-container\">\r\n <!-- holding the buttons -->\r\n {{#each buttons}}\r\n <div id=\"{{id}}\" class=\"button\">\r\n {{#if text}}\r\n <span>{{text}}</span>> {{/if}} {{#if image}}\r\n <img src=\"{{image}}\" alt=\"{{altText}}\"> {{/if}}\r\n </div>\r\n {{/each}}\r\n</div>";
  101617. /***/ }),
  101618. /* 24 */
  101619. /***/ (function(module, exports) {
  101620. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAAASAAAAEgARslrPgAAAG5JREFUaN7t2NEKgCAMBVAX/f8v21MvQTDEHNI5z21wU7HVGgBQJ7IP9t57qmFErOhzO758OysIUO0cLczu0Wxd9mw8bb8CAlQTAAAqDU9ko1+js/tvfxMLUE2AasMz8dsMO+u/UNb2KyAAAPBnFyAoHCsn18AtAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE3LTEwLTI0VDA5OjI5OjA3KzAwOjAwnIEg5AAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxNy0xMC0yNFQwOToyOTowNyswMDowMO3cmFgAAAAodEVYdHN2ZzpiYXNlLXVyaQBmaWxlOi8vL3RtcC9tYWdpY2stYU9TenZXZUYevZw/AAAAAElFTkSuQmCC"
  101621. /***/ }),
  101622. /* 25 */
  101623. /***/ (function(module, exports) {
  101624. module.exports = "HELP";
  101625. /***/ }),
  101626. /* 26 */
  101627. /***/ (function(module, exports) {
  101628. module.exports = "SHARE";
  101629. /***/ }),
  101630. /* 27 */
  101631. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  101632. "use strict";
  101633. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  101634. var isMergeableObject = function isMergeableObject(value) {
  101635. return isNonNullObject(value)
  101636. && !isSpecial(value)
  101637. };
  101638. function isNonNullObject(value) {
  101639. return !!value && typeof value === 'object'
  101640. }
  101641. function isSpecial(value) {
  101642. var stringValue = Object.prototype.toString.call(value);
  101643. return stringValue === '[object RegExp]'
  101644. || stringValue === '[object Date]'
  101645. || isReactElement(value)
  101646. }
  101647. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  101648. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  101649. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  101650. function isReactElement(value) {
  101651. return value.$$typeof === REACT_ELEMENT_TYPE
  101652. }
  101653. function emptyTarget(val) {
  101654. return Array.isArray(val) ? [] : {}
  101655. }
  101656. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  101657. var clone = !optionsArgument || optionsArgument.clone !== false;
  101658. return (clone && isMergeableObject(value))
  101659. ? deepmerge(emptyTarget(value), value, optionsArgument)
  101660. : value
  101661. }
  101662. function defaultArrayMerge(target, source, optionsArgument) {
  101663. return target.concat(source).map(function(element) {
  101664. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  101665. })
  101666. }
  101667. function mergeObject(target, source, optionsArgument) {
  101668. var destination = {};
  101669. if (isMergeableObject(target)) {
  101670. Object.keys(target).forEach(function(key) {
  101671. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  101672. });
  101673. }
  101674. Object.keys(source).forEach(function(key) {
  101675. if (!isMergeableObject(source[key]) || !target[key]) {
  101676. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  101677. } else {
  101678. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  101679. }
  101680. });
  101681. return destination
  101682. }
  101683. function deepmerge(target, source, optionsArgument) {
  101684. var sourceIsArray = Array.isArray(source);
  101685. var targetIsArray = Array.isArray(target);
  101686. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  101687. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  101688. if (!sourceAndTargetTypesMatch) {
  101689. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  101690. } else if (sourceIsArray) {
  101691. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  101692. return arrayMerge(target, source, optionsArgument)
  101693. } else {
  101694. return mergeObject(target, source, optionsArgument)
  101695. }
  101696. }
  101697. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  101698. if (!Array.isArray(array)) {
  101699. throw new Error('first argument should be an array')
  101700. }
  101701. return array.reduce(function(prev, next) {
  101702. return deepmerge(prev, next, optionsArgument)
  101703. }, {})
  101704. };
  101705. var deepmerge_1 = deepmerge;
  101706. /* harmony default export */ __webpack_exports__["default"] = (deepmerge_1);
  101707. /***/ }),
  101708. /* 28 */
  101709. /***/ (function(module, exports, __webpack_require__) {
  101710. "use strict";
  101711. var __extends = (this && this.__extends) || (function () {
  101712. var extendStatics = Object.setPrototypeOf ||
  101713. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  101714. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  101715. return function (d, b) {
  101716. extendStatics(d, b);
  101717. function __() { this.constructor = d; }
  101718. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  101719. };
  101720. })();
  101721. Object.defineProperty(exports, "__esModule", { value: true });
  101722. var babylonjs_1 = __webpack_require__(0);
  101723. var PromiseObservable = (function (_super) {
  101724. __extends(PromiseObservable, _super);
  101725. function PromiseObservable() {
  101726. return _super !== null && _super.apply(this, arguments) || this;
  101727. }
  101728. PromiseObservable.prototype.notifyWithPromise = function (eventData, mask, target, currentTarget) {
  101729. if (mask === void 0) { mask = -1; }
  101730. var p = Promise.resolve();
  101731. if (!this._observers.length) {
  101732. return p;
  101733. }
  101734. var state = this['_eventState'];
  101735. state.mask = mask;
  101736. state.target = target;
  101737. state.currentTarget = currentTarget;
  101738. state.skipNextObservers = false;
  101739. this._observers.forEach(function (obs) {
  101740. if (state.skipNextObservers) {
  101741. return;
  101742. }
  101743. if (obs.mask & mask) {
  101744. if (obs.scope) {
  101745. p = p.then(function () {
  101746. return obs.callback.apply(obs.scope, [eventData, state]);
  101747. });
  101748. }
  101749. else {
  101750. p = p.then(function () {
  101751. return obs.callback(eventData, state);
  101752. });
  101753. }
  101754. }
  101755. });
  101756. return p;
  101757. };
  101758. return PromiseObservable;
  101759. }(babylonjs_1.Observable));
  101760. exports.PromiseObservable = PromiseObservable;
  101761. /***/ }),
  101762. /* 29 */
  101763. /***/ (function(module, exports, __webpack_require__) {
  101764. /* WEBPACK VAR INJECTION */(function(global) {var globalObject="undefined"!=typeof global?global:"undefined"!=typeof window?window:this,babylonDependency=globalObject&&globalObject.BABYLON||BABYLON||"undefined"!="function"&&__webpack_require__(0),BABYLON=babylonDependency,__decorate=this&&this.__decorate||function(e,t,r,n){var o,a=arguments.length,i=a<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)i=Reflect.decorate(e,t,r,n);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(i=(a<3?o(i):a>3?o(t,r,i):o(t,r))||i);return a>3&&i&&Object.defineProperty(t,r,i),i},__extends=this&&this.__extends||(function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])};return function(t,r){function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}})(),BABYLON;!(function(e){var t=(function(){function t(){this.solidPattern=/solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g,this.facetsPattern=/facet([\s\S]*?)endfacet/g,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,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,this.name="stl",this.extensions={".stl":{isBinary:!0}}}return t.prototype.importMesh=function(t,r,n,o,a,i,s){var l;if(this.isBinary(n)){var u=new e.Mesh("stlmesh",r);return this.parseBinary(u,n),a&&a.push(u),!0}for(var c=new Uint8Array(n),f="",d=0;d<n.byteLength;d++)f+=String.fromCharCode(c[d]);for(n=f;l=this.solidPattern.exec(n);){var h=l[1];if(h!=l[3])return e.Tools.Error("Error in STL, solid name != endsolid name"),!1;if(t&&h)if(t instanceof Array){if(!t.indexOf(h))continue}else if(h!==t)continue;h=h||"stlmesh";var u=new e.Mesh(h,r);this.parseASCII(u,l[2]),a&&a.push(u)}return!0},t.prototype.load=function(e,t,r){var n=this.importMesh(null,e,t,r,null,null,null);return n&&e.createDefaultCameraOrLight(),n},t.prototype.isBinary=function(e){var t,r;if(r=new DataView(e),t=50,84+r.getUint32(80,!0)*t===r.byteLength)return!0;for(var n=r.byteLength,o=0;o<n;o++)if(r.getUint8(o)>127)return!0;return!1},t.prototype.parseBinary=function(t,r){for(var n=new DataView(r),o=n.getUint32(80,!0),a=0,i=new Float32Array(3*o*3),s=new Float32Array(3*o*3),l=new Uint32Array(3*o),u=0,c=0;c<o;c++){for(var f=84+50*c,d=n.getFloat32(f,!0),h=n.getFloat32(f+4,!0),p=n.getFloat32(f+8,!0),m=1;m<=3;m++){var T=f+12*m;i[a]=n.getFloat32(T,!0),i[a+2]=n.getFloat32(T+4,!0),i[a+1]=n.getFloat32(T+8,!0),s[a]=d,s[a+2]=h,s[a+1]=p,a+=3}l[u]=u++,l[u]=u++,l[u]=u++}t.setVerticesData(e.VertexBuffer.PositionKind,i),t.setVerticesData(e.VertexBuffer.NormalKind,s),t.setIndices(l),t.computeWorldMatrix(!0)},t.prototype.parseASCII=function(t,r){for(var n,o=[],a=[],i=[],s=0;n=this.facetsPattern.exec(r);){var l=n[1],u=this.normalPattern.exec(l);if(this.normalPattern.lastIndex=0,u){for(var c,f=[Number(u[1]),Number(u[5]),Number(u[3])];c=this.vertexPattern.exec(l);)o.push(Number(c[1]),Number(c[5]),Number(c[3])),a.push(f[0],f[1],f[2]);i.push(s++,s++,s++),this.vertexPattern.lastIndex=0}}this.facetsPattern.lastIndex=0,t.setVerticesData(e.VertexBuffer.PositionKind,o),t.setVerticesData(e.VertexBuffer.NormalKind,a),t.setIndices(i),t.computeWorldMatrix(!0)},t})();e.STLFileLoader=t,e.SceneLoader&&e.SceneLoader.RegisterPlugin(new t)})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function t(){this.materials=[]}return t.prototype.parseMTL=function(r,n,o){for(var a,i=n.split("\n"),s=/\s+/,l=null,u=0;u<i.length;u++){var c=i[u].trim();if(0!==c.length&&"#"!==c.charAt(0)){var f=c.indexOf(" "),d=f>=0?c.substring(0,f):c;d=d.toLowerCase();var h=f>=0?c.substring(f+1).trim():"";"newmtl"===d?(l&&this.materials.push(l),l=new e.StandardMaterial(h,r)):"kd"===d&&l?(a=h.split(s,3).map(parseFloat),l.diffuseColor=e.Color3.FromArray(a)):"ka"===d&&l?(a=h.split(s,3).map(parseFloat),l.ambientColor=e.Color3.FromArray(a)):"ks"===d&&l?(a=h.split(s,3).map(parseFloat),l.specularColor=e.Color3.FromArray(a)):"ke"===d&&l?(a=h.split(s,3).map(parseFloat),l.emissiveColor=e.Color3.FromArray(a)):"ns"===d&&l?l.specularPower=parseFloat(h):"d"===d&&l?l.alpha=parseFloat(h):"map_ka"===d&&l?l.ambientTexture=t._getTexture(o,h,r):"map_kd"===d&&l?l.diffuseTexture=t._getTexture(o,h,r):"map_ks"===d&&l?l.specularTexture=t._getTexture(o,h,r):"map_ns"===d||("map_bump"===d&&l?l.bumpTexture=t._getTexture(o,h,r):"map_d"===d&&l&&(l.opacityTexture=t._getTexture(o,h,r)))}}l&&this.materials.push(l)},t._getTexture=function(t,r,n){if(!r)return null;var o=t;if("file:"===t){var a=r.lastIndexOf("\\");-1===a&&(a=r.lastIndexOf("/")),o+=a>-1?r.substr(a+1):r}else o+=r;return new e.Texture(o,n)},t})();e.MTLFileLoader=t;var r=(function(){function r(){this.name="obj",this.extensions=".obj",this.obj=/^o/,this.group=/^g/,this.mtllib=/^mtllib /,this.usemtl=/^usemtl /,this.smooth=/^s /,this.vertexPattern=/v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,this.normalPattern=/vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,this.uvPattern=/vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/,this.facePattern1=/f\s+(([\d]{1,}[\s]?){3,})+/,this.facePattern2=/f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,this.facePattern3=/f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/,this.facePattern4=/f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/}return r.prototype._loadMTL=function(t,r,n){var o=e.Tools.BaseUrl+r+t;e.Tools.LoadFile(o,n,void 0,void 0,!1,(function(){console.warn("Error - Unable to load "+o)}))},r.prototype.importMesh=function(e,t,r,n,o,a,i){var s=this._parseSolid(e,t,r,n);return o&&s.forEach((function(e){o.push(e)})),!0},r.prototype.load=function(e,t,r){return this.importMesh(null,e,t,r,null,null,null)},r.prototype._parseSolid=function(n,o,a,i){for(var s,l=[],u=[],c=[],f=[],d=[],h=[],p=[],m=[],T=[],E=0,_=!1,A=[],y=[],g=[],v=[],L="",x="",b=new t,N=1,M=!0,O=function(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[]});var r=e[t[0]].normals.indexOf(t[1]);return-1===r?-1:e[t[0]].idx[r]},F=function(e,t){e[t[0]]||(e[t[0]]={normals:[],idx:[],uv:[]});var r=e[t[0]].normals.indexOf(t[1]);return 1!=r&&t[2]==e[t[0]].uv[r]?e[t[0]].idx[r]:-1},R=function(e,t,n,o,a,i){var s;s=r.OPTIMIZE_WITH_UV?F(T,[e,n,t]):O(T,[e,n]),-1==s?(d.push(h.length),h.push(o),p.push(a),m.push(i),T[e].normals.push(n),T[e].idx.push(E++),r.OPTIMIZE_WITH_UV&&T[e].uv.push(t)):d.push(s)},S=function(){for(var e=0;e<h.length;e++)A.push(h[e].x,h[e].y,h[e].z),y.push(m[e].x,m[e].y,m[e].z),g.push(p[e].x,p[e].y);h=[],m=[],p=[],T=[],E=0},I=function(e,t){t+1<e.length&&(v.push(e[0],e[t],e[t+1]),t+=1,I(e,t))},w=function(){f.length>0&&(s=f[f.length-1],S(),d.reverse(),s.indices=d.slice(),s.positions=A.slice(),s.normals=y.slice(),s.uvs=g.slice(),d=[],A=[],y=[],g=[])},P=a.split("\n"),B=0;B<P.length;B++){var C,G=P[B].trim();if(0!==G.length&&"#"!==G.charAt(0))if(null!==(C=this.vertexPattern.exec(G)))l.push(new e.Vector3(parseFloat(C[1]),parseFloat(C[2]),parseFloat(C[3])));else if(null!==(C=this.normalPattern.exec(G)))u.push(new e.Vector3(parseFloat(C[1]),parseFloat(C[2]),parseFloat(C[3])));else if(null!==(C=this.uvPattern.exec(G)))c.push(new e.Vector2(parseFloat(C[1]),parseFloat(C[2])));else if(null!==(C=this.facePattern3.exec(G)))!(function(e,t){I(e,t);for(var r=0;r<v.length;r++){var n=v[r].split("/"),o=parseInt(n[0])-1,a=parseInt(n[1])-1,i=parseInt(n[2])-1;R(o,a,i,l[o],c[a],u[i])}v=[]})(C[1].trim().split(" "),1);else if(null!==(C=this.facePattern4.exec(G)))!(function(t,r){I(t,r);for(var n=0;n<v.length;n++){var o=v[n].split("//"),a=parseInt(o[0])-1,i=parseInt(o[1])-1;R(a,1,i,l[a],e.Vector2.Zero(),u[i])}v=[]})(C[1].trim().split(" "),1);else if(null!==(C=this.facePattern2.exec(G)))!(function(t,r){I(t,r);for(var n=0;n<v.length;n++){var o=v[n].split("/"),a=parseInt(o[0])-1,i=parseInt(o[1])-1;R(a,i,0,l[a],c[i],e.Vector3.Up())}v=[]})(C[1].trim().split(" "),1);else if(null!==(C=this.facePattern1.exec(G)))!(function(t,r){I(t,r);for(var n=0;n<v.length;n++){var o=parseInt(v[n])-1;R(o,0,0,l[o],e.Vector2.Zero(),e.Vector3.Up())}v=[]})(C[1].trim().split(" "),1);else if(this.group.test(G)||this.obj.test(G)){var D={name:G.substring(2).trim(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,materialName:""};w(),f.push(D),_=!0,M=!0,N=1}else if(this.usemtl.test(G)){if(L=G.substring(7).trim(),!M){w();var D={name:"_mm"+N.toString(),indices:void 0,positions:void 0,normals:void 0,uvs:void 0,materialName:L};N++,f.push(D)}_&&M&&(f[f.length-1].materialName=L,M=!1)}else this.mtllib.test(G)?x=G.substring(7).trim():this.smooth.test(G)||console.log("Unhandled expression at line : "+G)}_&&(s=f[f.length-1],d.reverse(),S(),s.indices=d,s.positions=A,s.normals=y,s.uvs=g),_||(d.reverse(),S(),f.push({name:e.Geometry.RandomId(),indices:d,positions:A,normals:y,uvs:g,materialName:L}));for(var V=[],U=new Array,k=0;k<f.length;k++){if(n&&f[k].name)if(n instanceof Array){if(-1==n.indexOf(f[k].name))continue}else if(f[k].name!==n)continue;s=f[k];var H=new e.Mesh(f[k].name,o);U.push(f[k].materialName);var Y=new e.VertexData;Y.positions=s.positions,Y.normals=s.normals,Y.uvs=s.uvs,Y.indices=s.indices,Y.applyToMesh(H),V.push(H)}return""!==x&&this._loadMTL(x,i,(function(e){b.parseMTL(o,e,i);for(var t=0;t<b.materials.length;t++){for(var r,n=0,a=[];(r=U.indexOf(b.materials[t].name,n))>-1;)a.push(r),n=r+1;if(-1==r&&0==a.length)b.materials[t].dispose();else for(var s=0;s<a.length;s++)V[a[s]].material=b.materials[t]}})),V},r.OPTIMIZE_WITH_UV=!1,r})();e.OBJFileLoader=r,e.SceneLoader&&e.SceneLoader.RegisterPlugin(new r)})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t;!(function(e){e[e.AUTO=0]="AUTO",e[e.PASS_THROUGH=1]="PASS_THROUGH",e[e.FORCE_RIGHT_HANDED=2]="FORCE_RIGHT_HANDED"})(t=e.GLTFLoaderCoordinateSystemMode||(e.GLTFLoaderCoordinateSystemMode={}));var r=(function(){function e(){this.coordinateSystemMode=t.AUTO,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}}}return e.prototype.dispose=function(){this._loader&&this._loader.dispose()},e.prototype.importMeshAsync=function(t,r,n,o,a,i,s){try{var l=e._parse(n);this.onParsed&&this.onParsed(l),this._loader=this._getLoader(l),this._loader.importMeshAsync(t,r,l,o,a,i,s)}catch(e){s(e.message)}},e.prototype.loadAsync=function(t,r,n,o,a,i){try{var s=e._parse(r);this.onParsed&&this.onParsed(s),this._loader=this._getLoader(s),this._loader.loadAsync(t,s,n,o,a,i)}catch(e){i(e.message)}},e.prototype.canDirectLoad=function(e){return-1!==e.indexOf("scene")&&-1!==e.indexOf("node")},e.prototype.createPlugin=function(){return new e},e._parse=function(t){return t instanceof ArrayBuffer?e._parseBinary(t):{json:JSON.parse(t),bin:null}},e.prototype._getLoader=function(t){var r={major:2,minor:0},n=t.json.asset||{},o=e._parseVersion(n.version);if(!o)throw new Error("Invalid version: "+n.version);if(void 0!==n.minVersion){var a=e._parseVersion(n.minVersion);if(!a)throw new Error("Invalid minimum version: "+n.minVersion);if(e._compareVersion(a,r)>0)throw new Error("Incompatible minimum version: "+n.minVersion)}var i={1:e.CreateGLTFLoaderV1,2:e.CreateGLTFLoaderV2},s=i[o.major];if(!s)throw new Error("Unsupported version: "+n.version);return s(this)},e._parseBinary=function(t){var r={Magic:1179937895},o=new n(t),a=o.readUint32();if(a!==r.Magic)throw new Error("Unexpected magic: "+a);var i=o.readUint32();switch(i){case 1:return e._parseV1(o);case 2:return e._parseV2(o)}throw new Error("Unsupported version: "+i)},e._parseV1=function(t){var r={JSON:0},n=t.readUint32();if(n!=t.getLength())throw new Error("Length in header does not match actual data length: "+n+" != "+t.getLength());var o,a=t.readUint32(),i=t.readUint32();switch(i){case r.JSON:o=JSON.parse(e._decodeBufferToText(t.readUint8Array(a)));break;default:throw new Error("Unexpected content format: "+i)}var s=t.getLength()-t.getPosition();return{json:o,bin:t.readUint8Array(s)}},e._parseV2=function(t){var r={JSON:1313821514,BIN:5130562},n=t.readUint32();if(n!==t.getLength())throw new Error("Length in header does not match actual data length: "+n+" != "+t.getLength());var o=t.readUint32();if(t.readUint32()!==r.JSON)throw new Error("First chunk format is not JSON");for(var a=JSON.parse(e._decodeBufferToText(t.readUint8Array(o))),i=null;t.getPosition()<t.getLength();){var s=t.readUint32();switch(t.readUint32()){case r.JSON:throw new Error("Unexpected JSON chunk");case r.BIN:i=t.readUint8Array(s);break;default:t.skipBytes(s)}}return{json:a,bin:i}},e._parseVersion=function(e){var t=(e+"").match(/^(\d+)\.(\d+)$/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null},e._compareVersion=function(e,t){return e.major>t.major?1:e.major<t.major?-1:e.minor>t.minor?1:e.minor<t.minor?-1:0},e._decodeBufferToText=function(e){for(var t="",r=e.byteLength,n=0;n<r;n++)t+=String.fromCharCode(e[n]);return t},e.HomogeneousCoordinates=!1,e.IncrementalLoading=!0,e})();e.GLTFFileLoader=r;var n=(function(){function e(e){this._arrayBuffer=e,this._dataView=new DataView(e),this._byteOffset=0}return e.prototype.getPosition=function(){return this._byteOffset},e.prototype.getLength=function(){return this._arrayBuffer.byteLength},e.prototype.readUint32=function(){var e=this._dataView.getUint32(this._byteOffset,!0);return this._byteOffset+=4,e},e.prototype.readUint8Array=function(e){var t=new Uint8Array(this._arrayBuffer,this._byteOffset,e);return this._byteOffset+=e,t},e.prototype.skipBytes=function(e){this._byteOffset+=e},e})();e.SceneLoader&&e.SceneLoader.RegisterPlugin(new r)})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){!(function(e){e[e.BYTE=5120]="BYTE",e[e.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",e[e.SHORT=5122]="SHORT",e[e.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",e[e.FLOAT=5126]="FLOAT"})(e.EComponentType||(e.EComponentType={}));!(function(e){e[e.FRAGMENT=35632]="FRAGMENT",e[e.VERTEX=35633]="VERTEX"})(e.EShaderType||(e.EShaderType={}));!(function(e){e[e.BYTE=5120]="BYTE",e[e.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",e[e.SHORT=5122]="SHORT",e[e.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",e[e.INT=5124]="INT",e[e.UNSIGNED_INT=5125]="UNSIGNED_INT",e[e.FLOAT=5126]="FLOAT",e[e.FLOAT_VEC2=35664]="FLOAT_VEC2",e[e.FLOAT_VEC3=35665]="FLOAT_VEC3",e[e.FLOAT_VEC4=35666]="FLOAT_VEC4",e[e.INT_VEC2=35667]="INT_VEC2",e[e.INT_VEC3=35668]="INT_VEC3",e[e.INT_VEC4=35669]="INT_VEC4",e[e.BOOL=35670]="BOOL",e[e.BOOL_VEC2=35671]="BOOL_VEC2",e[e.BOOL_VEC3=35672]="BOOL_VEC3",e[e.BOOL_VEC4=35673]="BOOL_VEC4",e[e.FLOAT_MAT2=35674]="FLOAT_MAT2",e[e.FLOAT_MAT3=35675]="FLOAT_MAT3",e[e.FLOAT_MAT4=35676]="FLOAT_MAT4",e[e.SAMPLER_2D=35678]="SAMPLER_2D"})(e.EParameterType||(e.EParameterType={}));!(function(e){e[e.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",e[e.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",e[e.REPEAT=10497]="REPEAT"})(e.ETextureWrapMode||(e.ETextureWrapMode={}));!(function(e){e[e.NEAREST=9728]="NEAREST",e[e.LINEAR=9728]="LINEAR",e[e.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",e[e.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",e[e.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",e[e.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR"})(e.ETextureFilterType||(e.ETextureFilterType={}));!(function(e){e[e.ALPHA=6406]="ALPHA",e[e.RGB=6407]="RGB",e[e.RGBA=6408]="RGBA",e[e.LUMINANCE=6409]="LUMINANCE",e[e.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA"})(e.ETextureFormat||(e.ETextureFormat={}));!(function(e){e[e.FRONT=1028]="FRONT",e[e.BACK=1029]="BACK",e[e.FRONT_AND_BACK=1032]="FRONT_AND_BACK"})(e.ECullingType||(e.ECullingType={}));!(function(e){e[e.ZERO=0]="ZERO",e[e.ONE=1]="ONE",e[e.SRC_COLOR=768]="SRC_COLOR",e[e.ONE_MINUS_SRC_COLOR=769]="ONE_MINUS_SRC_COLOR",e[e.DST_COLOR=774]="DST_COLOR",e[e.ONE_MINUS_DST_COLOR=775]="ONE_MINUS_DST_COLOR",e[e.SRC_ALPHA=770]="SRC_ALPHA",e[e.ONE_MINUS_SRC_ALPHA=771]="ONE_MINUS_SRC_ALPHA",e[e.DST_ALPHA=772]="DST_ALPHA",e[e.ONE_MINUS_DST_ALPHA=773]="ONE_MINUS_DST_ALPHA",e[e.CONSTANT_COLOR=32769]="CONSTANT_COLOR",e[e.ONE_MINUS_CONSTANT_COLOR=32770]="ONE_MINUS_CONSTANT_COLOR",e[e.CONSTANT_ALPHA=32771]="CONSTANT_ALPHA",e[e.ONE_MINUS_CONSTANT_ALPHA=32772]="ONE_MINUS_CONSTANT_ALPHA",e[e.SRC_ALPHA_SATURATE=776]="SRC_ALPHA_SATURATE"})(e.EBlendingFunction||(e.EBlendingFunction={}))})(e.GLTF1||(e.GLTF1={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){var r;!(function(e){e[e.IDENTIFIER=1]="IDENTIFIER",e[e.UNKNOWN=2]="UNKNOWN",e[e.END_OF_INPUT=3]="END_OF_INPUT"})(r||(r={}));var n=(function(){function e(e){this._pos=0,this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}return e.prototype.getNextToken=function(){if(this.isEnd())return r.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=r.UNKNOWN,"_"===this.currentString||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=r.IDENTIFIER,this.currentIdentifier=this.currentString;!this.isEnd()&&(this.isLetterOrDigitPattern.test(this.currentString=this.peek())||"_"===this.currentString);)this.currentIdentifier+=this.currentString,this.forward();return this.currentToken},e.prototype.peek=function(){return this._toParse[this._pos]},e.prototype.read=function(){return this._toParse[this._pos++]},e.prototype.forward=function(){this._pos++},e.prototype.isEnd=function(){return this._pos>=this._maxPos},e})(),o=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],a=["world","view","projection","worldView","worldViewProjection","mBones"],i=["translation","rotation","scale"],s=["position","rotationQuaternion","scaling"],l=function(e,t){for(var r in e){var n=e[r];t.buffers[r]=n,t.buffersCount++}},u=function(e,t){for(var r in e){var n=e[r];t.shaders[r]=n,t.shaderscount++}},c=function(e,t,r){for(var n in e){var o=e[n];r[t][n]=o}},f=function(e){if(e)for(var t=0;t<e.length/2;t++)e[2*t+1]=1-e[2*t+1]},d=function(e){if("NORMAL"===e.semantic)return"normal";if("POSITION"===e.semantic)return"position";if("JOINT"===e.semantic)return"matricesIndices";if("WEIGHT"===e.semantic)return"matricesWeights";if("COLOR"===e.semantic)return"color";if(e.semantic&&-1!==e.semantic.indexOf("TEXCOORD_")){var t=Number(e.semantic.split("_")[1]);return"uv"+(0===t?"":t+1)}return null},h=function(r){for(var n in r.animations){var o=r.animations[n];if(o.channels&&o.samplers)for(var a=null,l=0;l<o.channels.length;l++){var u=o.channels[l],c=o.samplers[u.sampler];if(c){var f=null,d=null;o.parameters?(f=o.parameters[c.input],d=o.parameters[c.output]):(f=c.input,d=c.output);var h=t.GLTFUtils.GetBufferFromAccessor(r,r.accessors[f]),p=t.GLTFUtils.GetBufferFromAccessor(r,r.accessors[d]),m=u.target.id,T=r.scene.getNodeByID(m);if(null===T&&(T=r.scene.getNodeByName(m)),null!==T){var E=T instanceof e.Bone,_=u.target.path,A=i.indexOf(_);-1!==A&&(_=s[A]);var y=e.Animation.ANIMATIONTYPE_MATRIX;E||("rotationQuaternion"===_?(y=e.Animation.ANIMATIONTYPE_QUATERNION,T.rotationQuaternion=new e.Quaternion):y=e.Animation.ANIMATIONTYPE_VECTOR3);var g=null,v=[],L=0,x=!1;E&&a&&a.getKeys().length===h.length&&(g=a,x=!0),x||(g=new e.Animation(n,E?"_matrix":_,1,y,e.Animation.ANIMATIONLOOPMODE_CYCLE));for(var b=0;b<h.length;b++){var N=null;if("rotationQuaternion"===_?(N=e.Quaternion.FromArray([p[L],p[L+1],p[L+2],p[L+3]]),L+=4):(N=e.Vector3.FromArray([p[L],p[L+1],p[L+2]]),L+=3),E){var M=T,O=e.Vector3.Zero(),F=new e.Quaternion,R=e.Vector3.Zero(),S=M.getBaseMatrix();x&&a&&(S=a.getKeys()[b].value),S.decompose(R,F,O),"position"===_?O=N:"rotationQuaternion"===_?F=N:R=N,N=e.Matrix.Compose(R,F,O)}x?a&&(a.getKeys()[b].value=N):v.push({frame:h[b],value:N})}!x&&g&&(g.setKeys(v),T.animations.push(g)),a=g,r.scene.stopAnimation(T),r.scene.beginAnimation(T,0,h[h.length-1],!0,1)}else e.Tools.Warn("Creating animation named "+n+". But cannot find node named "+m+" to attach to")}}}},p=function(t){var r=null;if(t.translation||t.rotation||t.scale){var n=e.Vector3.FromArray(t.scale||[1,1,1]),o=e.Quaternion.FromArray(t.rotation||[0,0,0,1]),a=e.Vector3.FromArray(t.translation||[0,0,0]);r=e.Matrix.Compose(n,o,a)}else r=e.Matrix.FromArray(t.matrix);return r},m=function(t,r,n,o){for(var a=0;a<o.bones.length;a++)if(o.bones[a].name===n)return o.bones[a];var i=t.nodes;for(var s in i){var l=i[s];if(l.jointName)for(var u=l.children,a=0;a<u.length;a++){var c=t.nodes[u[a]];if(c.jointName&&c.jointName===n){var f=p(l),d=new e.Bone(l.name||"",o,m(t,r,l.jointName,o),f);return d.id=s,d}}}return null},T=function(e,t){for(var r=0;r<e.length;r++)for(var n=e[r],o=0;o<n.node.children.length;o++){var a=n.node.children[o];if(a===t)return n.bone}return null},E=function(e,t){var r=e.nodes,n=r[t];if(n)return{node:n,id:t};for(var o in r)if(n=r[o],n.jointName===t)return{node:n,id:o};return null},_=function(e,t){for(var r=0;r<e.jointNames.length;r++)if(e.jointNames[r]===t)return!0;return!1},A=function(t,r,n,o){for(var a in t.nodes){var i=t.nodes[a],s=a;if(i.jointName&&!_(n,i.jointName)){var l=p(i),u=new e.Bone(i.name||"",r,null,l);u.id=s,o.push({bone:u,node:i,id:s})}}for(var c=0;c<o.length;c++)for(var f=o[c],d=f.node.children,h=0;h<d.length;h++){for(var m=null,T=0;T<o.length;T++)if(o[T].id===d[h]){m=o[T];break}m&&(m.bone._parent=f.bone,f.bone.children.push(m.bone))}},y=function(t,r,n,o,a){if(o||(o=new e.Skeleton(r.name||"","",t.scene)),!r.babylonSkeleton)return o;var i=[],s=[];A(t,o,r,i),o.bones=[];for(var l=0;l<r.jointNames.length;l++){var u=E(t,r.jointNames[l]);if(u){var c=u.node;if(c){var a=u.id,f=t.scene.getBoneByID(a);if(f)o.bones.push(f);else{for(var d=!1,h=null,_=0;_<l;_++){var y=E(t,r.jointNames[_]);if(y){var g=y.node;if(g){var v=g.children;if(v){d=!1;for(var L=0;L<v.length;L++)if(v[L]===a){h=m(t,r,r.jointNames[_],o),d=!0;break}if(d)break}}else e.Tools.Warn("Joint named "+r.jointNames[_]+" does not exist when looking for parent")}}var x=p(c);!h&&i.length>0&&(h=T(i,a))&&-1===s.indexOf(h)&&s.push(h);new e.Bone(c.jointName||"",o,h,x).id=a}}else e.Tools.Warn("Joint named "+r.jointNames[l]+" does not exist")}}var b=o.bones;o.bones=[];for(var l=0;l<r.jointNames.length;l++){var u=E(t,r.jointNames[l]);if(u)for(var _=0;_<b.length;_++)if(b[_].id===u.id){o.bones.push(b[_]);break}}o.prepare();for(var l=0;l<s.length;l++)o.bones.push(s[l]);return o},g=function(r,n,o,a,i){if(i||(i=new e.Mesh(n.name||"",r.scene),i.id=a),!n.babylonNode)return i;var s=new e.MultiMaterial("multimat"+a,r.scene);i.material||(i.material=s);for(var l=new e.VertexData,u=new e.Geometry(a,r.scene,l,!1,i),c=new Array,d=new Array,h=new Array,p=new Array,m=0;m<o.length;m++){var T=o[m],E=r.meshes[T];if(E)for(var _=0;_<E.primitives.length;_++){var A=new e.VertexData,y=E.primitives[_];y.mode;var g=y.attributes,v=null,L=null;for(var x in g)if(v=r.accessors[g[x]],L=t.GLTFUtils.GetBufferFromAccessor(r,v),"NORMAL"===x)A.normals=new Float32Array(L.length),A.normals.set(L);else if("POSITION"===x){if(e.GLTFFileLoader.HomogeneousCoordinates){A.positions=new Float32Array(L.length-L.length/4);for(var b=0;b<L.length;b+=4)A.positions[b]=L[b],A.positions[b+1]=L[b+1],A.positions[b+2]=L[b+2]}else A.positions=new Float32Array(L.length),A.positions.set(L);d.push(A.positions.length)}else if(-1!==x.indexOf("TEXCOORD_")){var N=Number(x.split("_")[1]),M=e.VertexBuffer.UVKind+(0===N?"":N+1),O=new Float32Array(L.length);O.set(L),f(O),A.set(O,M)}else"JOINT"===x?(A.matricesIndices=new Float32Array(L.length),A.matricesIndices.set(L)):"WEIGHT"===x?(A.matricesWeights=new Float32Array(L.length),A.matricesWeights.set(L)):"COLOR"===x&&(A.colors=new Float32Array(L.length),A.colors.set(L));if(v=r.accessors[y.indices])L=t.GLTFUtils.GetBufferFromAccessor(r,v),A.indices=new Int32Array(L.length),A.indices.set(L),p.push(A.indices.length);else{for(var F=[],b=0;b<A.positions.length/3;b++)F.push(b);A.indices=new Int32Array(F),p.push(A.indices.length)}l.merge(A);var R=r.scene.getMaterialByID(y.material);s.subMaterials.push(null===R?t.GLTFUtils.GetDefaultMaterial(r.scene):R),c.push(0===c.length?0:c[c.length-1]+d[d.length-2]),h.push(0===h.length?0:h[h.length-1]+p[p.length-2])}}u.setAllVerticesData(l,!1),i.computeWorldMatrix(!0),i.subMeshes=[];for(var S=0,m=0;m<o.length;m++){var T=o[m],E=r.meshes[T];if(E)for(var _=0;_<E.primitives.length;_++)E.primitives[_].mode,e.SubMesh.AddToMesh(S,c[S],d[S],h[S],p[S],i,i,!0),S++}return i},v=function(e,t,r,n){e.position&&(e.position=t),(e.rotationQuaternion||e.rotation)&&(e.rotationQuaternion=r),e.scaling&&(e.scaling=n)},L=function(t,r,n){if(r.matrix){var o=new e.Vector3(0,0,0),a=new e.Quaternion,i=new e.Vector3(0,0,0);e.Matrix.FromArray(r.matrix).decompose(i,a,o),v(t,o,a,i)}else r.translation&&r.rotation&&r.scale&&v(t,e.Vector3.FromArray(r.translation),e.Quaternion.FromArray(r.rotation),e.Vector3.FromArray(r.scale));t.computeWorldMatrix(!0)},x=function(t,r,n,o){var a=null;if(t.importOnlyMeshes&&(r.skin||r.meshes)&&t.importMeshesNames&&t.importMeshesNames.length>0&&-1===t.importMeshesNames.indexOf(r.name||""))return null;if(r.skin){if(r.meshes){var i=t.skins[r.skin],s=g(t,r,r.meshes,n,r.babylonNode);s.skeleton=t.scene.getLastSkeletonByID(r.skin),null===s.skeleton&&i.babylonSkeleton&&(s.skeleton=y(t,i,0,i.babylonSkeleton,r.skin),i.babylonSkeleton||(i.babylonSkeleton=s.skeleton)),a=s}}else if(r.meshes){var s=g(t,r,r.mesh?[r.mesh]:r.meshes,n,r.babylonNode);a=s}else if(!r.light||r.babylonNode||t.importOnlyMeshes){if(r.camera&&!r.babylonNode&&!t.importOnlyMeshes){var l=t.cameras[r.camera];if(l)if("orthographic"===l.type){var u=new e.FreeCamera(r.camera,e.Vector3.Zero(),t.scene);u.name=r.name||"",u.mode=e.Camera.ORTHOGRAPHIC_CAMERA,u.attachControl(t.scene.getEngine().getRenderingCanvas()),a=u}else if("perspective"===l.type){var c=l[l.type],f=new e.FreeCamera(r.camera,e.Vector3.Zero(),t.scene);f.name=r.name||"",f.attachControl(t.scene.getEngine().getRenderingCanvas()),c.aspectRatio||(c.aspectRatio=t.scene.getEngine().getRenderWidth()/t.scene.getEngine().getRenderHeight()),c.znear&&c.zfar&&(f.maxZ=c.zfar,f.minZ=c.znear),a=f}}}else{var d=t.lights[r.light];if(d)if("ambient"===d.type){var h=d[d.type],p=new e.HemisphericLight(r.light,e.Vector3.Zero(),t.scene);p.name=r.name||"",h.color&&(p.diffuse=e.Color3.FromArray(h.color)),a=p}else if("directional"===d.type){var m=d[d.type],T=new e.DirectionalLight(r.light,e.Vector3.Zero(),t.scene);T.name=r.name||"",m.color&&(T.diffuse=e.Color3.FromArray(m.color)),a=T}else if("point"===d.type){var E=d[d.type],_=new e.PointLight(r.light,e.Vector3.Zero(),t.scene);_.name=r.name||"",E.color&&(_.diffuse=e.Color3.FromArray(E.color)),a=_}else if("spot"===d.type){var A=d[d.type],x=new e.SpotLight(r.light,e.Vector3.Zero(),e.Vector3.Zero(),0,0,t.scene);x.name=r.name||"",A.color&&(x.diffuse=e.Color3.FromArray(A.color)),A.fallOfAngle&&(x.angle=A.fallOfAngle),A.fallOffExponent&&(x.exponent=A.fallOffExponent),a=x}}if(!r.jointName){if(r.babylonNode)return r.babylonNode;if(null===a){var b=new e.Mesh(r.name||"",t.scene);r.babylonNode=b,a=b}}if(null!==a){if(r.matrix&&a instanceof e.Mesh)L(a,r);else{var N=r.translation||[0,0,0],M=r.rotation||[0,0,0,1],O=r.scale||[1,1,1];v(a,e.Vector3.FromArray(N),e.Quaternion.FromArray(M),e.Vector3.FromArray(O))}a.updateCache(!0),r.babylonNode=a}return a},b=function(e,t,r,n){void 0===n&&(n=!1);var o=e.nodes[t],a=null;if(n=!(e.importOnlyMeshes&&!n&&e.importMeshesNames)||(-1!==e.importMeshesNames.indexOf(o.name||"")||0===e.importMeshesNames.length),!o.jointName&&n&&null!==(a=x(e,o,t))&&(a.id=t,a.parent=r),o.children)for(var i=0;i<o.children.length;i++)b(e,o.children[i],a,n)},N=function(e){var t=e.currentScene;if(t)for(var r=0;r<t.nodes.length;r++)b(e,t.nodes[r],null);else for(var n in e.scenes){t=e.scenes[n];for(var r=0;r<t.nodes.length;r++)b(e,t.nodes[r],null)}h(e);for(var r=0;r<e.scene.skeletons.length;r++){var o=e.scene.skeletons[r];e.scene.beginAnimation(o,0,Number.MAX_VALUE,!0,1)}},M=function(e,r,n,o,a,i,s){var l=i.values||a.parameters;for(var u in n){var c=n[u],f=c.type;if(f===t.EParameterType.FLOAT_MAT2||f===t.EParameterType.FLOAT_MAT3||f===t.EParameterType.FLOAT_MAT4)if(!c.semantic||c.source||c.node){if(c.semantic&&(c.source||c.node)){var d=r.scene.getNodeByName(c.source||c.node||"");if(null===d&&(d=r.scene.getNodeByID(c.source||c.node||"")),null===d)continue;t.GLTFUtils.SetMatrix(r.scene,d,c,u,o.getEffect())}}else t.GLTFUtils.SetMatrix(r.scene,e,c,u,o.getEffect());else{var h=l[a.uniforms[u]];if(!h)continue;if(f===t.EParameterType.SAMPLER_2D){var p=r.textures[i.values?h:c.value].babylonTexture;if(null===p||void 0===p)continue;o.getEffect().setTexture(u,p)}else t.GLTFUtils.SetUniform(o.getEffect(),u,h,f)}}s(o)},O=function(e,r,n,o,a){var i=o.values||n.parameters,s=n.uniforms;for(var l in a){var u=a[l],c=u.type,f=i[s[l]];if(void 0===f&&(f=u.value),f){var d=function(e){return function(t){u.value&&e&&(r.setTexture(e,t),delete a[e])}};c===t.EParameterType.SAMPLER_2D?t.GLTFLoaderExtension.LoadTextureAsync(e,o.values?f:u.value,d(l),(function(){return d(null)})):u.value&&t.GLTFUtils.SetUniform(r,l,o.values?f:u.value,c)&&delete a[l]}}},F=function(e,t,r){return function(n,o){t.dispose(!0),r("Cannot compile program named "+e.name+". Error: "+o+". Default material will be applied")}},R=function(e,t,r,n,o,a){return function(i){O(e,t,r,n,o),t.onBind=function(i){M(i,e,o,t,r,n,a)}}},S=function(e,t,r){for(var n in t.uniforms){var i=t.uniforms[n],s=t.parameters[i];if(e.currentIdentifier===n&&s.semantic&&!s.source&&!s.node){var l=o.indexOf(s.semantic);if(-1!==l)return delete r[n],a[l]}}return e.currentIdentifier},I=function(e){for(var r in e.materials)t.GLTFLoaderExtension.LoadMaterialAsync(e,r,(function(e){}),(function(){}))},w=(function(){function i(){}return i.CreateRuntime=function(e,t,r){var n={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:r,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[]};return e.extensions&&c(e.extensions,"extensions",n),e.extensionsUsed&&c(e.extensionsUsed,"extensionsUsed",n),e.buffers&&l(e.buffers,n),e.bufferViews&&c(e.bufferViews,"bufferViews",n),e.accessors&&c(e.accessors,"accessors",n),e.meshes&&c(e.meshes,"meshes",n),e.lights&&c(e.lights,"lights",n),e.cameras&&c(e.cameras,"cameras",n),e.nodes&&c(e.nodes,"nodes",n),e.images&&c(e.images,"images",n),e.textures&&c(e.textures,"textures",n),e.shaders&&u(e.shaders,n),e.programs&&c(e.programs,"programs",n),e.samplers&&c(e.samplers,"samplers",n),e.techniques&&c(e.techniques,"techniques",n),e.materials&&c(e.materials,"materials",n),e.animations&&c(e.animations,"animations",n),e.skins&&c(e.skins,"skins",n),e.scenes&&(n.scenes=e.scenes),e.scene&&e.scenes&&(n.currentScene=e.scenes[e.scene]),n},i.LoadBufferAsync=function(r,n,o,a,i){var s=r.buffers[n];t.GLTFUtils.IsBase64(s.uri)?setTimeout((function(){return o(new Uint8Array(t.GLTFUtils.DecodeBase64(s.uri)))})):e.Tools.LoadFile(r.rootUrl+s.uri,(function(e){return o(new Uint8Array(e))}),i,void 0,!0,(function(e){e&&a(e.status+" "+e.statusText)}))},i.LoadTextureBufferAsync=function(r,n,o,a){var i=r.textures[n];if(!i||!i.source)return void a("");if(i.babylonTexture)return void o(null);var s=r.images[i.source];t.GLTFUtils.IsBase64(s.uri)?setTimeout((function(){return o(new Uint8Array(t.GLTFUtils.DecodeBase64(s.uri)))})):e.Tools.LoadFile(r.rootUrl+s.uri,(function(e){return o(new Uint8Array(e))}),void 0,void 0,!0,(function(e){e&&a(e.status+" "+e.statusText)}))},i.CreateTextureAsync=function(r,n,o,a,i){var s=r.textures[n];if(s.babylonTexture)return void a(s.babylonTexture);var l=r.samplers[s.sampler],u=l.minFilter===t.ETextureFilterType.NEAREST_MIPMAP_NEAREST||l.minFilter===t.ETextureFilterType.NEAREST_MIPMAP_LINEAR||l.minFilter===t.ETextureFilterType.LINEAR_MIPMAP_NEAREST||l.minFilter===t.ETextureFilterType.LINEAR_MIPMAP_LINEAR,c=e.Texture.BILINEAR_SAMPLINGMODE,f=new Blob([o]),d=URL.createObjectURL(f),h=function(){return URL.revokeObjectURL(d)},p=new e.Texture(d,r.scene,!u,!0,c,h,h);void 0!==l.wrapS&&(p.wrapU=t.GLTFUtils.GetWrapMode(l.wrapS)),void 0!==l.wrapT&&(p.wrapV=t.GLTFUtils.GetWrapMode(l.wrapT)),p.name=n,
  101765. s.babylonTexture=p,a(p)},i.LoadShaderStringAsync=function(r,n,o,a){var i=r.shaders[n];if(t.GLTFUtils.IsBase64(i.uri)){o(atob(i.uri.split(",")[1]))}else e.Tools.LoadFile(r.rootUrl+i.uri,o,void 0,void 0,!1,(function(e){e&&a(e.status+" "+e.statusText)}))},i.LoadMaterialAsync=function(i,s,l,u){var c=i.materials[s];if(!c.technique)return void(u&&u("No technique found."));var f=i.techniques[c.technique];if(!f){var h=new e.StandardMaterial(s,i.scene);return h.diffuseColor=new e.Color3(.5,.5,.5),h.sideOrientation=e.Material.CounterClockWiseSideOrientation,void l(h)}var p=i.programs[f.program],m=f.states,T=e.Effect.ShadersStore[p.vertexShader+"VertexShader"],E=e.Effect.ShadersStore[p.fragmentShader+"PixelShader"],_="",A="",y=new n(T),g=new n(E),v={},L=[],x=[],b=[];for(var N in f.uniforms){var M=f.uniforms[N],O=f.parameters[M];if(v[N]=O,!O.semantic||O.node||O.source)O.type===t.EParameterType.SAMPLER_2D?b.push(N):L.push(N);else{var I=o.indexOf(O.semantic);-1!==I?(L.push(a[I]),delete v[N]):L.push(N)}}for(var w in f.attributes){var P=f.attributes[w],B=f.parameters[P];B.semantic&&x.push(d(B))}for(;!y.isEnd()&&y.getNextToken();){var C=y.currentToken;if(C===r.IDENTIFIER){var G=!1;for(var w in f.attributes){var P=f.attributes[w],B=f.parameters[P];if(y.currentIdentifier===w&&B.semantic){_+=d(B),G=!0;break}}G||(_+=S(y,f,v))}else _+=y.currentString}for(;!g.isEnd()&&g.getNextToken();){var C=g.currentToken;C===r.IDENTIFIER?A+=S(g,f,v):A+=g.currentString}var D={vertex:p.vertexShader+s,fragment:p.fragmentShader+s},V={attributes:x,uniforms:L,samplers:b,needAlphaBlending:m&&m.enable&&-1!==m.enable.indexOf(3042)};e.Effect.ShadersStore[p.vertexShader+s+"VertexShader"]=_,e.Effect.ShadersStore[p.fragmentShader+s+"PixelShader"]=A;var U=new e.ShaderMaterial(s,i.scene,D,V);if(U.onError=F(p,U,u),U.onCompiled=R(i,U,f,c,v,l),U.sideOrientation=e.Material.CounterClockWiseSideOrientation,m&&m.functions){var k=m.functions;k.cullFace&&k.cullFace[0]!==t.ECullingType.BACK&&(U.backFaceCulling=!1);var H=k.blendFuncSeparate;H&&(H[0]===t.EBlendingFunction.SRC_ALPHA&&H[1]===t.EBlendingFunction.ONE_MINUS_SRC_ALPHA&&H[2]===t.EBlendingFunction.ONE&&H[3]===t.EBlendingFunction.ONE?U.alphaMode=e.Engine.ALPHA_COMBINE:H[0]===t.EBlendingFunction.ONE&&H[1]===t.EBlendingFunction.ONE&&H[2]===t.EBlendingFunction.ZERO&&H[3]===t.EBlendingFunction.ONE?U.alphaMode=e.Engine.ALPHA_ONEONE:H[0]===t.EBlendingFunction.SRC_ALPHA&&H[1]===t.EBlendingFunction.ONE&&H[2]===t.EBlendingFunction.ZERO&&H[3]===t.EBlendingFunction.ONE?U.alphaMode=e.Engine.ALPHA_ADD:H[0]===t.EBlendingFunction.ZERO&&H[1]===t.EBlendingFunction.ONE_MINUS_SRC_COLOR&&H[2]===t.EBlendingFunction.ONE&&H[3]===t.EBlendingFunction.ONE?U.alphaMode=e.Engine.ALPHA_SUBTRACT:H[0]===t.EBlendingFunction.DST_COLOR&&H[1]===t.EBlendingFunction.ZERO&&H[2]===t.EBlendingFunction.ONE&&H[3]===t.EBlendingFunction.ONE?U.alphaMode=e.Engine.ALPHA_MULTIPLY:H[0]===t.EBlendingFunction.SRC_ALPHA&&H[1]===t.EBlendingFunction.ONE_MINUS_SRC_COLOR&&H[2]===t.EBlendingFunction.ONE&&H[3]===t.EBlendingFunction.ONE&&(U.alphaMode=e.Engine.ALPHA_MAXIMIZED))}},i})();t.GLTFLoaderBase=w;var P=(function(){function r(){}return r.RegisterExtension=function(t){if(r.Extensions[t.name])return void e.Tools.Error('Tool with the same name "'+t.name+'" already exists');r.Extensions[t.name]=t},r.prototype.dispose=function(){},r.prototype.importMeshAsync=function(r,n,o,a,i,s,l){var u=this;return n.useRightHandedSystem=!0,t.GLTFLoaderExtension.LoadRuntimeAsync(n,o,a,(function(t){t.importOnlyMeshes=!0,""===r?t.importMeshesNames=[]:"string"==typeof r?t.importMeshesNames=[r]:!r||r instanceof Array?(t.importMeshesNames=[],e.Tools.Warn("Argument meshesNames must be of type string or string[]")):t.importMeshesNames=[r],u._createNodes(t);var n=new Array,o=new Array;for(var a in t.nodes){var l=t.nodes[a];l.babylonNode instanceof e.AbstractMesh&&n.push(l.babylonNode)}for(var c in t.skins){var f=t.skins[c];f.babylonSkeleton instanceof e.Skeleton&&o.push(f.babylonSkeleton)}u._loadBuffersAsync(t,(function(){u._loadShadersAsync(t,(function(){I(t),N(t),!e.GLTFFileLoader.IncrementalLoading&&i&&i(n,[],o)}))}),s),e.GLTFFileLoader.IncrementalLoading&&i&&i(n,[],o)}),l),!0},r.prototype.loadAsync=function(r,n,o,a,i,s){var l=this;r.useRightHandedSystem=!0,t.GLTFLoaderExtension.LoadRuntimeAsync(r,n,o,(function(r){t.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(r,(function(){l._createNodes(r),l._loadBuffersAsync(r,(function(){l._loadShadersAsync(r,(function(){I(r),N(r),e.GLTFFileLoader.IncrementalLoading||a()}))})),e.GLTFFileLoader.IncrementalLoading&&a()}),s)}),s)},r.prototype._loadShadersAsync=function(r,n){var o=!1,a=function(o,a){t.GLTFLoaderExtension.LoadShaderStringAsync(r,o,(function(i){r.loadedShaderCount++,i&&(e.Effect.ShadersStore[o+(a.type===t.EShaderType.VERTEX?"VertexShader":"PixelShader")]=i),r.loadedShaderCount===r.shaderscount&&n()}),(function(){e.Tools.Error("Error when loading shader program named "+o+" located at "+a.uri)}))};for(var i in r.shaders){o=!0;var s=r.shaders[i];s?a.bind(this,i,s)():e.Tools.Error("No shader named: "+i)}o||n()},r.prototype._loadBuffersAsync=function(r,n,o){var a=!1,i=function(o,a){t.GLTFLoaderExtension.LoadBufferAsync(r,o,(function(t){r.loadedBufferCount++,t&&(t.byteLength!=r.buffers[o].byteLength&&e.Tools.Error("Buffer named "+o+" is length "+t.byteLength+". Expected: "+a.byteLength),r.loadedBufferViews[o]=t),r.loadedBufferCount===r.buffersCount&&n()}),(function(){e.Tools.Error("Error when loading buffer named "+o+" located at "+a.uri)}))};for(var s in r.buffers){a=!0;var l=r.buffers[s];l?i.bind(this,s,l)():e.Tools.Error("No buffer named: "+s)}a||n()},r.prototype._createNodes=function(e){var t=e.currentScene;if(t)for(var r=0;r<t.nodes.length;r++)b(e,t.nodes[r],null);else for(var n in e.scenes){t=e.scenes[n];for(var r=0;r<t.nodes.length;r++)b(e,t.nodes[r],null)}},r.Extensions={},r})();t.GLTFLoader=P,e.GLTFFileLoader.CreateGLTFLoaderV1=function(){return new P}})(e.GLTF1||(e.GLTF1={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){var r=(function(){function r(){}return r.SetMatrix=function(r,n,o,a,i){var s=null;if("MODEL"===o.semantic?s=n.getWorldMatrix():"PROJECTION"===o.semantic?s=r.getProjectionMatrix():"VIEW"===o.semantic?s=r.getViewMatrix():"MODELVIEWINVERSETRANSPOSE"===o.semantic?s=e.Matrix.Transpose(n.getWorldMatrix().multiply(r.getViewMatrix()).invert()):"MODELVIEW"===o.semantic?s=n.getWorldMatrix().multiply(r.getViewMatrix()):"MODELVIEWPROJECTION"===o.semantic?s=n.getWorldMatrix().multiply(r.getTransformMatrix()):"MODELINVERSE"===o.semantic?s=n.getWorldMatrix().invert():"VIEWINVERSE"===o.semantic?s=r.getViewMatrix().invert():"PROJECTIONINVERSE"===o.semantic?s=r.getProjectionMatrix().invert():"MODELVIEWINVERSE"===o.semantic?s=n.getWorldMatrix().multiply(r.getViewMatrix()).invert():"MODELVIEWPROJECTIONINVERSE"===o.semantic?s=n.getWorldMatrix().multiply(r.getTransformMatrix()).invert():"MODELINVERSETRANSPOSE"===o.semantic&&(s=e.Matrix.Transpose(n.getWorldMatrix().invert())),s)switch(o.type){case t.EParameterType.FLOAT_MAT2:i.setMatrix2x2(a,e.Matrix.GetAsMatrix2x2(s));break;case t.EParameterType.FLOAT_MAT3:i.setMatrix3x3(a,e.Matrix.GetAsMatrix3x3(s));break;case t.EParameterType.FLOAT_MAT4:i.setMatrix(a,s)}},r.SetUniform=function(r,n,o,a){switch(a){case t.EParameterType.FLOAT:return r.setFloat(n,o),!0;case t.EParameterType.FLOAT_VEC2:return r.setVector2(n,e.Vector2.FromArray(o)),!0;case t.EParameterType.FLOAT_VEC3:return r.setVector3(n,e.Vector3.FromArray(o)),!0;case t.EParameterType.FLOAT_VEC4:return r.setVector4(n,e.Vector4.FromArray(o)),!0;default:return!1}},r.IsBase64=function(e){return!(e.length<5)&&"data:"===e.substr(0,5)},r.DecodeBase64=function(e){for(var t=atob(e.split(",")[1]),r=t.length,n=new Uint8Array(new ArrayBuffer(r)),o=0;o<r;o++)n[o]=t.charCodeAt(o);return n.buffer},r.GetWrapMode=function(r){switch(r){case t.ETextureWrapMode.CLAMP_TO_EDGE:return e.Texture.CLAMP_ADDRESSMODE;case t.ETextureWrapMode.MIRRORED_REPEAT:return e.Texture.MIRROR_ADDRESSMODE;case t.ETextureWrapMode.REPEAT:default:return e.Texture.WRAP_ADDRESSMODE}},r.GetByteStrideFromType=function(e){switch(e.type){case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 1}},r.GetTextureFilterMode=function(r){switch(r){case t.ETextureFilterType.LINEAR:case t.ETextureFilterType.LINEAR_MIPMAP_NEAREST:case t.ETextureFilterType.LINEAR_MIPMAP_LINEAR:return e.Texture.TRILINEAR_SAMPLINGMODE;case t.ETextureFilterType.NEAREST:case t.ETextureFilterType.NEAREST_MIPMAP_NEAREST:return e.Texture.NEAREST_SAMPLINGMODE;default:return e.Texture.BILINEAR_SAMPLINGMODE}},r.GetBufferFromBufferView=function(e,r,n,o,a){var n=r.byteOffset+n,i=e.loadedBufferViews[r.buffer];if(n+o>i.byteLength)throw new Error("Buffer access is out of range");var s=i.buffer;switch(n+=i.byteOffset,a){case t.EComponentType.BYTE:return new Int8Array(s,n,o);case t.EComponentType.UNSIGNED_BYTE:return new Uint8Array(s,n,o);case t.EComponentType.SHORT:return new Int16Array(s,n,o);case t.EComponentType.UNSIGNED_SHORT:return new Uint16Array(s,n,o);default:return new Float32Array(s,n,o)}},r.GetBufferFromAccessor=function(e,t){var n=e.bufferViews[t.bufferView],o=t.count*r.GetByteStrideFromType(t);return r.GetBufferFromBufferView(e,n,t.byteOffset,o,t.componentType)},r.DecodeBufferToText=function(e){for(var t="",r=e.byteLength,n=0;n<r;++n)t+=String.fromCharCode(e[n]);return t},r.GetDefaultMaterial=function(t){if(!r._DefaultMaterial){e.Effect.ShadersStore.GLTFDefaultMaterialVertexShader=["precision highp float;","","uniform mat4 worldView;","uniform mat4 projection;","","attribute vec3 position;","","void main(void)","{"," gl_Position = projection * worldView * vec4(position, 1.0);","}"].join("\n"),e.Effect.ShadersStore.GLTFDefaultMaterialPixelShader=["precision highp float;","","uniform vec4 u_emission;","","void main(void)","{"," gl_FragColor = u_emission;","}"].join("\n");var n={vertex:"GLTFDefaultMaterial",fragment:"GLTFDefaultMaterial"},o={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};r._DefaultMaterial=new e.ShaderMaterial("GLTFDefaultMaterial",t,n,o),r._DefaultMaterial.setColor4("u_emission",new e.Color4(.5,.5,.5,1))}return r._DefaultMaterial},r._DefaultMaterial=null,r})();t.GLTFUtils=r})(e.GLTF1||(e.GLTF1={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){var t=(function(){function t(e){this._name=e}return Object.defineProperty(t.prototype,"name",{get:function(){return this._name},enumerable:!0,configurable:!0}),t.prototype.loadRuntimeAsync=function(e,t,r,n,o){return!1},t.prototype.loadRuntimeExtensionsAsync=function(e,t,r){return!1},t.prototype.loadBufferAsync=function(e,t,r,n,o){return!1},t.prototype.loadTextureBufferAsync=function(e,t,r,n){return!1},t.prototype.createTextureAsync=function(e,t,r,n,o){return!1},t.prototype.loadShaderStringAsync=function(e,t,r,n){return!1},t.prototype.loadMaterialAsync=function(e,t,r,n){return!1},t.LoadRuntimeAsync=function(r,n,o,a,i){t.ApplyExtensions((function(e){return e.loadRuntimeAsync(r,n,o,a,i)}),(function(){setTimeout((function(){a(e.GLTFLoaderBase.CreateRuntime(n.json,r,o))}))}))},t.LoadRuntimeExtensionsAsync=function(e,r,n){t.ApplyExtensions((function(t){return t.loadRuntimeExtensionsAsync(e,r,n)}),(function(){setTimeout((function(){r()}))}))},t.LoadBufferAsync=function(r,n,o,a,i){t.ApplyExtensions((function(e){return e.loadBufferAsync(r,n,o,a,i)}),(function(){e.GLTFLoaderBase.LoadBufferAsync(r,n,o,a,i)}))},t.LoadTextureAsync=function(e,r,n,o){t.LoadTextureBufferAsync(e,r,(function(a){return t.CreateTextureAsync(e,r,a,n,o)}),o)},t.LoadShaderStringAsync=function(r,n,o,a){t.ApplyExtensions((function(e){return e.loadShaderStringAsync(r,n,o,a)}),(function(){e.GLTFLoaderBase.LoadShaderStringAsync(r,n,o,a)}))},t.LoadMaterialAsync=function(r,n,o,a){t.ApplyExtensions((function(e){return e.loadMaterialAsync(r,n,o,a)}),(function(){e.GLTFLoaderBase.LoadMaterialAsync(r,n,o,a)}))},t.LoadTextureBufferAsync=function(r,n,o,a){t.ApplyExtensions((function(e){return e.loadTextureBufferAsync(r,n,o,a)}),(function(){e.GLTFLoaderBase.LoadTextureBufferAsync(r,n,o,a)}))},t.CreateTextureAsync=function(r,n,o,a,i){t.ApplyExtensions((function(e){return e.createTextureAsync(r,n,o,a,i)}),(function(){e.GLTFLoaderBase.CreateTextureAsync(r,n,o,a,i)}))},t.ApplyExtensions=function(t,r){for(var n in e.GLTFLoader.Extensions){if(t(e.GLTFLoader.Extensions[n]))return}r()},t})();e.GLTFLoaderExtension=t})(e.GLTF1||(e.GLTF1={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){var t=(function(t){function r(){return t.call(this,"KHR_binary_glTF")||this}return __extends(r,t),r.prototype.loadRuntimeAsync=function(t,r,n,o,a){var i=r.json.extensionsUsed;return!(!i||-1===i.indexOf(this.name)||!r.bin)&&(this._bin=r.bin,o(e.GLTFLoaderBase.CreateRuntime(r.json,t,n)),!0)},r.prototype.loadBufferAsync=function(e,t,r,n){return-1!==e.extensionsUsed.indexOf(this.name)&&("binary_glTF"===t&&(r(this._bin),!0))},r.prototype.loadTextureBufferAsync=function(t,r,n,o){var a=t.textures[r],i=t.images[a.source];if(!(i.extensions&&this.name in i.extensions))return!1;var s=i.extensions[this.name],l=t.bufferViews[s.bufferView];return n(e.GLTFUtils.GetBufferFromBufferView(t,l,0,l.byteLength,e.EComponentType.UNSIGNED_BYTE)),!0},r.prototype.loadShaderStringAsync=function(t,r,n,o){var a=t.shaders[r];if(!(a.extensions&&this.name in a.extensions))return!1;var i=a.extensions[this.name],s=t.bufferViews[i.bufferView],l=e.GLTFUtils.GetBufferFromBufferView(t,s,0,s.byteLength,e.EComponentType.UNSIGNED_BYTE);return setTimeout((function(){var t=e.GLTFUtils.DecodeBufferToText(l);n(t)})),!0},r})(e.GLTFLoaderExtension);e.GLTFBinaryExtension=t,e.GLTFLoader.RegisterExtension(new t)})(e.GLTF1||(e.GLTF1={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){var r=(function(r){function n(){return r.call(this,"KHR_materials_common")||this}return __extends(n,r),n.prototype.loadRuntimeExtensionsAsync=function(t,r,n){if(!t.extensions)return!1;var o=t.extensions[this.name];if(!o)return!1;var a=o.lights;if(a)for(var i in a){var s=a[i];switch(s.type){case"ambient":var l=new e.HemisphericLight(s.name,new e.Vector3(0,1,0),t.scene),u=s.ambient;u&&(l.diffuse=e.Color3.FromArray(u.color||[1,1,1]));break;case"point":var c=new e.PointLight(s.name,new e.Vector3(10,10,10),t.scene),f=s.point;f&&(c.diffuse=e.Color3.FromArray(f.color||[1,1,1]));break;case"directional":var d=new e.DirectionalLight(s.name,new e.Vector3(0,-1,0),t.scene),h=s.directional;h&&(d.diffuse=e.Color3.FromArray(h.color||[1,1,1]));break;case"spot":var p=s.spot;if(p){var m=new e.SpotLight(s.name,new e.Vector3(0,10,0),new e.Vector3(0,-1,0),p.fallOffAngle||Math.PI,p.fallOffExponent||0,t.scene);m.diffuse=e.Color3.FromArray(p.color||[1,1,1])}break;default:e.Tools.Warn('GLTF Material Common extension: light type "'+s.type+"” not supported")}}return!1},n.prototype.loadMaterialAsync=function(t,r,n,o){var a=t.materials[r];if(!a||!a.extensions)return!1;var i=a.extensions[this.name];if(!i)return!1;var s=new e.StandardMaterial(r,t.scene);return s.sideOrientation=e.Material.CounterClockWiseSideOrientation,"CONSTANT"===i.technique&&(s.disableLighting=!0),s.backFaceCulling=void 0!==i.doubleSided&&!i.doubleSided,s.alpha=void 0===i.values.transparency?1:i.values.transparency,s.specularPower=void 0===i.values.shininess?0:i.values.shininess,"string"==typeof i.values.ambient?this._loadTexture(t,i.values.ambient,s,"ambientTexture",o):s.ambientColor=e.Color3.FromArray(i.values.ambient||[0,0,0]),"string"==typeof i.values.diffuse?this._loadTexture(t,i.values.diffuse,s,"diffuseTexture",o):s.diffuseColor=e.Color3.FromArray(i.values.diffuse||[0,0,0]),"string"==typeof i.values.emission?this._loadTexture(t,i.values.emission,s,"emissiveTexture",o):s.emissiveColor=e.Color3.FromArray(i.values.emission||[0,0,0]),"string"==typeof i.values.specular?this._loadTexture(t,i.values.specular,s,"specularTexture",o):s.specularColor=e.Color3.FromArray(i.values.specular||[0,0,0]),!0},n.prototype._loadTexture=function(e,r,n,o,a){t.GLTFLoaderBase.LoadTextureBufferAsync(e,r,(function(i){t.GLTFLoaderBase.CreateTextureAsync(e,r,i,(function(e){return n[o]=e}),a)}),a)},n})(t.GLTFLoaderExtension);t.GLTFMaterialsCommonExtension=r,t.GLTFLoader.RegisterExtension(new r)})(e.GLTF1||(e.GLTF1={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){!(function(e){e[e.BYTE=5120]="BYTE",e[e.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",e[e.SHORT=5122]="SHORT",e[e.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",e[e.UNSIGNED_INT=5125]="UNSIGNED_INT",e[e.FLOAT=5126]="FLOAT"})(e.EComponentType||(e.EComponentType={}));!(function(e){e[e.POINTS=0]="POINTS",e[e.LINES=1]="LINES",e[e.LINE_LOOP=2]="LINE_LOOP",e[e.LINE_STRIP=3]="LINE_STRIP",e[e.TRIANGLES=4]="TRIANGLES",e[e.TRIANGLE_STRIP=5]="TRIANGLE_STRIP",e[e.TRIANGLE_FAN=6]="TRIANGLE_FAN"})(e.EMeshPrimitiveMode||(e.EMeshPrimitiveMode={}));!(function(e){e[e.NEAREST=9728]="NEAREST",e[e.LINEAR=9729]="LINEAR"})(e.ETextureMagFilter||(e.ETextureMagFilter={}));!(function(e){e[e.NEAREST=9728]="NEAREST",e[e.LINEAR=9729]="LINEAR",e[e.NEAREST_MIPMAP_NEAREST=9984]="NEAREST_MIPMAP_NEAREST",e[e.LINEAR_MIPMAP_NEAREST=9985]="LINEAR_MIPMAP_NEAREST",e[e.NEAREST_MIPMAP_LINEAR=9986]="NEAREST_MIPMAP_LINEAR",e[e.LINEAR_MIPMAP_LINEAR=9987]="LINEAR_MIPMAP_LINEAR"})(e.ETextureMinFilter||(e.ETextureMinFilter={}));!(function(e){e[e.CLAMP_TO_EDGE=33071]="CLAMP_TO_EDGE",e[e.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",e[e.REPEAT=10497]="REPEAT"})(e.ETextureWrapMode||(e.ETextureWrapMode={}))})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){var r=(function(){function e(e){this._pendingCount=0,this._callback=e}return e.prototype._addPendingData=function(e){this._pendingCount++},e.prototype._removePendingData=function(e){0==--this._pendingCount&&this._callback()},e})(),n=(function(){function n(t){this._disposed=!1,this._renderReady=!1,this._requests=new Array,this._renderReadyObservable=new e.Observable,this._renderPendingCount=0,this._loaderPendingCount=0,this._loaderTrackers=new Array,this._parent=t}return n.RegisterExtension=function(r){if(n.Extensions[r.name])return void e.Tools.Error("Extension with the same name '"+r.name+"' already exists");n.Extensions[r.name]=r,t.GLTFLoaderExtension._Extensions.push(r)},n.prototype.dispose=function(){if(!this._disposed){this._disposed=!0;for(var e=0,t=this._requests;e<t.length;e++){var r=t[e];r.readyState!==(XMLHttpRequest.DONE||4)&&r.abort()}if(this._gltf.textures)for(var n=0,o=this._gltf.textures;n<o.length;n++){var a=o[n];a.url&&URL.revokeObjectURL(a.url)}}},n.prototype.importMeshAsync=function(e,t,r,n,o,a,i){var s=this;this._loadAsync(e,t,r,n,(function(){o(s._getMeshes(),[],s._getSkeletons())}),a,i)},n.prototype.loadAsync=function(e,t,r,n,o,a){this._loadAsync(null,e,t,r,n,o,a)},n.prototype._loadAsync=function(e,t,r,n,o,a,i){var s=this;this._tryCatchOnError((function(){s._loadData(r),s._babylonScene=t,s._rootUrl=n,s._successCallback=o,s._progressCallback=a,s._errorCallback=i,s._addPendingData(s),s._loadDefaultScene(e),s._loadAnimations(),s._removePendingData(s)}))},n.prototype._onProgress=function(e){this._progressCallback&&this._progressCallback(e)},n.prototype._executeWhenRenderReady=function(e){this._renderReady?e():this._renderReadyObservable.add(e)},n.prototype._onRenderReady=function(){this._rootNode.babylonMesh.setEnabled(!0),this._startAnimations(),this._successCallback(),this._renderReadyObservable.notifyObservers(this)},n.prototype._onComplete=function(){this._parent.onComplete&&this._parent.onComplete(),this.dispose()},n.prototype._loadData=function(t){if(this._gltf=t.json,n._AssignIndices(this._gltf.accessors),n._AssignIndices(this._gltf.animations),n._AssignIndices(this._gltf.buffers),n._AssignIndices(this._gltf.bufferViews),n._AssignIndices(this._gltf.images),n._AssignIndices(this._gltf.materials),n._AssignIndices(this._gltf.meshes),n._AssignIndices(this._gltf.nodes),n._AssignIndices(this._gltf.scenes),n._AssignIndices(this._gltf.skins),n._AssignIndices(this._gltf.textures),t.bin){var r=this._gltf.buffers;if(r&&r[0]&&!r[0].uri){var o=r[0];o.byteLength!=t.bin.byteLength&&e.Tools.Warn("Binary buffer length ("+o.byteLength+") from JSON does not match chunk length ("+t.bin.byteLength+")"),o.loadedData=t.bin}else e.Tools.Warn("Unexpected BIN chunk")}},n.prototype._getMeshes=function(){var e=new Array;e.push(this._rootNode.babylonMesh);var t=this._gltf.nodes;if(t)for(var r=0,n=t;r<n.length;r++){var o=n[r];o.babylonMesh&&e.push(o.babylonMesh)}return e},n.prototype._getSkeletons=function(){var e=new Array,t=this._gltf.skins;if(t)for(var r=0,n=t;r<n.length;r++){var o=n[r];o.babylonSkeleton&&e.push(o.babylonSkeleton)}return e},n.prototype._getAnimationTargets=function(){var e=new Array,t=this._gltf.animations;if(t)for(var r=0,n=t;r<n.length;r++){var o=n[r];e.push.apply(e,o.targets)}return e},n.prototype._startAnimations=function(){for(var e=0,t=this._getAnimationTargets();e<t.length;e++){var r=t[e];this._babylonScene.beginAnimation(r,0,Number.MAX_VALUE,!0)}},n.prototype._loadDefaultScene=function(e){var t=n._GetProperty(this._gltf.scenes,this._gltf.scene||0);if(!t)throw new Error("Failed to find scene "+(this._gltf.scene||0));this._loadScene("#/scenes/"+t.index,t,e)},n.prototype._loadScene=function(t,r,o){switch(this._rootNode={babylonMesh:new e.Mesh("__root__",this._babylonScene)},this._parent.coordinateSystemMode){case e.GLTFLoaderCoordinateSystemMode.AUTO:this._babylonScene.useRightHandedSystem||(this._rootNode.babylonMesh.rotation=new e.Vector3(0,Math.PI,0),this._rootNode.babylonMesh.scaling=new e.Vector3(1,1,-1));break;case e.GLTFLoaderCoordinateSystemMode.PASS_THROUGH:break;case e.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:return void e.Tools.Error("Invalid coordinate system mode "+this._parent.coordinateSystemMode)}var a=r.nodes;if(this._traverseNodes(t,a,(function(e,t){return e.parent=t,!0}),this._rootNode),o){o instanceof Array||(o=[o]);var i=new Array;this._traverseNodes(t,a,(function(e){return-1===o.indexOf(e.name)||(i.push(e.index),!1)}),this._rootNode),a=i}for(var s=0,l=a;s<l.length;s++){var u=l[s],c=n._GetProperty(this._gltf.nodes,u);if(!c)throw new Error(t+": Failed to find node "+u);this._loadNode("#/nodes/"+u,c)}this._rootNode.babylonMesh.setEnabled(!1)},n.prototype._loadNode=function(r,o){if(!t.GLTFLoaderExtension.LoadNode(this,r,o)){if(o.babylonMesh=new e.Mesh(o.name||"mesh"+o.index,this._babylonScene),o.babylonMesh.hasVertexAlpha=!0,this._loadTransform(o),null!=o.mesh){var a=n._GetProperty(this._gltf.meshes,o.mesh);if(!a)throw new Error(r+": Failed to find mesh "+o.mesh);this._loadMesh("#/meshes/"+o.mesh,o,a)}if(o.babylonMesh.parent=o.parent?o.parent.babylonMesh:null,o.babylonAnimationTargets=o.babylonAnimationTargets||[],o.babylonAnimationTargets.push(o.babylonMesh),null!=o.skin){var i=n._GetProperty(this._gltf.skins,o.skin);if(!i)throw new Error(r+": Failed to find skin "+o.skin);o.babylonMesh.skeleton=this._loadSkin("#/skins/"+o.skin,i)}if(o.camera,o.children)for(var s=0,l=o.children;s<l.length;s++){var u=l[s],c=n._GetProperty(this._gltf.nodes,u);if(!c)throw new Error(r+": Failed to find child node "+u);this._loadNode("#/nodes/"+u,c)}}},n.prototype._loadMesh=function(t,r,o){var a=this,i=o.primitives;if(!i||0===i.length)throw new Error(t+": Primitives are missing");this._createMorphTargets(t,r,o),this._loadAllVertexDataAsync(t,o,(function(){a._loadMorphTargets(t,r,o);for(var n=new e.VertexData,s=0,l=i;s<l.length;s++){var u=l[s];n.merge(u.vertexData)}new e.Geometry(r.babylonMesh.name,a._babylonScene,n,!1,r.babylonMesh),r.babylonMesh.subMeshes=[];for(var c=0,f=0,d=0;d<i.length;d++){var h=i[d].vertexData,p=h.positions.length,m=h.indices.length;e.SubMesh.AddToMesh(d,c,p,f,m,r.babylonMesh),c+=p,f+=m}}));var s=new e.MultiMaterial(r.babylonMesh.name,this._babylonScene);r.babylonMesh.material=s;for(var l=s.subMaterials,u=this,c=0;c<i.length;c++)!(function(e){var o=i[e];if(null==o.material)l[e]=u._getDefaultMaterial();else{var s=n._GetProperty(u._gltf.materials,o.material);if(!s)throw new Error(t+": Failed to find material "+o.material);u._loadMaterial("#/materials/"+s.index,s,(function(t,n){n&&a._parent.onMaterialLoaded&&a._parent.onMaterialLoaded(t),a._parent.onBeforeMaterialReadyAsync?(a._addLoaderPendingData(s),a._parent.onBeforeMaterialReadyAsync(t,r.babylonMesh,null!=l[e],(function(){a._tryCatchOnError((function(){l[e]=t,a._removeLoaderPendingData(s)}))}))):l[e]=t}))}})(c)},n.prototype._loadAllVertexDataAsync=function(e,t,r){for(var n=t.primitives,o=n.length,a=this,i=0;i<n.length;i++)!(function(i){var s=n[i];a._loadVertexDataAsync(e+"/primitive/"+i,t,s,(function(e){s.vertexData=e,0==--o&&r()}))})(i)},n.prototype._convertToFloat4TextureCoordArray=function(e,r,n){if(n.componentType==t.EComponentType.FLOAT)return r;var o=r,a=1;switch(n.componentType){case t.EComponentType.UNSIGNED_BYTE:a=1/255;break;case t.EComponentType.UNSIGNED_SHORT:a=1/65535;break;default:throw new Error(e+": Invalid component type ("+n.componentType+")")}for(var i=new Float32Array(2*n.count),s=0;s<i.length;++s)i[s]=o[s]*a;return i},n.prototype._convertToFloat4ColorArray=function(e,r,o){var a=n._GetNumComponents(o.type);if(4===a&&o.componentType===t.EComponentType.FLOAT)return r;var i=r,s=1;switch(o.componentType){case t.EComponentType.FLOAT:s=1;break;case t.EComponentType.UNSIGNED_BYTE:s=1/255;break;case t.EComponentType.UNSIGNED_SHORT:s=1/65535;break;default:throw new Error(e+": Invalid component type ("+o.componentType+")")}var l=new Float32Array(4*o.count);if(4===a)for(var u=0;u<l.length;++u)l[u]=i[u]*s;else for(var c=0,u=0;u<l.length;++u)l[u]=(u+1)%4==0?1:i[c++]*s;return l},n.prototype._loadVertexDataAsync=function(r,o,a,i){var s=this,l=a.attributes;if(!l)throw new Error(r+": Attributes are missing");if(a.mode&&a.mode!==t.EMeshPrimitiveMode.TRIANGLES)throw new Error(r+": Mode "+a.mode+" is not currently supported");var u=new e.VertexData,c=Object.keys(l).length,f=this;for(var d in l)!(function(t){var o=n._GetProperty(f._gltf.accessors,l[t]);if(!o)throw new Error(r+": Failed to find attribute '"+t+"' accessor "+l[t]);f._loadAccessorAsync("#/accessors/"+o.index,o,(function(l){switch(t){case"POSITION":u.positions=l;break;case"NORMAL":u.normals=l;break;case"TANGENT":u.tangents=l;break;case"TEXCOORD_0":u.uvs=s._convertToFloat4TextureCoordArray(r,l,o);break;case"TEXCOORD_1":u.uvs2=s._convertToFloat4TextureCoordArray(r,l,o);break;case"JOINTS_0":u.matricesIndices=new Float32Array(Array.prototype.slice.apply(l));break;case"WEIGHTS_0":u.matricesWeights=l;break;case"COLOR_0":u.colors=s._convertToFloat4ColorArray(r,l,o);break;default:e.Tools.Warn("Ignoring unrecognized attribute '"+t+"'")}if(0==--c)if(null==a.indices){u.indices=new Uint32Array(u.positions.length/3);for(var f=0;f<u.indices.length;f++)u.indices[f]=f;i(u)}else{var d=n._GetProperty(s._gltf.accessors,a.indices);if(!d)throw new Error(r+": Failed to find indices accessor "+a.indices);s._loadAccessorAsync("#/accessors/"+d.index,d,(function(e){u.indices=e,i(u)}))}}))})(d)},n.prototype._createMorphTargets=function(t,r,n){var o=n.primitives,a=o[0].targets;if(a){for(var i=0,s=o;i<s.length;i++){var l=s[i];if(!l.targets||l.targets.length!=a.length)throw new Error(t+": All primitives are required to list the same number of targets")}var u=new e.MorphTargetManager;r.babylonMesh.morphTargetManager=u;for(var c=0;c<a.length;c++){var f=r.weights?r.weights[c]:n.weights?n.weights[c]:0;u.addTarget(new e.MorphTarget("morphTarget"+c,f))}}},n.prototype._loadMorphTargets=function(t,r,n){var o=r.babylonMesh.morphTargetManager;o&&this._loadAllMorphTargetVertexDataAsync(t,r,n,(function(){for(var r=o.numTargets,a=0;a<r;a++){for(var i=new e.VertexData,s=0,l=n.primitives;s<l.length;s++){var u=l[s];i.merge(u.targetsVertexData[a],{tangentLength:3})}if(!i.positions)throw new Error(t+": Positions are missing");var c=o.getTarget(a);c.setPositions(i.positions),c.setNormals(i.normals),c.setTangents(i.tangents)}}))},n.prototype._loadAllMorphTargetVertexDataAsync=function(e,t,r,n){for(var o=r.primitives.length*t.babylonMesh.morphTargetManager.numTargets,a=this,i=0,s=r.primitives;i<s.length;i++){var l=s[i];!(function(t){var r=t.targets;t.targetsVertexData=new Array(r.length);for(var i=0;i<r.length;i++)!(function(i){a._loadMorphTargetVertexDataAsync(e+"/targets/"+i,t.vertexData,r[i],(function(e){t.targetsVertexData[i]=e,0==--o&&n()}))})(i)})(l)}},n.prototype._loadMorphTargetVertexDataAsync=function(t,r,o,a){var i=new e.VertexData,s=Object.keys(o).length,l=this;for(var u in o)!(function(u){var c=n._GetProperty(l._gltf.accessors,o[u]);if(!c)throw new Error(t+": Failed to find attribute '"+u+"' accessor "+o[u]);l._loadAccessorAsync("#/accessors/"+c.index,c,(function(t){var n=t;switch(u){case"POSITION":for(var o=0;o<n.length;o++)n[o]+=r.positions[o];i.positions=n;break;case"NORMAL":for(var o=0;o<n.length;o++)n[o]+=r.normals[o];i.normals=n;break;case"TANGENT":for(var o=0,l=0;o<n.length;o++,l++)n[o]+=r.tangents[l],(o+1)%3==0&&l++;i.tangents=n;break;default:e.Tools.Warn("Ignoring unrecognized attribute '"+u+"'")}0==--s&&a(i)}))})(u)},n.prototype._loadTransform=function(t){var r=e.Vector3.Zero(),n=e.Quaternion.Identity(),o=e.Vector3.One();if(t.matrix){e.Matrix.FromArray(t.matrix).decompose(o,n,r)}else t.translation&&(r=e.Vector3.FromArray(t.translation)),t.rotation&&(n=e.Quaternion.FromArray(t.rotation)),t.scale&&(o=e.Vector3.FromArray(t.scale));t.babylonMesh.position=r,t.babylonMesh.rotationQuaternion=n,t.babylonMesh.scaling=o},n.prototype._loadSkin=function(t,r){var o=this,a="skeleton"+r.index;if(r.babylonSkeleton=new e.Skeleton(r.name||a,a,this._babylonScene),null==r.inverseBindMatrices)this._loadBones(t,r,null);else{var i=n._GetProperty(this._gltf.accessors,r.inverseBindMatrices);if(!i)throw new Error(t+": Failed to find inverse bind matrices attribute "+r.inverseBindMatrices);this._loadAccessorAsync("#/accessors/"+i.index,i,(function(e){o._loadBones(t,r,e)}))}return r.babylonSkeleton},n.prototype._createBone=function(t,r,n,o,a,i){var s=new e.Bone(t.name||"bone"+t.index,r.babylonSkeleton,n,o,null,a,i);return t.babylonBones=t.babylonBones||{},t.babylonBones[r.index]=s,t.babylonAnimationTargets=t.babylonAnimationTargets||[],t.babylonAnimationTargets.push(s),s},n.prototype._loadBones=function(e,t,r){for(var o={},a=0,i=t.joints;a<i.length;a++){var s=i[a],l=n._GetProperty(this._gltf.nodes,s);if(!l)throw new Error(e+": Failed to find joint "+s);this._loadBone(l,t,r,o)}},n.prototype._loadBone=function(t,r,n,o){var a=o[t.index];if(a)return a;var i=r.joints.indexOf(t.index),s=e.Matrix.Identity();n&&-1!==i&&(s=e.Matrix.FromArray(n,16*i),s.invertToRef(s));var l=null;return t.index!==r.skeleton&&t.parent&&t.parent!==this._rootNode&&(l=this._loadBone(t.parent,r,n,o),s.multiplyToRef(l.getInvertedAbsoluteTransform(),s)),a=this._createBone(t,r,l,this._getNodeMatrix(t),s,i),o[t.index]=a,a},n.prototype._getNodeMatrix=function(t){return t.matrix?e.Matrix.FromArray(t.matrix):e.Matrix.Compose(t.scale?e.Vector3.FromArray(t.scale):e.Vector3.One(),t.rotation?e.Quaternion.FromArray(t.rotation):e.Quaternion.Identity(),t.translation?e.Vector3.FromArray(t.translation):e.Vector3.Zero())},n.prototype._traverseNodes=function(e,t,r,o){void 0===o&&(o=null);for(var a=0,i=t;a<i.length;a++){var s=i[a],l=n._GetProperty(this._gltf.nodes,s);if(!l)throw new Error(e+": Failed to find node "+s);this._traverseNode(e,l,r,o)}},n.prototype._traverseNode=function(e,r,n,o){void 0===o&&(o=null),t.GLTFLoaderExtension.TraverseNode(this,e,r,n,o)||n(r,o)&&r.children&&this._traverseNodes(e,r.children,n,r)},n.prototype._loadAnimations=function(){var e=this._gltf.animations;if(e)for(var t=0;t<e.length;t++){var r=e[t];this._loadAnimation("#/animations/"+t,r)}},n.prototype._loadAnimation=function(e,t){t.targets=[];for(var r=0;r<t.channels.length;r++){var o=n._GetProperty(t.channels,r);if(!o)throw new Error(e+": Failed to find channel "+r);var a=n._GetProperty(t.samplers,o.sampler);if(!a)throw new Error(e+": Failed to find sampler "+o.sampler)
  101766. ;this._loadAnimationChannel(t,e+"/channels/"+r,o,e+"/samplers/"+o.sampler,a)}},n.prototype._loadAnimationChannel=function(t,r,o,a,i){var s=n._GetProperty(this._gltf.nodes,o.target.node);if(!s)throw new Error(r+": Failed to find target node "+o.target.node);var l,u;switch(o.target.path){case"translation":l="position",u=e.Animation.ANIMATIONTYPE_VECTOR3;break;case"rotation":l="rotationQuaternion",u=e.Animation.ANIMATIONTYPE_QUATERNION;break;case"scale":l="scaling",u=e.Animation.ANIMATIONTYPE_VECTOR3;break;case"weights":l="influence",u=e.Animation.ANIMATIONTYPE_FLOAT;break;default:throw new Error(r+": Invalid target path "+o.target.path)}var c,f,d=function(){if(c&&f){var r,n=0;switch(l){case"position":r=function(){var t=e.Vector3.FromArray(f,n);return n+=3,t};break;case"rotationQuaternion":r=function(){var t=e.Quaternion.FromArray(f,n);return n+=4,t};break;case"scaling":r=function(){var t=e.Vector3.FromArray(f,n);return n+=3,t};break;case"influence":r=function(){for(var e=s.babylonMesh.morphTargetManager.numTargets,t=new Array(e),r=0;r<e;r++)t[r]=f[n++];return t}}var o;switch(i.interpolation){case"LINEAR":o=function(e){return{frame:c[e],value:r()}};break;case"CUBICSPLINE":o=function(e){return{frame:c[e],inTangent:r(),value:r(),outTangent:r()}};break;default:throw new Error(a+": Invalid interpolation "+i.interpolation)}for(var d=new Array(c.length),h=0;h<c.length;h++)d[h]=o(h);if("influence"===l)for(var p=s.babylonMesh.morphTargetManager,m=0;m<p.numTargets;m++)!(function(r){var n=p.getTarget(r),o=(t.name||"anim"+t.index)+"_"+r,a=new e.Animation(o,l,1,u);a.setKeys(d.map((function(e){return{frame:e.frame,inTangent:e.inTangent?e.inTangent[r]:void 0,value:e.value[r],outTangent:e.outTangent?e.outTangent[r]:void 0}}))),n.animations.push(a),t.targets.push(n)})(m);else{var T=t.name||"anim"+t.index,E=new e.Animation(T,l,1,u);if(E.setKeys(d),s.babylonAnimationTargets)for(var _=0,A=s.babylonAnimationTargets;_<A.length;_++){var y=A[_];y.animations.push(E.clone()),t.targets.push(y)}}}},h=n._GetProperty(this._gltf.accessors,i.input);if(!h)throw new Error(a+": Failed to find input accessor "+i.input);this._loadAccessorAsync("#/accessors/"+h.index,h,(function(e){c=e,d()}));var p=n._GetProperty(this._gltf.accessors,i.output);if(!p)throw new Error(a+": Failed to find output accessor "+i.output);this._loadAccessorAsync("#/accessors/"+p.index,p,(function(e){f=e,d()}))},n.prototype._loadBufferAsync=function(r,n,o){var a=this;if(this._addPendingData(n),n.loadedData)o(n.loadedData),this._removePendingData(n);else if(n.loadedObservable)n.loadedObservable.add((function(e){o(e.loadedData),a._removePendingData(e)}));else{if(!n.uri)throw new Error(r+": Uri is missing");if(t.GLTFUtils.IsBase64(n.uri)){var i=t.GLTFUtils.DecodeBase64(n.uri);n.loadedData=new Uint8Array(i),o(n.loadedData),this._removePendingData(n)}else n.loadedObservable=new e.Observable,n.loadedObservable.add((function(e){o(e.loadedData),a._removePendingData(e)})),this._loadUri(r,n.uri,(function(e){n.loadedData=e,n.loadedObservable.notifyObservers(n),n.loadedObservable=void 0}))}},n.prototype._loadBufferViewAsync=function(e,t,r){var o=n._GetProperty(this._gltf.buffers,t.buffer);if(!o)throw new Error(e+": Failed to find buffer "+t.buffer);this._loadBufferAsync("#/buffers/"+o.index,o,(function(n){var o;try{o=new Uint8Array(n.buffer,n.byteOffset+(t.byteOffset||0),t.byteLength)}catch(t){throw new Error(e+": "+t.message)}r(o)}))},n.prototype._loadAccessorAsync=function(e,r,o){var a=this;if(r.sparse)throw new Error(e+": Sparse accessors are not currently supported");var i=n._GetProperty(this._gltf.bufferViews,r.bufferView);if(!i)throw new Error(e+": Failed to find buffer view "+r.bufferView);this._loadBufferViewAsync("#/bufferViews/"+i.index,i,(function(s){var l=n._GetNumComponents(r.type);if(0===l)throw new Error(e+": Invalid type "+r.type);var u,c=r.byteOffset||0,f=i.byteStride;try{switch(r.componentType){case t.EComponentType.BYTE:u=a._buildArrayBuffer(Float32Array,s,c,r.count,l,f);break;case t.EComponentType.UNSIGNED_BYTE:u=a._buildArrayBuffer(Uint8Array,s,c,r.count,l,f);break;case t.EComponentType.SHORT:u=a._buildArrayBuffer(Int16Array,s,c,r.count,l,f);break;case t.EComponentType.UNSIGNED_SHORT:u=a._buildArrayBuffer(Uint16Array,s,c,r.count,l,f);break;case t.EComponentType.UNSIGNED_INT:u=a._buildArrayBuffer(Uint32Array,s,c,r.count,l,f);break;case t.EComponentType.FLOAT:u=a._buildArrayBuffer(Float32Array,s,c,r.count,l,f);break;default:throw new Error(e+": Invalid component type "+r.componentType)}}catch(t){throw new Error(e+": "+t)}o(u)}))},n.prototype._buildArrayBuffer=function(e,t,r,n,o,a){r+=t.byteOffset;var i=n*o;if(null==a||a===o*e.BYTES_PER_ELEMENT)return new e(t.buffer,r,i);for(var s=a/e.BYTES_PER_ELEMENT,l=new e(t.buffer,r,s*n),u=new e(i),c=0,f=0;f<i;){for(var d=0;d<o;d++)u[f]=l[c+d],f++;c+=s}return u},n.prototype._addPendingData=function(e){this._renderReady||this._renderPendingCount++,this._addLoaderPendingData(e)},n.prototype._removePendingData=function(e){this._renderReady||0==--this._renderPendingCount&&(this._renderReady=!0,this._onRenderReady()),this._removeLoaderPendingData(e)},n.prototype._addLoaderPendingData=function(e){this._loaderPendingCount++;for(var t=0,r=this._loaderTrackers;t<r.length;t++){r[t]._addPendingData(e)}},n.prototype._removeLoaderPendingData=function(e){for(var t=0,r=this._loaderTrackers;t<r.length;t++){r[t]._removePendingData(e)}0==--this._loaderPendingCount&&this._onComplete()},n.prototype._whenAction=function(e,t){var n=this,o=new r(function(){n._loaderTrackers.splice(n._loaderTrackers.indexOf(o),1),t()});this._loaderTrackers.push(o),this._addLoaderPendingData(o),e(),this._removeLoaderPendingData(o)},n.prototype._getDefaultMaterial=function(){if(!this._defaultMaterial){var t="__gltf_default",r=this._babylonScene.getMaterialByName(t);r||(r=new e.PBRMaterial(t,this._babylonScene),r.sideOrientation=e.Material.CounterClockWiseSideOrientation,r.metallic=1,r.roughness=1),this._defaultMaterial=r}return this._defaultMaterial},n.prototype._loadMaterialMetallicRoughnessProperties=function(t,r){var o=r.babylonMaterial;o.metallic=1,o.roughness=1;var a=r.pbrMetallicRoughness;if(a){if(o.albedoColor=a.baseColorFactor?e.Color3.FromArray(a.baseColorFactor):new e.Color3(1,1,1),o.metallic=null==a.metallicFactor?1:a.metallicFactor,o.roughness=null==a.roughnessFactor?1:a.roughnessFactor,a.baseColorTexture){var i=n._GetProperty(this._gltf.textures,a.baseColorTexture.index);if(!i)throw new Error(t+": Failed to find base color texture "+a.baseColorTexture.index);o.albedoTexture=this._loadTexture("#/textures/"+i.index,i,a.baseColorTexture.texCoord)}if(a.metallicRoughnessTexture){var i=n._GetProperty(this._gltf.textures,a.metallicRoughnessTexture.index);if(!i)throw new Error(t+": Failed to find metallic roughness texture "+a.metallicRoughnessTexture.index);o.metallicTexture=this._loadTexture("#/textures/"+i.index,i,a.metallicRoughnessTexture.texCoord),o.useMetallnessFromMetallicTextureBlue=!0,o.useRoughnessFromMetallicTextureGreen=!0,o.useRoughnessFromMetallicTextureAlpha=!1}this._loadMaterialAlphaProperties(t,r,a.baseColorFactor)}},n.prototype._loadMaterial=function(e,r,n){if(r.babylonMaterial)return void n(r.babylonMaterial,!1);t.GLTFLoaderExtension.LoadMaterial(this,e,r,n)||(this._createPbrMaterial(r),this._loadMaterialBaseProperties(e,r),this._loadMaterialMetallicRoughnessProperties(e,r),n(r.babylonMaterial,!0))},n.prototype._createPbrMaterial=function(t){var r=new e.PBRMaterial(t.name||"mat"+t.index,this._babylonScene);r.sideOrientation=e.Material.CounterClockWiseSideOrientation,t.babylonMaterial=r},n.prototype._loadMaterialBaseProperties=function(t,r){var o=r.babylonMaterial;if(o.emissiveColor=r.emissiveFactor?e.Color3.FromArray(r.emissiveFactor):new e.Color3(0,0,0),r.doubleSided&&(o.backFaceCulling=!1,o.twoSidedLighting=!0),r.normalTexture){var a=n._GetProperty(this._gltf.textures,r.normalTexture.index);if(!a)throw new Error(t+": Failed to find normal texture "+r.normalTexture.index);o.bumpTexture=this._loadTexture("#/textures/"+a.index,a,r.normalTexture.texCoord),o.invertNormalMapX=!this._babylonScene.useRightHandedSystem,o.invertNormalMapY=this._babylonScene.useRightHandedSystem,null!=r.normalTexture.scale&&(o.bumpTexture.level=r.normalTexture.scale)}if(r.occlusionTexture){var a=n._GetProperty(this._gltf.textures,r.occlusionTexture.index);if(!a)throw new Error(t+": Failed to find occlusion texture "+r.occlusionTexture.index);o.ambientTexture=this._loadTexture("#/textures/"+a.index,a,r.occlusionTexture.texCoord),o.useAmbientInGrayScale=!0,null!=r.occlusionTexture.strength&&(o.ambientTextureStrength=r.occlusionTexture.strength)}if(r.emissiveTexture){var a=n._GetProperty(this._gltf.textures,r.emissiveTexture.index);if(!a)throw new Error(t+": Failed to find emissive texture "+r.emissiveTexture.index);o.emissiveTexture=this._loadTexture("#/textures/"+a.index,a,r.emissiveTexture.texCoord)}},n.prototype._loadMaterialAlphaProperties=function(t,r,n){var o=r.babylonMaterial;switch(r.alphaMode||"OPAQUE"){case"OPAQUE":o.transparencyMode=e.PBRMaterial.PBRMATERIAL_OPAQUE;break;case"MASK":o.transparencyMode=e.PBRMaterial.PBRMATERIAL_ALPHATEST,o.alphaCutOff=null==r.alphaCutoff?.5:r.alphaCutoff,n&&(0==n[3]?o.alphaCutOff=1:o.alphaCutOff/=n[3]),o.albedoTexture&&(o.albedoTexture.hasAlpha=!0);break;case"BLEND":o.transparencyMode=e.PBRMaterial.PBRMATERIAL_ALPHABLEND,n&&(o.alpha=n[3]),o.albedoTexture&&(o.albedoTexture.hasAlpha=!0,o.useAlphaFromAlbedoTexture=!0);break;default:throw new Error(t+": Invalid alpha mode "+r.alphaMode)}},n.prototype._loadTexture=function(r,o,a){var i=this,s=null==o.sampler?{}:n._GetProperty(this._gltf.samplers,o.sampler);if(!s)throw new Error(r+": Failed to find sampler "+o.sampler);var l=s.minFilter===t.ETextureMinFilter.NEAREST||s.minFilter===t.ETextureMinFilter.LINEAR,u=n._GetTextureSamplingMode(s.magFilter,s.minFilter);this._addPendingData(o);var c=new e.Texture(null,this._babylonScene,l,!1,u,function(){i._tryCatchOnError((function(){i._removePendingData(o)}))},function(e){i._tryCatchOnError((function(){throw new Error(r+": "+e)}))});if(o.url)c.updateURL(o.url);else if(o.dataReadyObservable)o.dataReadyObservable.add((function(e){c.updateURL(e.url)}));else{o.dataReadyObservable=new e.Observable,o.dataReadyObservable.add((function(e){c.updateURL(e.url)}));var f=n._GetProperty(this._gltf.images,o.source);if(!f)throw new Error(r+": Failed to find source "+o.source);this._loadImage("#/images/"+f.index,f,(function(e){o.url=URL.createObjectURL(new Blob([e],{type:f.mimeType})),o.dataReadyObservable.notifyObservers(o),o.dataReadyObservable=void 0}))}return c.coordinatesIndex=a||0,c.wrapU=n._GetTextureWrapMode(s.wrapS),c.wrapV=n._GetTextureWrapMode(s.wrapT),c.name=o.name||"texture"+o.index,this._parent.onTextureLoaded&&this._parent.onTextureLoaded(c),c},n.prototype._loadImage=function(e,r,o){if(r.uri)t.GLTFUtils.IsBase64(r.uri)?o(new Uint8Array(t.GLTFUtils.DecodeBase64(r.uri))):this._loadUri(e,r.uri,o);else{var a=n._GetProperty(this._gltf.bufferViews,r.bufferView);if(!a)throw new Error(e+": Failed to find buffer view "+r.bufferView);this._loadBufferViewAsync("#/bufferViews/"+a.index,a,o)}},n.prototype._loadUri=function(r,n,o){var a=this;if(!t.GLTFUtils.ValidateUri(n))throw new Error(r+": Uri '"+n+"' is invalid");var i=e.Tools.LoadFile(this._rootUrl+n,(function(e){a._tryCatchOnError((function(){o(new Uint8Array(e))}))}),(function(e){a._tryCatchOnError((function(){a._onProgress(e)}))}),this._babylonScene.database,!0,(function(e){a._tryCatchOnError((function(){throw new Error(r+": Failed to load '"+n+"'"+(e?": "+e.status+" "+e.statusText:""))}))}));i&&this._requests.push(i)},n.prototype._tryCatchOnError=function(t){if(!this._disposed)try{t()}catch(t){e.Tools.Error("glTF Loader: "+t.message),this._errorCallback&&this._errorCallback(t.message),this.dispose()}},n._AssignIndices=function(e){if(e)for(var t=0;t<e.length;t++)e[t].index=t},n._GetProperty=function(e,t){return e&&void 0!=t&&e[t]?e[t]:null},n._GetTextureWrapMode=function(r){switch(r=void 0==r?t.ETextureWrapMode.REPEAT:r){case t.ETextureWrapMode.CLAMP_TO_EDGE:return e.Texture.CLAMP_ADDRESSMODE;case t.ETextureWrapMode.MIRRORED_REPEAT:return e.Texture.MIRROR_ADDRESSMODE;case t.ETextureWrapMode.REPEAT:return e.Texture.WRAP_ADDRESSMODE;default:return e.Tools.Warn("Invalid texture wrap mode ("+r+")"),e.Texture.WRAP_ADDRESSMODE}},n._GetTextureSamplingMode=function(r,n){if(r=void 0==r?t.ETextureMagFilter.LINEAR:r,n=void 0==n?t.ETextureMinFilter.LINEAR_MIPMAP_LINEAR:n,r===t.ETextureMagFilter.LINEAR)switch(n){case t.ETextureMinFilter.NEAREST:return e.Texture.LINEAR_NEAREST;case t.ETextureMinFilter.LINEAR:return e.Texture.LINEAR_LINEAR;case t.ETextureMinFilter.NEAREST_MIPMAP_NEAREST:return e.Texture.LINEAR_NEAREST_MIPNEAREST;case t.ETextureMinFilter.LINEAR_MIPMAP_NEAREST:return e.Texture.LINEAR_LINEAR_MIPNEAREST;case t.ETextureMinFilter.NEAREST_MIPMAP_LINEAR:return e.Texture.LINEAR_NEAREST_MIPLINEAR;case t.ETextureMinFilter.LINEAR_MIPMAP_LINEAR:return e.Texture.LINEAR_LINEAR_MIPLINEAR;default:return e.Tools.Warn("Invalid texture minification filter ("+n+")"),e.Texture.LINEAR_LINEAR_MIPLINEAR}else switch(r!==t.ETextureMagFilter.NEAREST&&e.Tools.Warn("Invalid texture magnification filter ("+r+")"),n){case t.ETextureMinFilter.NEAREST:return e.Texture.NEAREST_NEAREST;case t.ETextureMinFilter.LINEAR:return e.Texture.NEAREST_LINEAR;case t.ETextureMinFilter.NEAREST_MIPMAP_NEAREST:return e.Texture.NEAREST_NEAREST_MIPNEAREST;case t.ETextureMinFilter.LINEAR_MIPMAP_NEAREST:return e.Texture.NEAREST_LINEAR_MIPNEAREST;case t.ETextureMinFilter.NEAREST_MIPMAP_LINEAR:return e.Texture.NEAREST_NEAREST_MIPLINEAR;case t.ETextureMinFilter.LINEAR_MIPMAP_LINEAR:return e.Texture.NEAREST_LINEAR_MIPLINEAR;default:return e.Tools.Warn("Invalid texture minification filter ("+n+")"),e.Texture.NEAREST_NEAREST_MIPNEAREST}},n._GetNumComponents=function(e){switch(e){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}return 0},n.Extensions={},n})();t.GLTFLoader=n,e.GLTFFileLoader.CreateGLTFLoaderV2=function(e){return new n(e)}})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){var t=(function(){function e(){}return e.IsBase64=function(e){return!(e.length<5)&&"data:"===e.substr(0,5)},e.DecodeBase64=function(e){for(var t=atob(e.split(",")[1]),r=t.length,n=new Uint8Array(new ArrayBuffer(r)),o=0;o<r;o++)n[o]=t.charCodeAt(o);return n.buffer},e.ValidateUri=function(e){return-1===e.indexOf("..")},e})();e.GLTFUtils=t})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(e){var t=(function(){function e(){this.enabled=!0}return e.prototype._traverseNode=function(e,t,r,n,o){return!1},e.prototype._loadNode=function(e,t,r){return!1},e.prototype._loadMaterial=function(e,t,r,n){return!1},e.prototype._loadExtension=function(e,t,r){var n=this;if(!t.extensions)return!1;var o=t.extensions[this.name];return!!o&&(t.extensions[this.name]=void 0,r(e+"extensions/"+this.name,o,(function(){t.extensions[n.name]=o})),!0)},e.TraverseNode=function(e,t,r,n,o){return this._ApplyExtensions((function(a){return a._traverseNode(e,t,r,n,o)}))},e.LoadNode=function(e,t,r){return this._ApplyExtensions((function(n){return n._loadNode(e,t,r)}))},e.LoadMaterial=function(e,t,r,n){return this._ApplyExtensions((function(o){return o._loadMaterial(e,t,r,n)}))},e._ApplyExtensions=function(t){var r=e._Extensions;if(!r)return!1;for(var n=0,o=r;n<o.length;n++){var a=o[n];if(a.enabled&&t(a))return!0}return!1},e._Extensions=[],e})();e.GLTFLoaderExtension=t})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){!(function(r){var n=(function(r){function n(){return null!==r&&r.apply(this,arguments)||this}return __extends(n,r),Object.defineProperty(n.prototype,"name",{get:function(){return"MSFT_lod"},enumerable:!0,configurable:!0}),n.prototype._traverseNode=function(e,r,n,o,a){return this._loadExtension(r,n,(function(r,i,s){for(var l=i.ids.length-1;l>=0;l--){var u=t.GLTFLoader._GetProperty(e._gltf.nodes,i.ids[l]);if(!u)throw new Error(r+": Failed to find node "+i.ids[l]);e._traverseNode(r,u,o,a)}e._traverseNode(r,n,o,a),s()}))},n.prototype._loadNode=function(e,r,n){var o=this;return this._loadExtension(r,n,(function(r,a,i){for(var s=[n],l=0,u=a.ids;l<u.length;l++){var c=u[l],f=t.GLTFLoader._GetProperty(e._gltf.nodes,c);if(!f)throw new Error(r+": Failed to find node "+c);s.push(f)}e._addLoaderPendingData(n),o._loadNodeLOD(e,r,s,s.length-1,(function(){e._removeLoaderPendingData(n),i()}))}))},n.prototype._loadNodeLOD=function(e,t,r,o,a){var i=this;e._whenAction((function(){e._loadNode(t,r[o])}),(function(){if(o!==r.length-1){r[o+1].babylonMesh.setEnabled(!1)}if(0===o)return void a();setTimeout((function(){e._tryCatchOnError((function(){i._loadNodeLOD(e,t,r,o-1,a)}))}),n.MinimalLODDelay)}))},n.prototype._loadMaterial=function(e,r,n,o){var a=this;return this._loadExtension(r,n,(function(r,i,s){for(var l=[n],u=0,c=i.ids;u<c.length;u++){var f=c[u],d=t.GLTFLoader._GetProperty(e._gltf.materials,f);if(!d)throw new Error(r+": Failed to find material "+f);l.push(d)}e._addLoaderPendingData(n),a._loadMaterialLOD(e,r,l,l.length-1,o,(function(){e._removeLoaderPendingData(n),s()}))}))},n.prototype._loadMaterialLOD=function(t,r,o,a,i,s){var l=this;t._loadMaterial(r,o[a],(function(u,c){if(i(u,c),0===a)return void s();t._executeWhenRenderReady((function(){e.BaseTexture.WhenAllReady(u.getActiveTextures(),(function(){setTimeout((function(){t._tryCatchOnError((function(){l._loadMaterialLOD(t,r,o,a-1,i,s)}))}),n.MinimalLODDelay)}))}))}))},n.MinimalLODDelay=250,n})(t.GLTFLoaderExtension);r.MSFTLOD=n,t.GLTFLoader.RegisterExtension(new n)})(t.Extensions||(t.Extensions={}))})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){!(function(r){var n=(function(r){function n(){return null!==r&&r.apply(this,arguments)||this}return __extends(n,r),Object.defineProperty(n.prototype,"name",{get:function(){return"KHR_materials_pbrSpecularGlossiness"},enumerable:!0,configurable:!0}),n.prototype._loadMaterial=function(e,t,r,n){var o=this;return this._loadExtension(t,r,(function(t,a,i){e._createPbrMaterial(r),e._loadMaterialBaseProperties(t,r),o._loadSpecularGlossinessProperties(e,t,r,a),n(r.babylonMaterial,!0)}))},n.prototype._loadSpecularGlossinessProperties=function(r,n,o,a){var i=o.babylonMaterial;if(i.albedoColor=a.diffuseFactor?e.Color3.FromArray(a.diffuseFactor):new e.Color3(1,1,1),i.reflectivityColor=a.specularFactor?e.Color3.FromArray(a.specularFactor):new e.Color3(1,1,1),i.microSurface=null==a.glossinessFactor?1:a.glossinessFactor,a.diffuseTexture){var s=t.GLTFLoader._GetProperty(r._gltf.textures,a.diffuseTexture.index);if(!s)throw new Error(n+": Failed to find diffuse texture "+a.diffuseTexture.index);i.albedoTexture=r._loadTexture("textures["+s.index+"]",s,a.diffuseTexture.texCoord)}if(a.specularGlossinessTexture){var s=t.GLTFLoader._GetProperty(r._gltf.textures,a.specularGlossinessTexture.index);if(!s)throw new Error(n+": Failed to find diffuse texture "+a.specularGlossinessTexture.index);i.reflectivityTexture=r._loadTexture("textures["+s.index+"]",s,a.specularGlossinessTexture.texCoord),i.reflectivityTexture.hasAlpha=!0,i.useMicroSurfaceFromReflectivityMapAlpha=!0}r._loadMaterialAlphaProperties(n,o,a.diffuseFactor)},n})(t.GLTFLoaderExtension);r.KHRMaterialsPbrSpecularGlossiness=n,t.GLTFLoader.RegisterExtension(new n)})(t.Extensions||(t.Extensions={}))})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={})),(function(e,t){var r=t();e&&e.BABYLON||( true?module.exports=r:"function"==typeof define&&define.amd?define(["BJSLoaders"],t):"object"==typeof exports?exports.BJSLoaders=r:e.BABYLON=r)})(this,(function(){return BABYLON}));
  101767. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
  101768. /***/ }),
  101769. /* 30 */
  101770. /***/ (function(module, exports, __webpack_require__) {
  101771. /* WEBPACK VAR INJECTION */(function(global) {var globalObject="undefined"!=typeof global?global:"undefined"!=typeof window?window:this,babylonDependency=globalObject&&globalObject.BABYLON||BABYLON||"undefined"!="function"&&__webpack_require__(0),BABYLON=babylonDependency,__decorate=this&&this.__decorate||function(e,i,t,n){var r,o=arguments.length,a=o<3?i:null===n?n=Object.getOwnPropertyDescriptor(i,t):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,i,t,n);else for(var s=e.length-1;s>=0;s--)(r=e[s])&&(a=(o<3?r(a):o>3?r(i,t,a):r(i,t))||a);return o>3&&a&&Object.defineProperty(i,t,a),a},__extends=this&&this.__extends||(function(){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var t in i)i.hasOwnProperty(t)&&(e[t]=i[t])};return function(i,t){function n(){this.constructor=i}e(i,t),i.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}})(),BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.CLIPPLANE=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(e,i){return t.call(this,e,i)||this}return __extends(n,t),n.prototype.needAlphaBlending=function(){return!0},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},Object.defineProperty(n.prototype,"activeLight",{get:function(){return this._activeLight},set:function(e){this._activeLight=e},enumerable:!0,configurable:!0}),n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(this._activeLight)for(var f=0,l=t._lightSources;f<l.length;f++){var u=l[f];if(u.shadowEnabled){if(this._activeLight===u)break;var c=t._lightSources.indexOf(this._activeLight);-1!==c&&(t._lightSources.splice(c,1),t._lightSources.splice(0,0,this._activeLight));break}}if(e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,1),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!1,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var d=new e.EffectFallbacks;o.FOG&&d.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,d,1),o.NUM_BONE_INFLUENCERS>0&&d.addCPUSkinningFallback(0,t);var p=[e.VertexBuffer.PositionKind];o.NORMAL&&p.push(e.VertexBuffer.NormalKind),e.MaterialHelper.PrepareAttributesForBones(p,t,o,d),e.MaterialHelper.PrepareAttributesForInstances(p,o);var h=o.toString(),m=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","alpha","mBones","vClipPlane"],v=new Array,_=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:m,uniformBuffersNames:_,samplers:v,defines:o,maxSimultaneousLights:1}),n.setEffect(a.getEngine().createEffect("shadowOnly",{attributes:p,uniformsNames:m,uniformBuffersNames:_,samplers:v,defines:h,fallbacks:d,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:1}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._activeEffect.setFloat("alpha",this.alpha),e.MaterialHelper.BindEyePosition(a,r)),r.lightsEnabled&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,1),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.ShadowOnlyMaterial",i},n.prototype.getClassName=function(){return"ShadowOnlyMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},n})(e.PushMaterial);e.ShadowOnlyMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.shadowOnlyVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\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\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.shadowOnlyPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform float alpha;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0..1]\n\nvec4 color=vec4(0.,0.,0.,(1.0-clamp(shadow,0.,1.))*alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.LIGHT0=!1,i.LIGHT1=!1,i.LIGHT2=!1,i.LIGHT3=!1,i.SPOTLIGHT0=!1,i.SPOTLIGHT1=!1,i.SPOTLIGHT2=!1,i.SPOTLIGHT3=!1,i.HEMILIGHT0=!1,i.HEMILIGHT1=!1,i.HEMILIGHT2=!1,i.HEMILIGHT3=!1,i.DIRLIGHT0=!1,i.DIRLIGHT1=!1,i.DIRLIGHT2=!1,i.DIRLIGHT3=!1,i.POINTLIGHT0=!1,i.POINTLIGHT1=!1,i.POINTLIGHT2=!1,i.POINTLIGHT3=!1,i.SHADOW0=!1,i.SHADOW1=!1,i.SHADOW2=!1,i.SHADOW3=!1,i.SHADOWS=!1,i.SHADOWESM0=!1,i.SHADOWESM1=!1,i.SHADOWESM2=!1,i.SHADOWESM3=!1,i.SHADOWPCF0=!1,i.SHADOWPCF1=!1,i.SHADOWPCF2=!1,i.SHADOWPCF3=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r._maxSimultaneousLights=4,r.topColor=new e.Color3(1,0,0),r.topColorAlpha=1,r.bottomColor=new e.Color3(0,0,1),r.bottomColorAlpha=1,r.offset=0,r.smoothness=1,r.disableLighting=!1,r._scaledDiffuse=new e.Color3,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1||this.topColorAlpha<1||this.bottomColorAlpha<1},n.prototype.needAlphaTesting=function(){return!0},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!1,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix","topColor","bottomColor","offset","smoothness"],d=["diffuseSampler"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:4}),n.setEffect(a.getEngine().createEffect("gradient",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,a),this._mustRebind(r,a)&&(e.MaterialHelper.BindClipPlane(a,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._activeEffect.setColor4("topColor",this.topColor,this.topColorAlpha),this._activeEffect.setColor4("bottomColor",this.bottomColor,this.bottomColorAlpha),this._activeEffect.setFloat("offset",this.offset),this._activeEffect.setFloat("smoothness",this.smoothness),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){return[]},n.prototype.dispose=function(e){t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.GradientMaterial",i},n.prototype.getClassName=function(){return"GradientMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),__decorate([e.serializeAsColor3()],n.prototype,"topColor",void 0),__decorate([e.serialize()],n.prototype,"topColorAlpha",void 0),__decorate([e.serializeAsColor3()],n.prototype,"bottomColor",void 0),__decorate([e.serialize()],n.prototype,"bottomColorAlpha",void 0),__decorate([e.serialize()],n.prototype,"offset",void 0),__decorate([e.serialize()],n.prototype,"smoothness",void 0),__decorate([e.serialize()],n.prototype,"disableLighting",void 0),n})(e.PushMaterial);e.GradientMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.gradientVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\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\nvNormalW=normalize(vec3(finalWorld*vec4(normal,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 DIFFUSE\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#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.gradientPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nuniform vec4 topColor;\nuniform vec4 bottomColor;\nuniform float offset;\nuniform float smoothness;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\nfloat h=normalize(vPositionW).y+offset;\nfloat mysmoothness=clamp(smoothness,0.01,max(smoothness,10.));\nvec4 baseColor=mix(bottomColor,topColor,max(pow(max(h,0.0),mysmoothness),0.0));\n\nvec3 diffuseColor=baseColor.rgb;\n\nfloat alpha=baseColor.a;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}\n";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.LIGHT0=!1,i.LIGHT1=!1,i.LIGHT2=!1,i.LIGHT3=!1,i.SPOTLIGHT0=!1,i.SPOTLIGHT1=!1,i.SPOTLIGHT2=!1,i.SPOTLIGHT3=!1,i.HEMILIGHT0=!1,i.HEMILIGHT1=!1,i.HEMILIGHT2=!1,i.HEMILIGHT3=!1,i.DIRLIGHT0=!1,i.DIRLIGHT1=!1,i.DIRLIGHT2=!1,i.DIRLIGHT3=!1,i.POINTLIGHT0=!1,i.POINTLIGHT1=!1,i.POINTLIGHT2=!1,i.POINTLIGHT3=!1,i.SHADOW0=!1,i.SHADOW1=!1,i.SHADOW2=!1,i.SHADOW3=!1,i.SHADOWS=!1,i.SHADOWESM0=!1,i.SHADOWESM1=!1,i.SHADOWESM2=!1,i.SHADOWESM3=!1,i.SHADOWPCF0=!1,i.SHADOWPCF1=!1,i.SHADOWPCF2=!1,i.SHADOWPCF3=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled&&this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix"],d=["diffuseSampler"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:4}),n.setEffect(a.getEngine().createEffect("normal",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:4}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this.diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this.diffuseTexture===e},n.prototype.dispose=function(e){this.diffuseTexture&&this.diffuseTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.NormalMaterial",i},n.prototype.getClassName=function(){return"NormalMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.NormalMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.normalVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\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\nvNormalW=normalize(vec3(finalWorld*vec4(normal,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 DIFFUSE\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#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.normalPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef NORMAL\nbaseColor=mix(baseColor,vec4(vNormalW,1.0),0.5);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.LIGHT0=!1,i.LIGHT1=!1,i.LIGHT2=!1,i.LIGHT3=!1,i.SPOTLIGHT0=!1,i.SPOTLIGHT1=!1,i.SPOTLIGHT2=!1,i.SPOTLIGHT3=!1,i.HEMILIGHT0=!1,i.HEMILIGHT1=!1,i.HEMILIGHT2=!1,i.HEMILIGHT3=!1,i.DIRLIGHT0=!1,i.DIRLIGHT1=!1,i.DIRLIGHT2=!1,i.DIRLIGHT3=!1,i.POINTLIGHT0=!1,i.POINTLIGHT1=!1,i.POINTLIGHT2=!1,i.POINTLIGHT3=!1,i.SHADOW0=!1,i.SHADOW1=!1,i.SHADOW2=!1,i.SHADOW3=!1,i.SHADOWS=!1,i.SHADOWESM0=!1,i.SHADOWESM1=!1,i.SHADOWESM2=!1,i.SHADOWESM3=!1,i.SHADOWPCF0=!1,i.SHADOWPCF1=!1,i.SHADOWPCF2=!1,i.SHADOWPCF3=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.speed=1,r.movingSpeed=1,r.lowFrequencySpeed=1,r.fogDensity=.15,r._lastTime=0,r.diffuseColor=new e.Color3(1,1,1),r._disableLighting=!1,r._maxSimultaneousLights=4,r._scaledDiffuse=new e.Color3,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled&&this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix","time","speed","movingSpeed","fogColor","fogDensity","lowFrequencySpeed"],d=["diffuseSampler","noiseTexture"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("lava",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this.diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this.diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this.diffuseTexture.coordinatesIndex,this.diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this.diffuseTexture.getTextureMatrix())),this.noiseTexture&&this._activeEffect.setTexture("noiseTexture",this.noiseTexture),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._lastTime+=r.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime*this.speed/1e3),this.fogColor||(this.fogColor=e.Color3.Black()),this._activeEffect.setColor3("fogColor",this.fogColor),this._activeEffect.setFloat("fogDensity",this.fogDensity),this._activeEffect.setFloat("lowFrequencySpeed",this.lowFrequencySpeed),this._activeEffect.setFloat("movingSpeed",this.movingSpeed),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.noiseTexture&&this.noiseTexture.animations&&this.noiseTexture.animations.length>0&&e.push(this.noiseTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this.diffuseTexture===e},n.prototype.dispose=function(e){this.diffuseTexture&&this.diffuseTexture.dispose(),this.noiseTexture&&this.noiseTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.LavaMaterial",i},n.prototype.getClassName=function(){return"LavaMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture()],n.prototype,"noiseTexture",void 0),__decorate([e.serializeAsColor3()],n.prototype,"fogColor",void 0),__decorate([e.serialize()],n.prototype,"speed",void 0),__decorate([e.serialize()],n.prototype,"movingSpeed",void 0),__decorate([e.serialize()],n.prototype,"lowFrequencySpeed",void 0),__decorate([e.serialize()],n.prototype,"fogDensity",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),
  101772. __decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.LavaMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.lavaVertexShader="precision highp float;\n\nuniform float time;\nuniform float lowFrequencySpeed;\n\nvarying float noise;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n\n\nvec3 mod289(vec3 x)\n{\nreturn x-floor(x*(1.0/289.0))*289.0;\n}\nvec4 mod289(vec4 x)\n{\nreturn x-floor(x*(1.0/289.0))*289.0;\n}\nvec4 permute(vec4 x)\n{\nreturn mod289(((x*34.0)+1.0)*x);\n}\nvec4 taylorInvSqrt(vec4 r)\n{\nreturn 1.79284291400159-0.85373472095314*r;\n}\nvec3 fade(vec3 t) {\nreturn t*t*t*(t*(t*6.0-15.0)+10.0);\n}\n\nfloat pnoise(vec3 P,vec3 rep)\n{\nvec3 Pi0=mod(floor(P),rep); \nvec3 Pi1=mod(Pi0+vec3(1.0),rep); \nPi0=mod289(Pi0);\nPi1=mod289(Pi1);\nvec3 Pf0=fract(P); \nvec3 Pf1=Pf0-vec3(1.0); \nvec4 ix=vec4(Pi0.x,Pi1.x,Pi0.x,Pi1.x);\nvec4 iy=vec4(Pi0.yy,Pi1.yy);\nvec4 iz0=Pi0.zzzz;\nvec4 iz1=Pi1.zzzz;\nvec4 ixy=permute(permute(ix)+iy);\nvec4 ixy0=permute(ixy+iz0);\nvec4 ixy1=permute(ixy+iz1);\nvec4 gx0=ixy0*(1.0/7.0);\nvec4 gy0=fract(floor(gx0)*(1.0/7.0))-0.5;\ngx0=fract(gx0);\nvec4 gz0=vec4(0.5)-abs(gx0)-abs(gy0);\nvec4 sz0=step(gz0,vec4(0.0));\ngx0-=sz0*(step(0.0,gx0)-0.5);\ngy0-=sz0*(step(0.0,gy0)-0.5);\nvec4 gx1=ixy1*(1.0/7.0);\nvec4 gy1=fract(floor(gx1)*(1.0/7.0))-0.5;\ngx1=fract(gx1);\nvec4 gz1=vec4(0.5)-abs(gx1)-abs(gy1);\nvec4 sz1=step(gz1,vec4(0.0));\ngx1-=sz1*(step(0.0,gx1)-0.5);\ngy1-=sz1*(step(0.0,gy1)-0.5);\nvec3 g000=vec3(gx0.x,gy0.x,gz0.x);\nvec3 g100=vec3(gx0.y,gy0.y,gz0.y);\nvec3 g010=vec3(gx0.z,gy0.z,gz0.z);\nvec3 g110=vec3(gx0.w,gy0.w,gz0.w);\nvec3 g001=vec3(gx1.x,gy1.x,gz1.x);\nvec3 g101=vec3(gx1.y,gy1.y,gz1.y);\nvec3 g011=vec3(gx1.z,gy1.z,gz1.z);\nvec3 g111=vec3(gx1.w,gy1.w,gz1.w);\nvec4 norm0=taylorInvSqrt(vec4(dot(g000,g000),dot(g010,g010),dot(g100,g100),dot(g110,g110)));\ng000*=norm0.x;\ng010*=norm0.y;\ng100*=norm0.z;\ng110*=norm0.w;\nvec4 norm1=taylorInvSqrt(vec4(dot(g001,g001),dot(g011,g011),dot(g101,g101),dot(g111,g111)));\ng001*=norm1.x;\ng011*=norm1.y;\ng101*=norm1.z;\ng111*=norm1.w;\nfloat n000=dot(g000,Pf0);\nfloat n100=dot(g100,vec3(Pf1.x,Pf0.yz));\nfloat n010=dot(g010,vec3(Pf0.x,Pf1.y,Pf0.z));\nfloat n110=dot(g110,vec3(Pf1.xy,Pf0.z));\nfloat n001=dot(g001,vec3(Pf0.xy,Pf1.z));\nfloat n101=dot(g101,vec3(Pf1.x,Pf0.y,Pf1.z));\nfloat n011=dot(g011,vec3(Pf0.x,Pf1.yz));\nfloat n111=dot(g111,Pf1);\nvec3 fade_xyz=fade(Pf0);\nvec4 n_z=mix(vec4(n000,n100,n010,n110),vec4(n001,n101,n011,n111),fade_xyz.z);\nvec2 n_yz=mix(n_z.xy,n_z.zw,fade_xyz.y);\nfloat n_xyz=mix(n_yz.x,n_yz.y,fade_xyz.x);\nreturn 2.2*n_xyz;\n}\n\nfloat turbulence( vec3 p ) {\nfloat w=100.0;\nfloat t=-.5;\nfor (float f=1.0 ; f<=10.0 ; f++ ){\nfloat power=pow( 2.0,f );\nt+=abs( pnoise( vec3( power*p ),vec3( 10.0,10.0,10.0 ) )/power );\n}\nreturn t;\n}\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef NORMAL\n\nnoise=10.0*-.10*turbulence( .5*normal+time*1.15 );\n\nfloat b=lowFrequencySpeed*5.0*pnoise( 0.05*position +vec3(time*1.025),vec3( 100.0 ) );\n\nfloat displacement =-1.5*noise+b;\n\nvec3 newPosition=position+normal*displacement;\ngl_Position=viewProjection*finalWorld*vec4( newPosition,1.0 );\nvec4 worldPos=finalWorld*vec4(newPosition,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,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 DIFFUSE\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#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}",BABYLON.Effect.ShadersStore.lavaPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n\nuniform float time;\nuniform float speed;\nuniform float movingSpeed;\nuniform vec3 fogColor;\nuniform sampler2D noiseTexture;\nuniform float fogDensity;\n\nvarying float noise;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0]\n#include<__decl__lightFragment>[1]\n#include<__decl__lightFragment>[2]\n#include<__decl__lightFragment>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nfloat random( vec3 scale,float seed ){\nreturn fract( sin( dot( gl_FragCoord.xyz+seed,scale ) )*43758.5453+seed ) ;\n}\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\n\nvec4 noiseTex=texture2D( noiseTexture,vDiffuseUV );\nvec2 T1=vDiffuseUV+vec2( 1.5,-1.5 )*time*0.02;\nvec2 T2=vDiffuseUV+vec2( -0.5,2.0 )*time*0.01*speed;\nT1.x+=noiseTex.x*2.0;\nT1.y+=noiseTex.y*2.0;\nT2.x-=noiseTex.y*0.2+time*0.001*movingSpeed;\nT2.y+=noiseTex.z*0.2+time*0.002*movingSpeed;\nfloat p=texture2D( noiseTexture,T1*3.0 ).a;\nvec4 lavaColor=texture2D( diffuseSampler,T2*4.0);\nvec4 temp=lavaColor*( vec4( p,p,p,p )*2. )+( lavaColor*lavaColor-0.1 );\nbaseColor=temp;\nfloat depth=gl_FragCoord.z*4.0;\nconst float LOG2=1.442695;\nfloat fogFactor=exp2(-fogDensity*fogDensity*depth*depth*LOG2 );\nfogFactor=1.0-clamp( fogFactor,0.0,1.0 );\nbaseColor=mix( baseColor,vec4( fogColor,baseColor.w ),fogFactor );\ndiffuseColor=baseColor.rgb;\n\n\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled&&this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix"],d=["diffuseSampler"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("simple",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights-1}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this.diffuseTexture===e},n.prototype.dispose=function(e){this._diffuseTexture&&this._diffuseTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.SimpleMaterial",i},n.prototype.getClassName=function(){return"SimpleMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsColor3("diffuse")],n.prototype,"diffuseColor",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.SimpleMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.simpleVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\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\nvNormalW=normalize(vec3(finalWorld*vec4(normal,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 DIFFUSE\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#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.simplePixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.BUMP=!1,i.REFLECTION=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.SPECULARTERM=!1,i.LOGARITHMICDEPTH=!1,i.FRESNELSEPARATE=!1,i.BUMPSUPERIMPOSE=!1,i.BUMPAFFECTSREFLECTION=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n,r){void 0===r&&(r=new e.Vector2(512,512));var o=t.call(this,i,n)||this;return o.renderTargetSize=r,o.diffuseColor=new e.Color3(1,1,1),o.specularColor=new e.Color3(0,0,0),o.specularPower=64,o._disableLighting=!1,o._maxSimultaneousLights=4,o.windForce=6,o.windDirection=new e.Vector2(0,1),o.waveHeight=.4,o.bumpHeight=.4,o._bumpSuperimpose=!1,o._fresnelSeparate=!1,o._bumpAffectsReflection=!1,o.waterColor=new e.Color3(.1,.1,.6),o.colorBlendFactor=.2,o.waterColor2=new e.Color3(.1,.1,.6),o.colorBlendFactor2=.2,o.waveLength=.1,o.waveSpeed=1,o._renderTargets=new e.SmartArray(16),o._mesh=null,o._reflectionTransform=e.Matrix.Zero(),o._lastTime=0,o._lastDeltaTime=0,o._createRenderTargets(n,r),o.getRenderTargetTextures=function(){return o._renderTargets.reset(),o._renderTargets.push(o._reflectionRTT),o._renderTargets.push(o._refractionRTT),o._renderTargets},o}return __extends(n,t),Object.defineProperty(n.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"refractionTexture",{get:function(){return this._refractionRTT},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"reflectionTexture",{get:function(){return this._reflectionRTT},enumerable:!0,configurable:!0}),n.prototype.addToRenderList=function(e){this._refractionRTT.renderList&&this._refractionRTT.renderList.push(e),this._reflectionRTT.renderList&&this._reflectionRTT.renderList.push(e)},n.prototype.enableRenderTargets=function(e){var i=e?1:0;this._refractionRTT.refreshRate=i,this._reflectionRTT.refreshRate=i},n.prototype.getRenderList=function(){return this._refractionRTT.renderList},Object.defineProperty(n.prototype,"renderTargetsEnabled",{get:function(){return!(0===this._refractionRTT.refreshRate)},enumerable:!0,configurable:!0}),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled)){if(this.bumpTexture&&e.StandardMaterial.BumpTextureEnabled){if(!this.bumpTexture.isReady())return!1;o._needUVs=!0,o.BUMP=!0}e.StandardMaterial.ReflectionTextureEnabled&&(o.REFLECTION=!0)}if(e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForMisc(t,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,o),o._areMiscDirty&&(this._fresnelSeparate&&(o.FRESNELSEPARATE=!0),this._bumpSuperimpose&&(o.BUMPSUPERIMPOSE=!0),this._bumpAffectsReflection&&(o.BUMPAFFECTSREFLECTION=!0)),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!0,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),this._mesh=t,o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),o.LOGARITHMICDEPTH&&f.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vNormalInfos","mBones","vClipPlane","normalMatrix","logarithmicDepthConstant","worldReflectionViewProjection","windDirection","waveLength","time","windForce","cameraPosition","bumpHeight","waveHeight","waterColor","waterColor2","colorBlendFactor","colorBlendFactor2","waveSpeed"],d=["normalSampler","refractionSampler","reflectionSampler"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("water",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;if(a&&this._mesh){this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this.bumpTexture&&e.StandardMaterial.BumpTextureEnabled&&(this._activeEffect.setTexture("normalSampler",this.bumpTexture),this._activeEffect.setFloat2("vNormalInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level),this._activeEffect.setMatrix("normalMatrix",this.bumpTexture.getTextureMatrix())),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),o.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),e.MaterialHelper.BindLogDepth(o,this._activeEffect,r),e.StandardMaterial.ReflectionTextureEnabled&&(this._activeEffect.setTexture("refractionSampler",this._refractionRTT),this._activeEffect.setTexture("reflectionSampler",this._reflectionRTT));var s=this._mesh.getWorldMatrix().multiply(this._reflectionTransform).multiply(r.getProjectionMatrix()),f=r.getEngine().getDeltaTime();f!==this._lastDeltaTime&&(this._lastDeltaTime=f,this._lastTime+=this._lastDeltaTime),this._activeEffect.setMatrix("worldReflectionViewProjection",s),this._activeEffect.setVector2("windDirection",this.windDirection),this._activeEffect.setFloat("waveLength",this.waveLength),this._activeEffect.setFloat("time",this._lastTime/1e5),this._activeEffect.setFloat("windForce",this.windForce),this._activeEffect.setFloat("waveHeight",this.waveHeight),this._activeEffect.setFloat("bumpHeight",this.bumpHeight),this._activeEffect.setColor4("waterColor",this.waterColor,1),this._activeEffect.setFloat("colorBlendFactor",this.colorBlendFactor),this._activeEffect.setColor4("waterColor2",this.waterColor2,1),this._activeEffect.setFloat("colorBlendFactor2",this.colorBlendFactor2),this._activeEffect.setFloat("waveSpeed",this.waveSpeed),this._afterBind(t,this._activeEffect)}}},n.prototype._createRenderTargets=function(i,t){var n=this;this._refractionRTT=new e.RenderTargetTexture(name+"_refraction",{width:t.x,height:t.y},i,!1,!0),this._refractionRTT.wrapU=e.Texture.MIRROR_ADDRESSMODE,this._refractionRTT.wrapV=e.Texture.MIRROR_ADDRESSMODE,this._refractionRTT.ignoreCameraViewport=!0,this._reflectionRTT=new e.RenderTargetTexture(name+"_reflection",{width:t.x,height:t.y},i,!1,!0),this._reflectionRTT.wrapU=e.Texture.MIRROR_ADDRESSMODE,this._reflectionRTT.wrapV=e.Texture.MIRROR_ADDRESSMODE,this._reflectionRTT.ignoreCameraViewport=!0;var r,o,a=null,s=e.Matrix.Zero();this._refractionRTT.onBeforeRender=function(){n._mesh&&(r=n._mesh.isVisible,n._mesh.isVisible=!1),a=i.clipPlane;var t=n._mesh?n._mesh.position.y:0;i.clipPlane=e.Plane.FromPositionAndNormal(new e.Vector3(0,t+.05,0),new e.Vector3(0,1,0))},this._refractionRTT.onAfterRender=function(){n._mesh&&(n._mesh.isVisible=r),i.clipPlane=a},this._reflectionRTT.onBeforeRender=function(){n._mesh&&(r=n._mesh.isVisible,n._mesh.isVisible=!1),a=i.clipPlane;var t=n._mesh?n._mesh.position.y:0;i.clipPlane=e.Plane.FromPositionAndNormal(new e.Vector3(0,t-.05,0),new e.Vector3(0,-1,0)),e.Matrix.ReflectionToRef(i.clipPlane,s),o=i.getViewMatrix(),s.multiplyToRef(o,n._reflectionTransform),i.setTransformMatrix(n._reflectionTransform,i.getProjectionMatrix()),i.getEngine().cullBackFaces=!1,i._mirroredCameraPosition=e.Vector3.TransformCoordinates(i.activeCamera.position,s)},this._reflectionRTT.onAfterRender=function(){n._mesh&&(n._mesh.isVisible=r),i.clipPlane=a,i.setTransformMatrix(o,i.getProjectionMatrix()),i.getEngine().cullBackFaces=!0,i._mirroredCameraPosition=null}},n.prototype.getAnimatables=function(){var e=[];return this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this._reflectionRTT&&this._reflectionRTT.animations&&this._reflectionRTT.animations.length>0&&e.push(this._reflectionRTT),this._refractionRTT&&this._refractionRTT.animations&&this._refractionRTT.animations.length>0&&e.push(this._refractionRTT),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._bumpTexture&&e.push(this._bumpTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this._bumpTexture===e},n.prototype.dispose=function(e){this.bumpTexture&&this.bumpTexture.dispose();var i=this.getScene().customRenderTargets.indexOf(this._refractionRTT);-1!=i&&this.getScene().customRenderTargets.splice(i,1),i=-1,i=this.getScene().customRenderTargets.indexOf(this._reflectionRTT),-1!=i&&this.getScene().customRenderTargets.splice(i,1),this._reflectionRTT&&this._reflectionRTT.dispose(),this._refractionRTT&&this._refractionRTT.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.WaterMaterial",i.reflectionTexture.isRenderTarget=!0,i.refractionTexture.isRenderTarget=!0,i},n.prototype.getClassName=function(){return"WaterMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},n.CreateDefaultMesh=function(i,t){return e.Mesh.CreateGround(i,512,512,32,t,!1)},__decorate([e.serializeAsTexture("bumpTexture")],n.prototype,"_bumpTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"specularColor",void 0),__decorate([e.serialize()],n.prototype,"specularPower",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize()],n.prototype,"windForce",void 0),__decorate([e.serializeAsVector2()],n.prototype,"windDirection",void 0),__decorate([e.serialize()],n.prototype,"waveHeight",void 0),__decorate([e.serialize()],n.prototype,"bumpHeight",void 0),__decorate([e.serialize("bumpSuperimpose")],n.prototype,"_bumpSuperimpose",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsMiscDirty")],n.prototype,"bumpSuperimpose",void 0),__decorate([e.serialize("fresnelSeparate")],n.prototype,"_fresnelSeparate",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsMiscDirty")],n.prototype,"fresnelSeparate",void 0),__decorate([e.serialize("bumpAffectsReflection")],n.prototype,"_bumpAffectsReflection",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsMiscDirty")],n.prototype,"bumpAffectsReflection",void 0),__decorate([e.serializeAsColor3()],n.prototype,"waterColor",void 0),__decorate([e.serialize()],n.prototype,"colorBlendFactor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"waterColor2",void 0),__decorate([e.serialize()],n.prototype,"colorBlendFactor2",void 0),__decorate([e.serialize()],n.prototype,"waveLength",void 0),__decorate([e.serialize()],n.prototype,"waveSpeed",void 0),__decorate([e.serialize()],n.prototype,"useLogarithmicDepth",null),n})(e.PushMaterial);e.WaterMaterial=t})(BABYLON||(BABYLON={})),
  101773. BABYLON.Effect.ShadersStore.waterVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef BUMP\nvarying vec2 vNormalUV;\n#ifdef BUMPSUPERIMPOSE\nvarying vec2 vNormalUV2;\n#endif\nuniform mat4 normalMatrix;\nuniform vec2 vNormalInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<logDepthDeclaration>\n\nuniform mat4 worldReflectionViewProjection;\nuniform vec2 windDirection;\nuniform float waveLength;\nuniform float time;\nuniform float windForce;\nuniform float waveHeight;\nuniform float waveSpeed;\n\nvarying vec3 vPosition;\nvarying vec3 vRefractionMapTexCoord;\nvarying vec3 vReflectionMapTexCoord;\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,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 BUMP\nif (vNormalInfos.x == 0.)\n{\nvNormalUV=vec2(normalMatrix*vec4((uv*1.0)/waveLength+time*windForce*windDirection,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv*0.721)/waveLength+time*1.2*windForce*windDirection,1.0,0.0));\n#endif\n}\nelse\n{\nvNormalUV=vec2(normalMatrix*vec4((uv2*1.0)/waveLength+time*windForce*windDirection ,1.0,0.0));\n#ifdef BUMPSUPERIMPOSE\nvNormalUV2=vec2(normalMatrix*vec4((uv2*0.721)/waveLength+time*1.2*windForce*windDirection ,1.0,0.0));\n#endif\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\nvec3 p=position;\nfloat newY=(sin(((p.x/0.05)+time*waveSpeed))*waveHeight*windDirection.x*5.0)\n+(cos(((p.z/0.05)+time*waveSpeed))*waveHeight*windDirection.y*5.0);\np.y+=abs(newY);\ngl_Position=viewProjection*finalWorld*vec4(p,1.0);\n#ifdef REFLECTION\nworldPos=viewProjection*finalWorld*vec4(p,1.0);\n\nvPosition=position;\nvRefractionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);\nvRefractionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);\nvRefractionMapTexCoord.z=worldPos.w;\nworldPos=worldReflectionViewProjection*vec4(position,1.0);\nvReflectionMapTexCoord.x=0.5*(worldPos.w+worldPos.x);\nvReflectionMapTexCoord.y=0.5*(worldPos.w+worldPos.y);\nvReflectionMapTexCoord.z=worldPos.w;\n#endif\n#include<logDepthVertex>\n}\n",BABYLON.Effect.ShadersStore.waterPixelShader="#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef BUMP\nvarying vec2 vNormalUV;\nvarying vec2 vNormalUV2;\nuniform sampler2D normalSampler;\nuniform vec2 vNormalInfos;\n#endif\nuniform sampler2D refractionSampler;\nuniform sampler2D reflectionSampler;\n\nconst float LOG2=1.442695;\nuniform vec3 cameraPosition;\nuniform vec4 waterColor;\nuniform float colorBlendFactor;\nuniform vec4 waterColor2;\nuniform float colorBlendFactor2;\nuniform float bumpHeight;\nuniform float time;\n\nvarying vec3 vRefractionMapTexCoord;\nvarying vec3 vReflectionMapTexCoord;\nvarying vec3 vPosition;\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n\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#ifdef BUMP\n#ifdef BUMPSUPERIMPOSE\nbaseColor=0.6*texture2D(normalSampler,vNormalUV)+0.4*texture2D(normalSampler,vec2(vNormalUV2.x,vNormalUV2.y));\n#else\nbaseColor=texture2D(normalSampler,vNormalUV);\n#endif\nvec3 bumpColor=baseColor.rgb;\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vNormalInfos.y;\n#else\nvec3 bumpColor=vec3(1.0);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec2 perturbation=bumpHeight*(baseColor.rg-0.5);\n#ifdef BUMPAFFECTSREFLECTION\nvec3 normalW=normalize(vNormalW+vec3(perturbation.x*8.0,0.0,perturbation.y*8.0));\nif (normalW.y<0.0) {\nnormalW.y=-normalW.y;\n}\n#else\nvec3 normalW=normalize(vNormalW);\n#endif\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\nvec2 perturbation=bumpHeight*(vec2(1.0,1.0)-0.5);\n#endif\n#ifdef FRESNELSEPARATE\n#ifdef REFLECTION\n\nvec3 eyeVector=normalize(vEyePosition-vPosition);\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation*0.5,0.0,1.0);\nvec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\nvec2 projectedReflectionTexCoords=clamp(vec2(\nvReflectionMapTexCoord.x/vReflectionMapTexCoord.z+perturbation.x*0.3,\nvReflectionMapTexCoord.y/vReflectionMapTexCoord.z+perturbation.y\n),0.0,1.0);\nvec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\nvec3 upVector=vec3(0.0,1.0,0.0);\nfloat fresnelTerm=clamp(abs(pow(dot(eyeVector,upVector),3.0)),0.05,0.65);\nfloat IfresnelTerm=1.0-fresnelTerm;\nrefractiveColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*refractiveColor;\nreflectiveColor=IfresnelTerm*colorBlendFactor2*waterColor+(1.0-colorBlendFactor2*IfresnelTerm)*reflectiveColor;\nvec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*IfresnelTerm;\nbaseColor=combinedColor;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#else \n#ifdef REFLECTION\n\nvec3 eyeVector=normalize(vEyePosition-vPosition);\nvec2 projectedRefractionTexCoords=clamp(vRefractionMapTexCoord.xy/vRefractionMapTexCoord.z+perturbation,0.0,1.0);\nvec4 refractiveColor=texture2D(refractionSampler,projectedRefractionTexCoords);\nvec2 projectedReflectionTexCoords=clamp(vReflectionMapTexCoord.xy/vReflectionMapTexCoord.z+perturbation,0.0,1.0);\nvec4 reflectiveColor=texture2D(reflectionSampler,projectedReflectionTexCoords);\nvec3 upVector=vec3(0.0,1.0,0.0);\nfloat fresnelTerm=max(dot(eyeVector,upVector),0.0);\nvec4 combinedColor=refractiveColor*fresnelTerm+reflectiveColor*(1.0-fresnelTerm);\nbaseColor=colorBlendFactor*waterColor+(1.0-colorBlendFactor)*combinedColor;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 finalDiffuse=clamp(baseColor.rgb,0.0,1.0);\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#endif\n\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}\n";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.UV1=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.BonesPerMesh=0,i.NUM_BONE_INFLUENCERS=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r.speed=1,r._scaledDiffuse=new e.Color3,r._lastTime=0,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return!1},n.prototype.needAlphaTesting=function(){return!0},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(o._areMiscDirty&&(o.POINTSIZE=this.pointsCloud||a.forcePointsCloud,o.FOG=a.fogEnabled&&t.applyFog&&a.fogMode!==e.Scene.FOGMODE_NONE&&this.fogEnabled),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!1,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.UV1&&l.push(e.VertexBuffer.UVKind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString();n.setEffect(a.getEngine().createEffect("fire",{attributes:l,uniformsNames:["world","view","viewProjection","vEyePosition","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix","time","speed"],uniformBuffersNames:[],samplers:["diffuseSampler","distortionSampler","opacitySampler"],defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:null,maxSimultaneousLights:4,transformFeedbackVaryings:null},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene();if(n._materialDefines){var o=n.effect;if(o){if(this._activeEffect=o,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,o)){if(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix()),this._activeEffect.setTexture("distortionSampler",this._distortionTexture),this._activeEffect.setTexture("opacitySampler",this._opacityTexture)),r.clipPlane){var a=r.clipPlane;this._activeEffect.setFloat4("vClipPlane",a.normal.x,a.normal.y,a.normal.z,a.d)}this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(o,r)}this._activeEffect.setColor4("vDiffuseColor",this._scaledDiffuse,this.alpha*t.visibility),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._lastTime+=r.getEngine().getDeltaTime(),this._activeEffect.setFloat("time",this._lastTime),this._activeEffect.setFloat("speed",this.speed),this._afterBind(t,this._activeEffect)}}},n.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._distortionTexture&&this._distortionTexture.animations&&this._distortionTexture.animations.length>0&&e.push(this._distortionTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),this._distortionTexture&&e.push(this._distortionTexture),this._opacityTexture&&e.push(this._opacityTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this._diffuseTexture===e||(this._distortionTexture===e||this._opacityTexture===e))},n.prototype.getClassName=function(){return"FireMaterial"},n.prototype.dispose=function(e){this._diffuseTexture&&this._diffuseTexture.dispose(),this._distortionTexture&&this._distortionTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var e=t.prototype.serialize.call(this);return e.customType="BABYLON.FireMaterial",e.diffuseColor=this.diffuseColor.asArray(),e.speed=this.speed,this._diffuseTexture&&(e._diffuseTexture=this._diffuseTexture.serialize()),this._distortionTexture&&(e._distortionTexture=this._distortionTexture.serialize()),this._opacityTexture&&(e._opacityTexture=this._opacityTexture.serialize()),e},n.Parse=function(i,t,r){var o=new n(i.name,t);return o.diffuseColor=e.Color3.FromArray(i.diffuseColor),o.speed=i.speed,o.alpha=i.alpha,o.id=i.id,e.Tags.AddTagsTo(o,i.tags),o.backFaceCulling=i.backFaceCulling,o.wireframe=i.wireframe,i._diffuseTexture&&(o._diffuseTexture=e.Texture.Parse(i._diffuseTexture,t,r)),i._distortionTexture&&(o._distortionTexture=e.Texture.Parse(i._distortionTexture,t,r)),i._opacityTexture&&(o._opacityTexture=e.Texture.Parse(i._opacityTexture,t,r)),i.checkReadyOnlyOnce&&(o.checkReadyOnlyOnce=i.checkReadyOnlyOnce),o},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture("distortionTexture")],n.prototype,"_distortionTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"distortionTexture",void 0),__decorate([e.serializeAsTexture("opacityTexture")],n.prototype,"_opacityTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"opacityTexture",void 0),__decorate([e.serializeAsColor3("diffuse")],n.prototype,"diffuseColor",void 0),__decorate([e.serialize()],n.prototype,"speed",void 0),n})(e.PushMaterial);e.FireMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.fireVertexShader="precision highp float;\n\nattribute vec3 position;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n\nuniform float time;\nuniform float speed;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;\nvarying vec2 vDistortionCoords2;\nvarying vec2 vDistortionCoords3;\n#endif\nvoid main(void) {\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\n#ifdef DIFFUSE\nvDiffuseUV=uv;\nvDiffuseUV.y-=0.2;\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n#ifdef DIFFUSE\n\nvec3 layerSpeed=vec3(-0.2,-0.52,-0.1)*speed;\nvDistortionCoords1.x=uv.x;\nvDistortionCoords1.y=uv.y+layerSpeed.x*time/1000.0;\nvDistortionCoords2.x=uv.x;\nvDistortionCoords2.y=uv.y+layerSpeed.y*time/1000.0;\nvDistortionCoords3.x=uv.x;\nvDistortionCoords3.y=uv.y+layerSpeed.z*time/1000.0;\n#endif\n}\n",BABYLON.Effect.ShadersStore.firePixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\nuniform sampler2D distortionSampler;\nuniform sampler2D opacitySampler;\n#ifdef DIFFUSE\nvarying vec2 vDistortionCoords1;\nvarying vec2 vDistortionCoords2;\nvarying vec2 vDistortionCoords3;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\nvec4 bx2(vec4 x)\n{\nreturn vec4(2.0)*x-vec4(1.0);\n}\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\n\nfloat alpha=1.0;\n#ifdef DIFFUSE\n\nconst float distortionAmount0=0.092;\nconst float distortionAmount1=0.092;\nconst float distortionAmount2=0.092;\nvec2 heightAttenuation=vec2(0.3,0.39);\nvec4 noise0=texture2D(distortionSampler,vDistortionCoords1);\nvec4 noise1=texture2D(distortionSampler,vDistortionCoords2);\nvec4 noise2=texture2D(distortionSampler,vDistortionCoords3);\nvec4 noiseSum=bx2(noise0)*distortionAmount0+bx2(noise1)*distortionAmount1+bx2(noise2)*distortionAmount2;\nvec4 perturbedBaseCoords=vec4(vDiffuseUV,0.0,1.0)+noiseSum*(vDiffuseUV.y*heightAttenuation.x+heightAttenuation.y);\nvec4 opacityColor=texture2D(opacitySampler,perturbedBaseCoords.xy);\n#ifdef ALPHATEST\nif (opacityColor.r<0.1)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor=texture2D(diffuseSampler,perturbedBaseCoords.xy)*2.0;\nbaseColor*=opacityColor;\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 diffuseBase=vec3(1.0,1.0,1.0);\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec4 color=vec4(baseColor.rgb,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.HEIGHTMAP=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.HIGHLEVEL=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r.furLength=1,r.furAngle=0,r.furColor=new e.Color3(.44,.21,.02),r.furOffset=0,r.furSpacing=12,r.furGravity=new e.Vector3(0,0,0),r.furSpeed=100,r.furDensity=20,r._disableLighting=!1,r._maxSimultaneousLights=4,r.highLevelFur=!0,r._furTime=0,r}return __extends(n,t),Object.defineProperty(n.prototype,"furTime",{get:function(){return this._furTime},set:function(e){this._furTime=e},enumerable:!0,configurable:!0}),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.updateFur=function(){for(var e=1;e<this._meshes.length;e++){var i=this._meshes[e].material;i.furLength=this.furLength,i.furAngle=this.furAngle,i.furGravity=this.furGravity,i.furSpacing=this.furSpacing,i.furSpeed=this.furSpeed,i.furColor=this.furColor,i.diffuseTexture=this.diffuseTexture,i.furTexture=this.furTexture,i.highLevelFur=this.highLevelFur,i.furTime=this.furTime,i.furDensity=this.furDensity}},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&a.texturesEnabled){if(this.diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled){if(!this.diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(this.heightTexture&&s.getCaps().maxVertexTextureImageUnits){if(!this.heightTexture.isReady())return!1;o._needUVs=!0,o.HEIGHTMAP=!0}}if(this.highLevelFur!==o.HIGHLEVEL&&(o.HIGHLEVEL=!0,o.markAsUnprocessed()),e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix","furLength","furAngle","furColor","furOffset","furGravity","furTime","furSpacing","furDensity"],d=["diffuseSampler","heightTexture","furTexture"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("fur",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),r.getCachedMaterial()!==this&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._heightTexture&&this._activeEffect.setTexture("heightTexture",this._heightTexture),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._activeEffect.setFloat("furLength",this.furLength),this._activeEffect.setFloat("furAngle",this.furAngle),this._activeEffect.setColor4("furColor",this.furColor,1),this.highLevelFur&&(this._activeEffect.setVector3("furGravity",this.furGravity),this._activeEffect.setFloat("furOffset",this.furOffset),this._activeEffect.setFloat("furSpacing",this.furSpacing),this._activeEffect.setFloat("furDensity",this.furDensity),this._furTime+=this.getScene().getEngine().getDeltaTime()/this.furSpeed,this._activeEffect.setFloat("furTime",this._furTime),this._activeEffect.setTexture("furTexture",this.furTexture)),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){var e=[];return this.diffuseTexture&&this.diffuseTexture.animations&&this.diffuseTexture.animations.length>0&&e.push(this.diffuseTexture),this.heightTexture&&this.heightTexture.animations&&this.heightTexture.animations.length>0&&e.push(this.heightTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),this._heightTexture&&e.push(this._heightTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this.diffuseTexture===e||this._heightTexture===e)},n.prototype.dispose=function(e){if(this.diffuseTexture&&this.diffuseTexture.dispose(),this._meshes)for(var i=1;i<this._meshes.length;i++){var n=this._meshes[i].material;n&&n.dispose(e),this._meshes[i].dispose()}t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.FurMaterial",this._meshes&&(i.sourceMeshName=this._meshes[0].name,i.quality=this._meshes.length),i},n.prototype.getClassName=function(){return"FurMaterial"},n.Parse=function(i,t,r){var o=e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r);return i.sourceMeshName&&o.highLevelFur&&t.executeWhenReady((function(){var e=t.getMeshByName(i.sourceMeshName);if(e){var r=n.GenerateTexture("Fur Texture",t);o.furTexture=r,n.FurifyMesh(e,i.quality)}})),o},n.GenerateTexture=function(i,t){for(var n=new e.DynamicTexture("FurTexture "+i,256,t,!0),r=n.getContext(),o=0;o<2e4;++o)r.fillStyle="rgba(255, "+Math.floor(255*Math.random())+", "+Math.floor(255*Math.random())+", 1)",r.fillRect(Math.random()*n.getSize().width,Math.random()*n.getSize().height,2,2);return n.update(!1),n.wrapU=e.Texture.WRAP_ADDRESSMODE,n.wrapV=e.Texture.WRAP_ADDRESSMODE,n},n.FurifyMesh=function(i,t){var r,o=[i],a=i.material;if(!(a instanceof n))throw"The material of the source mesh must be a Fur Material";for(r=1;r<t;r++){var s=new e.FurMaterial(a.name+r,i.getScene());i.getScene().materials.pop(),e.Tags.EnableFor(s),e.Tags.AddTagsTo(s,"furShellMaterial"),s.furLength=a.furLength,s.furAngle=a.furAngle,s.furGravity=a.furGravity,s.furSpacing=a.furSpacing,s.furSpeed=a.furSpeed,s.furColor=a.furColor,s.diffuseTexture=a.diffuseTexture,s.furOffset=r/t,s.furTexture=a.furTexture,s.highLevelFur=a.highLevelFur,s.furTime=a.furTime,s.furDensity=a.furDensity;var f=i.clone(i.name+r);f.material=s,f.skeleton=i.skeleton,f.position=e.Vector3.Zero(),o.push(f)}for(r=1;r<o.length;r++)o[r].parent=i;return i.material._meshes=o,o},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture("heightTexture")],n.prototype,"_heightTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"heightTexture",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serialize()],n.prototype,"furLength",void 0),__decorate([e.serialize()],n.prototype,"furAngle",void 0),__decorate([e.serializeAsColor3()],n.prototype,"furColor",void 0),__decorate([e.serialize()],n.prototype,"furOffset",void 0),__decorate([e.serialize()],n.prototype,"furSpacing",void 0),__decorate([e.serializeAsVector3()],n.prototype,"furGravity",void 0),__decorate([e.serialize()],n.prototype,"furSpeed",void 0),__decorate([e.serialize()],n.prototype,"furDensity",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize()],n.prototype,"highLevelFur",void 0),__decorate([e.serialize()],n.prototype,"furTime",null),n})(e.PushMaterial);e.FurMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.furVertexShader="precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\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<bonesDeclaration>\n\nuniform float furLength;\nuniform float furAngle;\n#ifdef HIGHLEVEL\nuniform float furOffset;\nuniform vec3 furGravity;\nuniform float furTime;\nuniform float furSpacing;\nuniform float furDensity;\n#endif\n#ifdef HEIGHTMAP\nuniform sampler2D heightTexture;\n#endif\n#ifdef HIGHLEVEL\nvarying vec2 vFurUV;\n#endif\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\nvarying float vfur_length;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nfloat Rand(vec3 rv) {\nfloat x=dot(rv,vec3(12.9898,78.233,24.65487));\nreturn fract(sin(x)*43758.5453);\n}\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\n\nfloat r=Rand(position);\n#ifdef HEIGHTMAP\n#if __VERSION__>100\nvfur_length=furLength*texture(heightTexture,uv).x;\n#else\nvfur_length=furLength*texture2D(heightTexture,uv).r;\n#endif\n#else \nvfur_length=(furLength*r);\n#endif\nvec3 tangent1=vec3(normal.y,-normal.x,0);\nvec3 tangent2=vec3(-normal.z,0,normal.x);\nr=Rand(tangent1*r);\nfloat J=(2.0+4.0*r);\nr=Rand(tangent2*r);\nfloat K=(2.0+2.0*r);\ntangent1=tangent1*J+tangent2*K;\ntangent1=normalize(tangent1);\nvec3 newPosition=position+normal*vfur_length*cos(furAngle)+tangent1*vfur_length*sin(furAngle);\n#ifdef HIGHLEVEL\n\nvec3 forceDirection=vec3(0.0,0.0,0.0);\nforceDirection.x=sin(furTime+position.x*0.05)*0.2;\nforceDirection.y=cos(furTime*0.7+position.y*0.04)*0.2;\nforceDirection.z=sin(furTime*0.7+position.z*0.04)*0.2;\nvec3 displacement=vec3(0.0,0.0,0.0);\ndisplacement=furGravity+forceDirection;\nfloat displacementFactor=pow(furOffset,3.0);\nvec3 aNormal=normal;\naNormal.xyz+=displacement*displacementFactor;\nnewPosition=vec3(newPosition.x,newPosition.y,newPosition.z)+(normalize(aNormal)*furOffset*furSpacing);\n#endif\n#ifdef NORMAL\n#ifdef HIGHLEVEL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0))*aNormal);\n#else\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#endif\n\ngl_Position=viewProjection*finalWorld*vec4(newPosition,1.0);\nvec4 worldPos=finalWorld*vec4(newPosition,1.0);\nvPositionW=vec3(worldPos);\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\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#ifdef HIGHLEVEL\nvFurUV=vDiffuseUV*furDensity;\n#endif\n#else\n#ifdef HIGHLEVEL\nvFurUV=uv*furDensity;\n#endif\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",
  101774. BABYLON.Effect.ShadersStore.furPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nuniform vec4 furColor;\nuniform float furLength;\nvarying vec3 vPositionW;\nvarying float vfur_length;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef HIGHLEVEL\nuniform float furOffset;\nuniform sampler2D furTexture;\nvarying vec2 vFurUV;\n#endif\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<fogFragmentDeclaration>\n#include<clipPlaneFragmentDeclaration>\nfloat Rand(vec3 rv) {\nfloat x=dot(rv,vec3(12.9898,78.233,24.65487));\nreturn fract(sin(x)*43758.5453);\n}\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=furColor;\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n#ifdef DIFFUSE\nbaseColor*=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef HIGHLEVEL\n\nvec4 furTextureColor=texture2D(furTexture,vec2(vFurUV.x,vFurUV.y));\nif (furTextureColor.a<=0.0 || furTextureColor.g<furOffset) {\ndiscard;\n}\nfloat occlusion=mix(0.0,furTextureColor.b*1.2,furOffset);\nbaseColor=vec4(baseColor.xyz*occlusion,1.1-furOffset);\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase.rgb*baseColor.rgb,0.0,1.0);\n\n#ifdef HIGHLEVEL\nvec4 color=vec4(finalDiffuse,alpha);\n#else\nfloat r=vfur_length/furLength*0.5;\nvec4 color=vec4(finalDiffuse*(0.5+r),alpha);\n#endif\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.BUMP=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.SPECULARTERM=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r.specularColor=new e.Color3(0,0,0),r.specularPower=64,r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(a.texturesEnabled){if(this.mixTexture&&e.StandardMaterial.DiffuseTextureEnabled){if(!this.mixTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}(this.bumpTexture1||this.bumpTexture2||this.bumpTexture3)&&e.StandardMaterial.BumpTextureEnabled&&(o._needUVs=!0,o._needNormals=!0,o.BUMP=!0)}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vTextureInfos","mBones","vClipPlane","textureMatrix","diffuse1Infos","diffuse2Infos","diffuse3Infos"],d=["textureSampler","diffuse1Sampler","diffuse2Sampler","diffuse3Sampler","bump1Sampler","bump2Sampler","bump3Sampler"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("terrain",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this.mixTexture&&(this._activeEffect.setTexture("textureSampler",this._mixTexture),this._activeEffect.setFloat2("vTextureInfos",this._mixTexture.coordinatesIndex,this._mixTexture.level),this._activeEffect.setMatrix("textureMatrix",this._mixTexture.getTextureMatrix()),e.StandardMaterial.DiffuseTextureEnabled&&(this._diffuseTexture1&&(this._activeEffect.setTexture("diffuse1Sampler",this._diffuseTexture1),this._activeEffect.setFloat2("diffuse1Infos",this._diffuseTexture1.uScale,this._diffuseTexture1.vScale)),this._diffuseTexture2&&(this._activeEffect.setTexture("diffuse2Sampler",this._diffuseTexture2),this._activeEffect.setFloat2("diffuse2Infos",this._diffuseTexture2.uScale,this._diffuseTexture2.vScale)),this._diffuseTexture3&&(this._activeEffect.setTexture("diffuse3Sampler",this._diffuseTexture3),this._activeEffect.setFloat2("diffuse3Infos",this._diffuseTexture3.uScale,this._diffuseTexture3.vScale))),e.StandardMaterial.BumpTextureEnabled&&r.getEngine().getCaps().standardDerivatives&&(this._bumpTexture1&&this._activeEffect.setTexture("bump1Sampler",this._bumpTexture1),this._bumpTexture2&&this._activeEffect.setTexture("bump2Sampler",this._bumpTexture2),this._bumpTexture3&&this._activeEffect.setTexture("bump3Sampler",this._bumpTexture3))),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),o.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){var e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._mixTexture&&e.push(this._mixTexture),this._diffuseTexture1&&e.push(this._diffuseTexture1),this._diffuseTexture2&&e.push(this._diffuseTexture2),this._diffuseTexture3&&e.push(this._diffuseTexture3),this._bumpTexture1&&e.push(this._bumpTexture1),this._bumpTexture2&&e.push(this._bumpTexture2),this._bumpTexture3&&e.push(this._bumpTexture3),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this._mixTexture===e||(this._diffuseTexture1===e||(this._diffuseTexture2===e||(this._diffuseTexture3===e||(this._bumpTexture1===e||(this._bumpTexture2===e||this._bumpTexture3===e))))))},n.prototype.dispose=function(e){this.mixTexture&&this.mixTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.TerrainMaterial",i},n.prototype.getClassName=function(){return"TerrainMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("mixTexture")],n.prototype,"_mixTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"mixTexture",void 0),__decorate([e.serializeAsTexture("diffuseTexture1")],n.prototype,"_diffuseTexture1",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture1",void 0),__decorate([e.serializeAsTexture("diffuseTexture2")],n.prototype,"_diffuseTexture2",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture2",void 0),__decorate([e.serializeAsTexture("diffuseTexture3")],n.prototype,"_diffuseTexture3",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture3",void 0),__decorate([e.serializeAsTexture("bumpTexture1")],n.prototype,"_bumpTexture1",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture1",void 0),__decorate([e.serializeAsTexture("bumpTexture2")],n.prototype,"_bumpTexture2",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture2",void 0),__decorate([e.serializeAsTexture("bumpTexture3")],n.prototype,"_bumpTexture3",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture3",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"specularColor",void 0),__decorate([e.serialize()],n.prototype,"specularPower",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.TerrainMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.terrainVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;\nuniform mat4 textureMatrix;\nuniform vec2 vTextureInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\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\nvNormalW=normalize(vec3(finalWorld*vec4(normal,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 DIFFUSE\nif (vTextureInfos.x == 0.)\n{\nvTextureUV=vec2(textureMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvTextureUV=vec2(textureMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\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",BABYLON.Effect.ShadersStore.terrainPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef DIFFUSE\nvarying vec2 vTextureUV;\nuniform sampler2D textureSampler;\nuniform vec2 vTextureInfos;\nuniform sampler2D diffuse1Sampler;\nuniform sampler2D diffuse2Sampler;\nuniform sampler2D diffuse3Sampler;\nuniform vec2 diffuse1Infos;\nuniform vec2 diffuse2Infos;\nuniform vec2 diffuse3Infos;\n#endif\n#ifdef BUMP\nuniform sampler2D bump1Sampler;\nuniform sampler2D bump2Sampler;\nuniform sampler2D bump3Sampler;\n#endif\n\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\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 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,vec3 mixColor)\n{ \nvec3 bump1Color=texture2D(bump1Sampler,vTextureUV*diffuse1Infos).xyz;\nvec3 bump2Color=texture2D(bump2Sampler,vTextureUV*diffuse2Infos).xyz;\nvec3 bump3Color=texture2D(bump3Sampler,vTextureUV*diffuse3Infos).xyz;\nbump1Color.rgb*=mixColor.r;\nbump2Color.rgb=mix(bump1Color.rgb,bump2Color.rgb,mixColor.g);\nvec3 map=mix(bump2Color.rgb,bump3Color.rgb,mixColor.b);\nmap=map*255./127.-128./127.;\nmat3 TBN=cotangent_frame(vNormalW*vTextureInfos.y,-viewDir,vTextureUV);\nreturn normalize(TBN*map);\n}\n#endif\nvoid main(void) {\n\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(textureSampler,vTextureUV);\n#if defined(BUMP) && defined(DIFFUSE)\nnormalW=perturbNormal(viewDirectionW,baseColor.rgb);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vTextureInfos.y;\nvec4 diffuse1Color=texture2D(diffuse1Sampler,vTextureUV*diffuse1Infos);\nvec4 diffuse2Color=texture2D(diffuse2Sampler,vTextureUV*diffuse2Infos);\nvec4 diffuse3Color=texture2D(diffuse3Sampler,vTextureUV*diffuse3Infos);\ndiffuse1Color.rgb*=baseColor.r;\ndiffuse2Color.rgb=mix(diffuse1Color.rgb,diffuse2Color.rgb,baseColor.g);\nbaseColor.rgb=mix(diffuse2Color.rgb,diffuse3Color.rgb,baseColor.b);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor*baseColor.rgb,0.0,1.0);\n\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}\n";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSEX=!1,i.DIFFUSEY=!1,i.DIFFUSEZ=!1,i.BUMPX=!1,i.BUMPY=!1,i.BUMPZ=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.DEPTHPREPASS=!1,i.POINTSIZE=!1,i.FOG=!1,i.SPECULARTERM=!1,i.NORMAL=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.tileSize=1,r.diffuseColor=new e.Color3(1,1,1),r.specularColor=new e.Color3(.2,.2,.2),r.specularPower=64,r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&a.texturesEnabled){if(e.StandardMaterial.DiffuseTextureEnabled)for(var f=[this.diffuseTextureX,this.diffuseTextureY,this.diffuseTextureZ],l=["DIFFUSEX","DIFFUSEY","DIFFUSEZ"],u=0;u<f.length;u++)if(f[u]){if(!f[u].isReady())return!1;o[l[u]]=!0}if(e.StandardMaterial.BumpTextureEnabled)for(var f=[this.normalTextureX,this.normalTextureY,this.normalTextureZ],l=["BUMPX","BUMPY","BUMPZ"],u=0;u<f.length;u++)if(f[u]){if(!f[u].isReady())return!1;o[l[u]]=!0}}if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var c=new e.EffectFallbacks;o.FOG&&c.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,c,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&c.addCPUSkinningFallback(0,t);var d=[e.VertexBuffer.PositionKind];o.NORMAL&&d.push(e.VertexBuffer.NormalKind),o.VERTEXCOLOR&&d.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(d,t,o,c),e.MaterialHelper.PrepareAttributesForInstances(d,o);var p=o.toString(),h=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","mBones","vClipPlane","tileSize"],m=["diffuseSamplerX","diffuseSamplerY","diffuseSamplerZ","normalSamplerX","normalSamplerY","normalSamplerZ"],v=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:h,uniformBuffersNames:v,samplers:m,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("triplanar",{attributes:d,uniformsNames:h,uniformBuffersNames:v,samplers:m,defines:p,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._activeEffect.setFloat("tileSize",this.tileSize),r.getCachedMaterial()!==this&&(this.diffuseTextureX&&this._activeEffect.setTexture("diffuseSamplerX",this.diffuseTextureX),this.diffuseTextureY&&this._activeEffect.setTexture("diffuseSamplerY",this.diffuseTextureY),this.diffuseTextureZ&&this._activeEffect.setTexture("diffuseSamplerZ",this.diffuseTextureZ),this.normalTextureX&&this._activeEffect.setTexture("normalSamplerX",this.normalTextureX),this.normalTextureY&&this._activeEffect.setTexture("normalSamplerY",this.normalTextureY),this.normalTextureZ&&this._activeEffect.setTexture("normalSamplerZ",this.normalTextureZ),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),o.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this.maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){var e=[];return this.mixTexture&&this.mixTexture.animations&&this.mixTexture.animations.length>0&&e.push(this.mixTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTextureX&&e.push(this._diffuseTextureX),this._diffuseTextureY&&e.push(this._diffuseTextureY),this._diffuseTextureZ&&e.push(this._diffuseTextureZ),this._normalTextureX&&e.push(this._normalTextureX),this._normalTextureY&&e.push(this._normalTextureY),this._normalTextureZ&&e.push(this._normalTextureZ),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||(this._diffuseTextureX===e||(this._diffuseTextureY===e||(this._diffuseTextureZ===e||(this._normalTextureX===e||(this._normalTextureY===e||this._normalTextureZ===e)))))},n.prototype.dispose=function(e){this.mixTexture&&this.mixTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.TriPlanarMaterial",i},n.prototype.getClassName=function(){return"TriPlanarMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture()],n.prototype,"mixTexture",void 0),__decorate([e.serializeAsTexture("diffuseTextureX")],n.prototype,"_diffuseTextureX",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTextureX",void 0),__decorate([e.serializeAsTexture("diffuseTexturY")],n.prototype,"_diffuseTextureY",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTextureY",void 0),__decorate([e.serializeAsTexture("diffuseTextureZ")],n.prototype,"_diffuseTextureZ",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTextureZ",void 0),__decorate([e.serializeAsTexture("normalTextureX")],n.prototype,"_normalTextureX",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"normalTextureX",void 0),__decorate([e.serializeAsTexture("normalTextureY")],n.prototype,"_normalTextureY",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"normalTextureY",void 0),__decorate([e.serializeAsTexture("normalTextureZ")],n.prototype,"_normalTextureZ",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"normalTextureZ",void 0),__decorate([e.serialize()],n.prototype,"tileSize",void 0),__decorate([e.serializeAsColor3()],n.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"specularColor",void 0),__decorate([e.serialize()],n.prototype,"specularPower",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.TriPlanarMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.triplanarVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\n#endif\nuniform float tileSize;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void)\n{\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 DIFFUSEX\nvTextureUVX=worldPos.zy/tileSize;\n#endif\n#ifdef DIFFUSEY\nvTextureUVY=worldPos.xz/tileSize;\n#endif\n#ifdef DIFFUSEZ\nvTextureUVZ=worldPos.xy/tileSize;\n#endif\n#ifdef NORMAL\n\nvec3 xtan=vec3(0,0,1);\nvec3 xbin=vec3(0,1,0);\nvec3 ytan=vec3(1,0,0);\nvec3 ybin=vec3(0,0,1);\nvec3 ztan=vec3(1,0,0);\nvec3 zbin=vec3(0,1,0);\nvec3 normalizedNormal=normalize(normal);\nnormalizedNormal*=normalizedNormal;\nvec3 worldBinormal=normalize(xbin*normalizedNormal.x+ybin*normalizedNormal.y+zbin*normalizedNormal.z);\nvec3 worldTangent=normalize(xtan*normalizedNormal.x+ytan*normalizedNormal.y+ztan*normalizedNormal.z);\nworldTangent=(world*vec4(worldTangent,1.0)).xyz;\nworldBinormal=(world*vec4(worldBinormal,1.0)).xyz;\nvec3 worldNormal=normalize(cross(worldTangent,worldBinormal));\ntangentSpace[0]=worldTangent;\ntangentSpace[1]=worldBinormal;\ntangentSpace[2]=worldNormal;\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",BABYLON.Effect.ShadersStore.triplanarPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef DIFFUSEX\nvarying vec2 vTextureUVX;\nuniform sampler2D diffuseSamplerX;\n#ifdef BUMPX\nuniform sampler2D normalSamplerX;\n#endif\n#endif\n#ifdef DIFFUSEY\nvarying vec2 vTextureUVY;\nuniform sampler2D diffuseSamplerY;\n#ifdef BUMPY\nuniform sampler2D normalSamplerY;\n#endif\n#endif\n#ifdef DIFFUSEZ\nvarying vec2 vTextureUVZ;\nuniform sampler2D diffuseSamplerZ;\n#ifdef BUMPZ\nuniform sampler2D normalSamplerZ;\n#endif\n#endif\n#ifdef NORMAL\nvarying mat3 tangentSpace;\n#endif\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(0.,0.,0.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=tangentSpace[2];\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\nvec4 baseNormal=vec4(0.0,0.0,0.0,1.0);\nnormalW*=normalW;\n#ifdef DIFFUSEX\nbaseColor+=texture2D(diffuseSamplerX,vTextureUVX)*normalW.x;\n#ifdef BUMPX\nbaseNormal+=texture2D(normalSamplerX,vTextureUVX)*normalW.x;\n#endif\n#endif\n#ifdef DIFFUSEY\nbaseColor+=texture2D(diffuseSamplerY,vTextureUVY)*normalW.y;\n#ifdef BUMPY\nbaseNormal+=texture2D(normalSamplerY,vTextureUVY)*normalW.y;\n#endif\n#endif\n#ifdef DIFFUSEZ\nbaseColor+=texture2D(diffuseSamplerZ,vTextureUVZ)*normalW.z;\n#ifdef BUMPZ\nbaseNormal+=texture2D(normalSamplerZ,vTextureUVZ)*normalW.z;\n#endif\n#endif\n#ifdef NORMAL\nnormalW=normalize((2.0*baseNormal.xyz-1.0)*tangentSpace);\n#endif\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat shadow=1.;\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularBase=vec3(0.,0.,0.);\nvec3 specularColor=vSpecularColor.rgb;\n#else\nfloat glossiness=0.;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;\n\nvec4 color=vec4(finalDiffuse+finalSpecular,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}\n";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.CLIPPLANE=!1,i.POINTSIZE=!1,i.FOG=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.luminance=1,r.turbidity=10,r.rayleigh=2,r.mieCoefficient=.005,r.mieDirectionalG=.8,r.distance=500,r.inclination=.49,r.azimuth=.25,r.sunPosition=new e.Vector3(0,100,0),r.useSunPosition=!1,r._cameraPosition=e.Vector3.Zero(),r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;if(e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!1),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var s=new e.EffectFallbacks;o.FOG&&s.addFallback(1,"FOG");var f=[e.VertexBuffer.PositionKind];o.VERTEXCOLOR&&f.push(e.VertexBuffer.ColorKind);var l=o.toString();n.setEffect(a.getEngine().createEffect("sky",f,["world","viewProjection","view","vFogInfos","vFogColor","pointSize","vClipPlane","luminance","turbidity","rayleigh","mieCoefficient","mieDirectionalG","sunPosition","cameraPosition"],[],l,s,this.onCompiled,this.onError),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene();if(n._materialDefines){var o=n.effect;if(o){if(this._activeEffect=o,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),this._mustRebind(r,o)){if(r.clipPlane){var a=r.clipPlane;this._activeEffect.setFloat4("vClipPlane",a.normal.x,a.normal.y,a.normal.z,a.d)}this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize)}r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect);var s=r.activeCamera;if(s){var f=s.getWorldMatrix();this._cameraPosition.x=f.m[12],this._cameraPosition.y=f.m[13],this._cameraPosition.z=f.m[14],this._activeEffect.setVector3("cameraPosition",this._cameraPosition)}
  101775. if(this.luminance>0&&this._activeEffect.setFloat("luminance",this.luminance),this._activeEffect.setFloat("turbidity",this.turbidity),this._activeEffect.setFloat("rayleigh",this.rayleigh),this._activeEffect.setFloat("mieCoefficient",this.mieCoefficient),this._activeEffect.setFloat("mieDirectionalG",this.mieDirectionalG),!this.useSunPosition){var l=Math.PI*(this.inclination-.5),u=2*Math.PI*(this.azimuth-.5);this.sunPosition.x=this.distance*Math.cos(u),this.sunPosition.y=this.distance*Math.sin(u)*Math.sin(l),this.sunPosition.z=this.distance*Math.sin(u)*Math.cos(l)}this._activeEffect.setVector3("sunPosition",this.sunPosition),this._afterBind(t,this._activeEffect)}}},n.prototype.getAnimatables=function(){return[]},n.prototype.dispose=function(e){t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.SkyMaterial",i},n.prototype.getClassName=function(){return"SkyMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serialize()],n.prototype,"luminance",void 0),__decorate([e.serialize()],n.prototype,"turbidity",void 0),__decorate([e.serialize()],n.prototype,"rayleigh",void 0),__decorate([e.serialize()],n.prototype,"mieCoefficient",void 0),__decorate([e.serialize()],n.prototype,"mieDirectionalG",void 0),__decorate([e.serialize()],n.prototype,"distance",void 0),__decorate([e.serialize()],n.prototype,"inclination",void 0),__decorate([e.serialize()],n.prototype,"azimuth",void 0),__decorate([e.serializeAsVector3()],n.prototype,"sunPosition",void 0),__decorate([e.serialize()],n.prototype,"useSunPosition",void 0),n})(e.PushMaterial);e.SkyMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.skyVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\nvoid main(void) {\ngl_Position=viewProjection*world*vec4(position,1.0);\nvec4 worldPos=world*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.skyPixelShader="precision highp float;\n\nvarying vec3 vPositionW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\nuniform vec3 cameraPosition;\nuniform float luminance;\nuniform float turbidity;\nuniform float rayleigh;\nuniform float mieCoefficient;\nuniform float mieDirectionalG;\nuniform vec3 sunPosition;\n\n#include<fogFragmentDeclaration>\n\nconst float e=2.71828182845904523536028747135266249775724709369995957;\nconst float pi=3.141592653589793238462643383279502884197169;\nconst float n=1.0003;\nconst float N=2.545E25;\nconst float pn=0.035;\nconst vec3 lambda=vec3(680E-9,550E-9,450E-9);\nconst vec3 K=vec3(0.686,0.678,0.666);\nconst float v=4.0;\nconst float rayleighZenithLength=8.4E3;\nconst float mieZenithLength=1.25E3;\nconst vec3 up=vec3(0.0,1.0,0.0);\nconst float EE=1000.0;\nconst float sunAngularDiameterCos=0.999956676946448443553574619906976478926848692873900859324;\nconst float cutoffAngle=pi/1.95;\nconst float steepness=1.5;\nvec3 totalRayleigh(vec3 lambda)\n{\nreturn (8.0*pow(pi,3.0)*pow(pow(n,2.0)-1.0,2.0)*(6.0+3.0*pn))/(3.0*N*pow(lambda,vec3(4.0))*(6.0-7.0*pn));\n}\nvec3 simplifiedRayleigh()\n{\nreturn 0.0005/vec3(94,40,18);\n}\nfloat rayleighPhase(float cosTheta)\n{ \nreturn (3.0/(16.0*pi))*(1.0+pow(cosTheta,2.0));\n}\nvec3 totalMie(vec3 lambda,vec3 K,float T)\n{\nfloat c=(0.2*T )*10E-18;\nreturn 0.434*c*pi*pow((2.0*pi)/lambda,vec3(v-2.0))*K;\n}\nfloat hgPhase(float cosTheta,float g)\n{\nreturn (1.0/(4.0*pi))*((1.0-pow(g,2.0))/pow(1.0-2.0*g*cosTheta+pow(g,2.0),1.5));\n}\nfloat sunIntensity(float zenithAngleCos)\n{\nreturn EE*max(0.0,1.0-exp(-((cutoffAngle-acos(zenithAngleCos))/steepness)));\n}\nfloat A=0.15;\nfloat B=0.50;\nfloat C=0.10;\nfloat D=0.20;\nfloat EEE=0.02;\nfloat F=0.30;\nfloat W=1000.0;\nvec3 Uncharted2Tonemap(vec3 x)\n{\nreturn ((x*(A*x+C*B)+D*EEE)/(x*(A*x+B)+D*F))-EEE/F;\n}\nvoid main(void) {\n\n#include<clipPlaneFragment>\n\nfloat sunfade=1.0-clamp(1.0-exp((sunPosition.y/450000.0)),0.0,1.0);\nfloat rayleighCoefficient=rayleigh-(1.0*(1.0-sunfade));\nvec3 sunDirection=normalize(sunPosition);\nfloat sunE=sunIntensity(dot(sunDirection,up));\nvec3 betaR=simplifiedRayleigh()*rayleighCoefficient;\nvec3 betaM=totalMie(lambda,K,turbidity)*mieCoefficient;\nfloat zenithAngle=acos(max(0.0,dot(up,normalize(vPositionW-cameraPosition))));\nfloat sR=rayleighZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));\nfloat sM=mieZenithLength/(cos(zenithAngle)+0.15*pow(93.885-((zenithAngle*180.0)/pi),-1.253));\nvec3 Fex=exp(-(betaR*sR+betaM*sM));\nfloat cosTheta=dot(normalize(vPositionW-cameraPosition),sunDirection);\nfloat rPhase=rayleighPhase(cosTheta*0.5+0.5);\nvec3 betaRTheta=betaR*rPhase;\nfloat mPhase=hgPhase(cosTheta,mieDirectionalG);\nvec3 betaMTheta=betaM*mPhase;\nvec3 Lin=pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*(1.0-Fex),vec3(1.5));\nLin*=mix(vec3(1.0),pow(sunE*((betaRTheta+betaMTheta)/(betaR+betaM))*Fex,vec3(1.0/2.0)),clamp(pow(1.0-dot(up,sunDirection),5.0),0.0,1.0));\nvec3 direction=normalize(vPositionW-cameraPosition);\nfloat theta=acos(direction.y);\nfloat phi=atan(direction.z,direction.x);\nvec2 uv=vec2(phi,theta)/vec2(2.0*pi,pi)+vec2(0.5,0.0);\nvec3 L0=vec3(0.1)*Fex;\nfloat sundisk=smoothstep(sunAngularDiameterCos,sunAngularDiameterCos+0.00002,cosTheta);\nL0+=(sunE*19000.0*Fex)*sundisk;\nvec3 whiteScale=1.0/Uncharted2Tonemap(vec3(W));\nvec3 texColor=(Lin+L0); \ntexColor*=0.04 ;\ntexColor+=vec3(0.0,0.001,0.0025)*0.3;\nfloat g_fMaxLuminance=1.0;\nfloat fLumScaled=0.1/luminance; \nfloat fLumCompressed=(fLumScaled*(1.0+(fLumScaled/(g_fMaxLuminance*g_fMaxLuminance))))/(1.0+fLumScaled); \nfloat ExposureBias=fLumCompressed;\nvec3 curr=Uncharted2Tonemap((log2(2.0/pow(luminance,4.0)))*texColor);\n\n\n\nvec3 retColor=curr*whiteScale;\n\n\nfloat alpha=1.0;\n#ifdef VERTEXCOLOR\nretColor.rgb*=vColor.rgb;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec4 color=clamp(vec4(retColor.rgb,alpha),0.0,1.0);\n\n#include<fogFragment>\ngl_FragColor=color;\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.TRANSPARENT=!1,i.FOG=!1,i.PREMULTIPLYALPHA=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.mainColor=e.Color3.Black(),r.lineColor=e.Color3.Teal(),r.gridRatio=1,r.gridOffset=e.Vector3.Zero(),r.majorUnitFrequency=10,r.minorUnitVisibility=.33,r.opacity=1,r.preMultiplyAlpha=!1,r._gridControl=new e.Vector4(r.gridRatio,r.majorUnitFrequency,r.minorUnitVisibility,r.opacity),r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.opacity<1},n.prototype.needAlphaBlendingForMesh=function(e){return this.needAlphaBlending()},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;if(o.TRANSPARENT!==this.opacity<1&&(o.TRANSPARENT=!o.TRANSPARENT,o.markAsUnprocessed()),o.PREMULTIPLYALPHA!=this.preMultiplyAlpha&&(o.PREMULTIPLYALPHA=!o.PREMULTIPLYALPHA,o.markAsUnprocessed()),e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,!1,this.fogEnabled,o),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var s=[e.VertexBuffer.PositionKind,e.VertexBuffer.NormalKind],f=o.toString();n.setEffect(a.getEngine().createEffect("grid",s,["projection","worldView","mainColor","lineColor","gridControl","gridOffset","vFogInfos","vFogColor","world","view"],[],f,void 0,this.onCompiled,this.onError),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene();if(n._materialDefines){var o=n.effect;o&&(this._activeEffect=o,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("worldView",i.multiply(r.getViewMatrix())),this._activeEffect.setMatrix("view",r.getViewMatrix()),this._activeEffect.setMatrix("projection",r.getProjectionMatrix()),this._mustRebind(r,o)&&(this._activeEffect.setColor3("mainColor",this.mainColor),this._activeEffect.setColor3("lineColor",this.lineColor),this._activeEffect.setVector3("gridOffset",this.gridOffset),this._gridControl.x=this.gridRatio,this._gridControl.y=Math.round(this.majorUnitFrequency),this._gridControl.z=this.minorUnitVisibility,this._gridControl.w=this.opacity,this._activeEffect.setVector4("gridControl",this._gridControl)),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},n.prototype.dispose=function(e){t.prototype.dispose.call(this,e)},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.GridMaterial",i},n.prototype.getClassName=function(){return"GridMaterial"},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsColor3()],n.prototype,"mainColor",void 0),__decorate([e.serializeAsColor3()],n.prototype,"lineColor",void 0),__decorate([e.serialize()],n.prototype,"gridRatio",void 0),__decorate([e.serializeAsColor3()],n.prototype,"gridOffset",void 0),__decorate([e.serialize()],n.prototype,"majorUnitFrequency",void 0),__decorate([e.serialize()],n.prototype,"minorUnitVisibility",void 0),__decorate([e.serialize()],n.prototype,"opacity",void 0),__decorate([e.serialize()],n.prototype,"preMultiplyAlpha",void 0),n})(e.PushMaterial);e.GridMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.gridVertexShader="precision highp float;\n\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 projection;\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 worldView;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogVertexDeclaration>\nvoid main(void) {\n#ifdef FOG\nvec4 worldPos=world*vec4(position,1.0);\n#endif\n#include<fogVertex>\nvec4 cameraSpacePosition=worldView*vec4(position,1.0);\ngl_Position=projection*cameraSpacePosition;\n#ifdef TRANSPARENT\nvCameraSpacePosition=cameraSpacePosition;\n#endif\nvPosition=position;\nvNormal=normal;\n}",BABYLON.Effect.ShadersStore.gridPixelShader="#extension GL_OES_standard_derivatives : enable\n#define SQRT2 1.41421356\n#define PI 3.14159\nprecision highp float;\nuniform vec3 mainColor;\nuniform vec3 lineColor;\nuniform vec4 gridControl;\nuniform vec3 gridOffset;\n\n#ifdef TRANSPARENT\nvarying vec4 vCameraSpacePosition;\n#endif\nvarying vec3 vPosition;\nvarying vec3 vNormal;\n#include<fogFragmentDeclaration>\nfloat getVisibility(float position) {\n\nfloat majorGridFrequency=gridControl.y;\nif (floor(position+0.5) == floor(position/majorGridFrequency+0.5)*majorGridFrequency)\n{\nreturn 1.0;\n} \nreturn gridControl.z;\n}\nfloat getAnisotropicAttenuation(float differentialLength) {\nconst float maxNumberOfLines=10.0;\nreturn clamp(1.0/(differentialLength+1.0)-1.0/maxNumberOfLines,0.0,1.0);\n}\nfloat isPointOnLine(float position,float differentialLength) {\nfloat fractionPartOfPosition=position-floor(position+0.5); \nfractionPartOfPosition/=differentialLength; \nfractionPartOfPosition=clamp(fractionPartOfPosition,-1.,1.);\nfloat result=0.5+0.5*cos(fractionPartOfPosition*PI); \nreturn result; \n}\nfloat contributionOnAxis(float position) {\nfloat differentialLength=length(vec2(dFdx(position),dFdy(position)));\ndifferentialLength*=SQRT2; \n\nfloat result=isPointOnLine(position,differentialLength);\n\nfloat visibility=getVisibility(position);\nresult*=visibility;\n\nfloat anisotropicAttenuation=getAnisotropicAttenuation(differentialLength);\nresult*=anisotropicAttenuation;\nreturn result;\n}\nfloat normalImpactOnAxis(float x) {\nfloat normalImpact=clamp(1.0-3.0*abs(x*x*x),0.0,1.0);\nreturn normalImpact;\n}\nvoid main(void) {\n\nfloat gridRatio=gridControl.x;\nvec3 gridPos=(vPosition+gridOffset)/gridRatio;\n\nfloat x=contributionOnAxis(gridPos.x);\nfloat y=contributionOnAxis(gridPos.y);\nfloat z=contributionOnAxis(gridPos.z);\n\nvec3 normal=normalize(vNormal);\nx*=normalImpactOnAxis(normal.x);\ny*=normalImpactOnAxis(normal.y);\nz*=normalImpactOnAxis(normal.z);\n\nfloat grid=clamp(x+y+z,0.,1.);\n\nvec3 color=mix(mainColor,lineColor,grid);\n#ifdef FOG\n#include<fogFragment>\n#endif\n#ifdef TRANSPARENT\nfloat distanceToFragment=length(vCameraSpacePosition.xyz);\nfloat cameraPassThrough=clamp(distanceToFragment-0.25,0.0,1.0);\nfloat opacity=clamp(grid,0.08,cameraPassThrough*gridControl.w*grid);\ngl_FragColor=vec4(color.rgb,opacity);\n#ifdef PREMULTIPLYALPHA\ngl_FragColor.rgb*=opacity;\n#endif\n#else\n\ngl_FragColor=vec4(color.rgb,1.0);\n#endif\n}";var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.AMBIENT=!1,i.OPACITY=!1,i.OPACITYRGB=!1,i.REFLECTION=!1,i.EMISSIVE=!1,i.SPECULAR=!1,i.BUMP=!1,i.PARALLAX=!1,i.PARALLAXOCCLUSION=!1,i.SPECULAROVERALPHA=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.ALPHAFROMDIFFUSE=!1,i.POINTSIZE=!1,i.FOG=!1,i.SPECULARTERM=!1,i.DIFFUSEFRESNEL=!1,i.OPACITYFRESNEL=!1,i.REFLECTIONFRESNEL=!1,i.REFRACTIONFRESNEL=!1,i.EMISSIVEFRESNEL=!1,i.FRESNEL=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.GLOSSINESS=!1,i.ROUGHNESS=!1,i.EMISSIVEASILLUMINATION=!1,i.LINKEMISSIVEWITHDIFFUSE=!1,i.REFLECTIONFRESNELFROMSPECULAR=!1,i.LIGHTMAP=!1,i.USELIGHTMAPASSHADOWMAP=!1,i.REFLECTIONMAP_3D=!1,i.REFLECTIONMAP_SPHERICAL=!1,i.REFLECTIONMAP_PLANAR=!1,i.REFLECTIONMAP_CUBIC=!1,i.REFLECTIONMAP_PROJECTION=!1,i.REFLECTIONMAP_SKYBOX=!1,i.REFLECTIONMAP_EXPLICIT=!1,i.REFLECTIONMAP_EQUIRECTANGULAR=!1,i.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,i.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,i.INVERTCUBICMAP=!1,i.LOGARITHMICDEPTH=!1,i.REFRACTION=!1,i.REFRACTIONMAP_3D=!1,i.REFLECTIONOVERALPHA=!1,i.TWOSIDEDLIGHTING=!1,i.SHADOWFLOAT=!1,i.MORPHTARGETS=!1,i.MORPHTARGETS_NORMAL=!1,i.MORPHTARGETS_TANGENT=!1,i.NUM_MORPH_INFLUENCERS=0,i.IMAGEPROCESSING=!1,i.VIGNETTE=!1,i.VIGNETTEBLENDMODEMULTIPLY=!1,i.VIGNETTEBLENDMODEOPAQUE=!1,i.TONEMAPPING=!1,i.CONTRAST=!1,i.COLORCURVES=!1,i.COLORGRADING=!1,i.COLORGRADING3D=!1,i.SAMPLER3DGREENDEPTH=!1,i.SAMPLER3DBGRMAP=!1,i.IMAGEPROCESSINGPOSTPROCESS=!1,i.EXPOSURE=!1,i.rebuild(),i}return __extends(i,e),i.prototype.setReflectionMode=function(e){for(var i=["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"],t=0,n=i;t<n.length;t++){var r=n[t];this[r]=r===e}},i})(e.MaterialDefines);e.StandardMaterialDefines_OldVer=i;var t=(function(t){function n(i,r){var o=t.call(this,i,r)||this;return o.ambientColor=new e.Color3(0,0,0),o.diffuseColor=new e.Color3(1,1,1),o.specularColor=new e.Color3(1,1,1),o.emissiveColor=new e.Color3(0,0,0),o.specularPower=64,o._useAlphaFromDiffuseTexture=!1,o._useEmissiveAsIllumination=!1,o._linkEmissiveWithDiffuse=!1,o._useSpecularOverAlpha=!1,o._useReflectionOverAlpha=!1,o._disableLighting=!1,o._useParallax=!1,o._useParallaxOcclusion=!1,o.parallaxScaleBias=.05,o._roughness=0,o.indexOfRefraction=.98,o.invertRefractionY=!0,o._useLightmapAsShadowmap=!1,o._useReflectionFresnelFromSpecular=!1,o._useGlossinessFromSpecularMapAlpha=!1,o._maxSimultaneousLights=4,o._invertNormalMapX=!1,o._invertNormalMapY=!1,o._twoSidedLighting=!1,o._renderTargets=new e.SmartArray(16),o._worldViewProjectionMatrix=e.Matrix.Zero(),o._globalAmbientColor=new e.Color3(0,0,0),o._attachImageProcessingConfiguration(null),o.getRenderTargetTextures=function(){return o._renderTargets.reset(),n.ReflectionTextureEnabled&&o._reflectionTexture&&o._reflectionTexture.isRenderTarget&&o._renderTargets.push(o._reflectionTexture),n.RefractionTextureEnabled&&o._refractionTexture&&o._refractionTexture.isRenderTarget&&o._renderTargets.push(o._refractionTexture),o._renderTargets},o}return __extends(n,t),Object.defineProperty(n.prototype,"imageProcessingConfiguration",{get:function(){return this._imageProcessingConfiguration},set:function(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()},enumerable:!0,configurable:!0}),n.prototype._attachImageProcessingConfiguration=function(e){var i=this;e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((function(e){i._markAllSubMeshesAsImageProcessingDirty()})))},Object.defineProperty(n.prototype,"cameraColorCurvesEnabled",{get:function(){return this.imageProcessingConfiguration.colorCurvesEnabled},set:function(e){this.imageProcessingConfiguration.colorCurvesEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraColorGradingEnabled",{get:function(){return this.imageProcessingConfiguration.colorGradingEnabled},set:function(e){this.imageProcessingConfiguration.colorGradingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraToneMappingEnabled",{get:function(){return this._imageProcessingConfiguration.toneMappingEnabled},set:function(e){this._imageProcessingConfiguration.toneMappingEnabled=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraExposure",{get:function(){return this._imageProcessingConfiguration.exposure},set:function(e){this._imageProcessingConfiguration.exposure=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraContrast",{get:function(){return this._imageProcessingConfiguration.contrast},set:function(e){this._imageProcessingConfiguration.contrast=e},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"cameraColorGradingTexture",{get:function(){return this._imageProcessingConfiguration.colorGradingTexture},set:function(e){this._imageProcessingConfiguration.colorGradingTexture=e},enumerable:!0,configurable:!0}),n.prototype.getClassName=function(){return"StandardMaterial_OldVer"},Object.defineProperty(n.prototype,"useLogarithmicDepth",{get:function(){return this._useLogarithmicDepth},set:function(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()},enumerable:!0,configurable:!0}),n.prototype.needAlphaBlending=function(){return this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled},n.prototype.needAlphaTesting=function(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha},n.prototype._shouldUseAlphaFromDiffuseTexture=function(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture},n.prototype.getAlphaTestTexture=function(){return this._diffuseTexture},n.prototype.isReadyForSubMesh=function(t,r,o){if(this.isFrozen&&this._wasPreviouslyReady&&r.effect)return!0;r._materialDefines||(r._materialDefines=new i);var a=this.getScene(),s=r._materialDefines;if(!this.checkReadyOnEveryCall&&r.effect&&s._renderId===a.getRenderId())return!0;var f=a.getEngine();if(s._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,s,!0,this._maxSimultaneousLights,this._disableLighting),s._areTexturesDirty){if(s._needUVs=!1,a.texturesEnabled){if(this._diffuseTexture&&n.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.DIFFUSE=!0}else s.DIFFUSE=!1;if(this._ambientTexture&&n.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.AMBIENT=!0}else s.AMBIENT=!1;if(this._opacityTexture&&n.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.OPACITY=!0,s.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else s.OPACITY=!1;if(this._reflectionTexture&&n.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(s._needNormals=!0,s.REFLECTION=!0,s.ROUGHNESS=this._roughness>0,s.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,s.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===e.Texture.INVCUBIC_MODE,s.REFLECTIONMAP_3D=this._reflectionTexture.isCube,this._reflectionTexture.coordinatesMode){case e.Texture.CUBIC_MODE:case e.Texture.INVCUBIC_MODE:s.setReflectionMode("REFLECTIONMAP_CUBIC");break;case e.Texture.EXPLICIT_MODE:s.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case e.Texture.PLANAR_MODE:s.setReflectionMode("REFLECTIONMAP_PLANAR");break;case e.Texture.PROJECTION_MODE:s.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case e.Texture.SKYBOX_MODE:s.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case e.Texture.SPHERICAL_MODE:s.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case e.Texture.EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case e.Texture.FIXED_EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case e.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED")}}else s.REFLECTION=!1;if(this._emissiveTexture&&n.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.EMISSIVE=!0}else s.EMISSIVE=!1;if(this._lightmapTexture&&n.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.LIGHTMAP=!0,s.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap}else s.LIGHTMAP=!1;if(this._specularTexture&&n.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.SPECULAR=!0,s.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else s.SPECULAR=!1;if(a.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&n.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;s._needUVs=!0,s.BUMP=!0,s.PARALLAX=this._useParallax,s.PARALLAXOCCLUSION=this._useParallaxOcclusion}else s.BUMP=!1;if(this._refractionTexture&&n.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.REFRACTION=!0,s.REFRACTIONMAP_3D=this._refractionTexture.isCube}else s.REFRACTION=!1;s.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else s.DIFFUSE=!1,s.AMBIENT=!1,s.OPACITY=!1,s.REFLECTION=!1,s.EMISSIVE=!1,s.LIGHTMAP=!1,s.BUMP=!1,s.REFRACTION=!1;s.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),s.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,s.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,s.SPECULAROVERALPHA=this._useSpecularOverAlpha}if(s._areImageProcessingDirty){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s)}if(s._areFresnelDirty&&(n.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(s.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,s.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,s.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,s.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,s.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,s.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,s._needNormals=!0,s.FRESNEL=!0):s.FRESNEL=!1),e.MaterialHelper.PrepareDefinesForMisc(t,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,s),e.MaterialHelper.PrepareDefinesForAttributes(t,s,!0,!0,!0),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,f,s,!!o),s.isDirty){s.markAsProcessed(),a.resetCachedMaterial();var l=new e.EffectFallbacks;s.REFLECTION&&l.addFallback(0,"REFLECTION"),s.SPECULAR&&l.addFallback(0,"SPECULAR"),s.BUMP&&l.addFallback(0,"BUMP"),s.PARALLAX&&l.addFallback(1,"PARALLAX"),s.PARALLAXOCCLUSION&&l.addFallback(0,"PARALLAXOCCLUSION"),s.SPECULAROVERALPHA&&l.addFallback(0,"SPECULAROVERALPHA"),s.FOG&&l.addFallback(1,"FOG"),s.POINTSIZE&&l.addFallback(0,"POINTSIZE"),s.LOGARITHMICDEPTH&&l.addFallback(0,"LOGARITHMICDEPTH"),e.MaterialHelper.HandleFallbacksForShadows(s,l,this._maxSimultaneousLights),s.SPECULARTERM&&l.addFallback(0,"SPECULARTERM"),s.DIFFUSEFRESNEL&&l.addFallback(1,"DIFFUSEFRESNEL"),s.OPACITYFRESNEL&&l.addFallback(2,"OPACITYFRESNEL"),s.REFLECTIONFRESNEL&&l.addFallback(3,"REFLECTIONFRESNEL"),s.EMISSIVEFRESNEL&&l.addFallback(4,"EMISSIVEFRESNEL"),s.FRESNEL&&l.addFallback(4,"FRESNEL");var u=[e.VertexBuffer.PositionKind];s.NORMAL&&u.push(e.VertexBuffer.NormalKind),s.UV1&&u.push(e.VertexBuffer.UVKind),s.UV2&&u.push(e.VertexBuffer.UV2Kind),s.VERTEXCOLOR&&u.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(u,t,s,l),e.MaterialHelper.PrepareAttributesForInstances(u,s),e.MaterialHelper.PrepareAttributesForMorphTargets(u,t,s);var c="default",d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","vClipPlane","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","logarithmicDepthConstant","vTangentSpaceParams"],p=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler"],h=["Material","Scene"];e.ImageProcessingConfiguration.PrepareUniforms(d,s),e.ImageProcessingConfiguration.PrepareSamplers(p,s),e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:d,uniformBuffersNames:h,samplers:p,defines:s,maxSimultaneousLights:this._maxSimultaneousLights}),this.customShaderNameResolve&&(c=this.customShaderNameResolve(c,d,h,p,s));var m=s.toString();r.setEffect(a.getEngine().createEffect(c,{attributes:u,uniformsNames:d,uniformBuffersNames:h,samplers:p,defines:m,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS}},f),s),this.buildUniformLayout()}return!(!r.effect||!r.effect.isReady())&&(s._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.buildUniformLayout=function(){this._uniformBuffer.addUniform("diffuseLeftColor",4),this._uniformBuffer.addUniform("diffuseRightColor",4),this._uniformBuffer.addUniform("opacityParts",4),this._uniformBuffer.addUniform("reflectionLeftColor",4),this._uniformBuffer.addUniform("reflectionRightColor",4),this._uniformBuffer.addUniform("refractionLeftColor",4),this._uniformBuffer.addUniform("refractionRightColor",4),this._uniformBuffer.addUniform("emissiveLeftColor",4),this._uniformBuffer.addUniform("emissiveRightColor",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vAmbientInfos",2),this._uniformBuffer.addUniform("vOpacityInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("vEmissiveInfos",2),this._uniformBuffer.addUniform("vLightmapInfos",2),this._uniformBuffer.addUniform("vSpecularInfos",2),this._uniformBuffer.addUniform("vBumpInfos",3),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("ambientMatrix",16),this._uniformBuffer.addUniform("opacityMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("emissiveMatrix",16),this._uniformBuffer.addUniform("lightmapMatrix",16),this._uniformBuffer.addUniform("specularMatrix",16),this._uniformBuffer.addUniform("bumpMatrix",16),this._uniformBuffer.addUniform("vTangentSpaceParams",2),this._uniformBuffer.addUniform("refractionMatrix",16),this._uniformBuffer.addUniform("vRefractionInfos",4),this._uniformBuffer.addUniform("vSpecularColor",4),this._uniformBuffer.addUniform("vEmissiveColor",3),this._uniformBuffer.addUniform("vDiffuseColor",4),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.create()},n.prototype.unbind=function(){this._activeEffect&&(this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._activeEffect.setTexture("reflection2DSampler",null),this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._activeEffect.setTexture("refraction2DSampler",null)),t.prototype.unbind.call(this)},n.prototype.bindForSubMesh=function(i,t,r){var o=this.getScene(),a=r._materialDefines;if(a){var s=r.effect;if(s){if(this._activeEffect=s,this.bindOnlyWorldMatrix(i),e.MaterialHelper.BindBonesParameters(t,s),this._mustRebind(o,s,t.visibility)){if(this._uniformBuffer.bindToEffect(s,"Material"),this.bindViewProjection(s),!this._uniformBuffer.useUbo||!this.isFrozen||!this._uniformBuffer.isSync){if(n.FresnelEnabled&&a.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),this._uniformBuffer.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&this._uniformBuffer.updateColor4("opacityParts",new e.Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),this._uniformBuffer.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),this._uniformBuffer.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(this._uniformBuffer.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),this._uniformBuffer.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),
  101776. o.texturesEnabled&&(this._diffuseTexture&&n.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._uniformBuffer.updateMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),this._ambientTexture&&n.AmbientTextureEnabled&&(this._uniformBuffer.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),this._uniformBuffer.updateMatrix("ambientMatrix",this._ambientTexture.getTextureMatrix())),this._opacityTexture&&n.OpacityTextureEnabled&&(this._uniformBuffer.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),this._uniformBuffer.updateMatrix("opacityMatrix",this._opacityTexture.getTextureMatrix())),this._reflectionTexture&&n.ReflectionTextureEnabled&&(this._uniformBuffer.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),this._uniformBuffer.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix())),this._emissiveTexture&&n.EmissiveTextureEnabled&&(this._uniformBuffer.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),this._uniformBuffer.updateMatrix("emissiveMatrix",this._emissiveTexture.getTextureMatrix())),this._lightmapTexture&&n.LightmapTextureEnabled&&(this._uniformBuffer.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),this._uniformBuffer.updateMatrix("lightmapMatrix",this._lightmapTexture.getTextureMatrix())),this._specularTexture&&n.SpecularTextureEnabled&&(this._uniformBuffer.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),this._uniformBuffer.updateMatrix("specularMatrix",this._specularTexture.getTextureMatrix())),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&n.BumpTextureEnabled&&(this._uniformBuffer.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),this._uniformBuffer.updateMatrix("bumpMatrix",this._bumpTexture.getTextureMatrix()),o._mirroredCameraPosition?this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):this._uniformBuffer.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&n.RefractionTextureEnabled)){var f=1;this._refractionTexture.isCube||(this._uniformBuffer.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(f=this._refractionTexture.depth)),this._uniformBuffer.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,f,this.invertRefractionY?-1:1)}this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),a.SPECULARTERM&&this._uniformBuffer.updateColor4("vSpecularColor",this.specularColor,this.specularPower),this._uniformBuffer.updateColor3("vEmissiveColor",this.emissiveColor),this._uniformBuffer.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility)}if(o.texturesEnabled&&(this._diffuseTexture&&n.DiffuseTextureEnabled&&s.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&n.AmbientTextureEnabled&&s.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&n.OpacityTextureEnabled&&s.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&n.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?s.setTexture("reflectionCubeSampler",this._reflectionTexture):s.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&n.EmissiveTextureEnabled&&s.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&n.LightmapTextureEnabled&&s.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&n.SpecularTextureEnabled&&s.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&o.getEngine().getCaps().standardDerivatives&&n.BumpTextureEnabled&&s.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&n.RefractionTextureEnabled)){var f=1;this._refractionTexture.isCube?s.setTexture("refractionCubeSampler",this._refractionTexture):s.setTexture("refraction2DSampler",this._refractionTexture)}e.MaterialHelper.BindClipPlane(s,o),o.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),e.MaterialHelper.BindEyePosition(s,o),s.setColor3("vAmbientColor",this._globalAmbientColor)}!this._mustRebind(o,s)&&this.isFrozen||(o.lightsEnabled&&!this._disableLighting&&e.MaterialHelper.BindLights(o,t,s,a,this._maxSimultaneousLights),(o.fogEnabled&&t.applyFog&&o.fogMode!==e.Scene.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture)&&this.bindView(s),e.MaterialHelper.BindFogParameters(o,t,s),a.NUM_MORPH_INFLUENCERS&&e.MaterialHelper.BindMorphTargetParameters(t,s),e.MaterialHelper.BindLogDepth(a,s,o),this._imageProcessingConfiguration.bind(this._activeEffect)),this._uniformBuffer.update(),this._afterBind(t,this._activeEffect)}}},n.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e},n.prototype.dispose=function(e,i){i&&(this._diffuseTexture&&this._diffuseTexture.dispose(),this._ambientTexture&&this._ambientTexture.dispose(),this._opacityTexture&&this._opacityTexture.dispose(),this._reflectionTexture&&this._reflectionTexture.dispose(),this._emissiveTexture&&this._emissiveTexture.dispose(),this._specularTexture&&this._specularTexture.dispose(),this._bumpTexture&&this._bumpTexture.dispose(),this._lightmapTexture&&this._lightmapTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),t.prototype.dispose.call(this,e,i)},n.prototype.clone=function(i){var t=this,r=e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this);return r.name=i,r.id=i,r},n.prototype.serialize=function(){return e.SerializationHelper.Serialize(this)},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},Object.defineProperty(n,"DiffuseTextureEnabled",{get:function(){return n._DiffuseTextureEnabled},set:function(i){n._DiffuseTextureEnabled!==i&&(n._DiffuseTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"AmbientTextureEnabled",{get:function(){return n._AmbientTextureEnabled},set:function(i){n._AmbientTextureEnabled!==i&&(n._AmbientTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"OpacityTextureEnabled",{get:function(){return n._OpacityTextureEnabled},set:function(i){n._OpacityTextureEnabled!==i&&(n._OpacityTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"ReflectionTextureEnabled",{get:function(){return n._ReflectionTextureEnabled},set:function(i){n._ReflectionTextureEnabled!==i&&(n._ReflectionTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"EmissiveTextureEnabled",{get:function(){return n._EmissiveTextureEnabled},set:function(i){n._EmissiveTextureEnabled!==i&&(n._EmissiveTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"SpecularTextureEnabled",{get:function(){return n._SpecularTextureEnabled},set:function(i){n._SpecularTextureEnabled!==i&&(n._SpecularTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"BumpTextureEnabled",{get:function(){return n._BumpTextureEnabled},set:function(i){n._BumpTextureEnabled!==i&&(n._BumpTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"LightmapTextureEnabled",{get:function(){return n._LightmapTextureEnabled},set:function(i){n._LightmapTextureEnabled!==i&&(n._LightmapTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"RefractionTextureEnabled",{get:function(){return n._RefractionTextureEnabled},set:function(i){n._RefractionTextureEnabled!==i&&(n._RefractionTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"ColorGradingTextureEnabled",{get:function(){return n._ColorGradingTextureEnabled},set:function(i){n._ColorGradingTextureEnabled!==i&&(n._ColorGradingTextureEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.TextureDirtyFlag))},enumerable:!0,configurable:!0}),Object.defineProperty(n,"FresnelEnabled",{get:function(){return n._FresnelEnabled},set:function(i){n._FresnelEnabled!==i&&(n._FresnelEnabled=i,e.Engine.MarkAllMaterialsAsDirty(e.Material.FresnelDirtyFlag))},enumerable:!0,configurable:!0}),n._DiffuseTextureEnabled=!0,n._AmbientTextureEnabled=!0,n._OpacityTextureEnabled=!0,n._ReflectionTextureEnabled=!0,n._EmissiveTextureEnabled=!0,n._SpecularTextureEnabled=!0,n._BumpTextureEnabled=!0,n._LightmapTextureEnabled=!0,n._RefractionTextureEnabled=!0,n._ColorGradingTextureEnabled=!0,n._FresnelEnabled=!0,__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsTexture("ambientTexture")],n.prototype,"_ambientTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"ambientTexture",void 0),__decorate([e.serializeAsTexture("opacityTexture")],n.prototype,"_opacityTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"opacityTexture",void 0),__decorate([e.serializeAsTexture("reflectionTexture")],n.prototype,"_reflectionTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"reflectionTexture",void 0),__decorate([e.serializeAsTexture("emissiveTexture")],n.prototype,"_emissiveTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"emissiveTexture",void 0),__decorate([e.serializeAsTexture("specularTexture")],n.prototype,"_specularTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"specularTexture",void 0),__decorate([e.serializeAsTexture("bumpTexture")],n.prototype,"_bumpTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"bumpTexture",void 0),__decorate([e.serializeAsTexture("lightmapTexture")],n.prototype,"_lightmapTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"lightmapTexture",void 0),__decorate([e.serializeAsTexture("refractionTexture")],n.prototype,"_refractionTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"refractionTexture",void 0),__decorate([e.serializeAsColor3("ambient")],n.prototype,"ambientColor",void 0),__decorate([e.serializeAsColor3("diffuse")],n.prototype,"diffuseColor",void 0),__decorate([e.serializeAsColor3("specular")],n.prototype,"specularColor",void 0),__decorate([e.serializeAsColor3("emissive")],n.prototype,"emissiveColor",void 0),__decorate([e.serialize()],n.prototype,"specularPower",void 0),__decorate([e.serialize("useAlphaFromDiffuseTexture")],n.prototype,"_useAlphaFromDiffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useAlphaFromDiffuseTexture",void 0),__decorate([e.serialize("useEmissiveAsIllumination")],n.prototype,"_useEmissiveAsIllumination",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useEmissiveAsIllumination",void 0),__decorate([e.serialize("linkEmissiveWithDiffuse")],n.prototype,"_linkEmissiveWithDiffuse",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"linkEmissiveWithDiffuse",void 0),__decorate([e.serialize("useSpecularOverAlpha")],n.prototype,"_useSpecularOverAlpha",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useSpecularOverAlpha",void 0),__decorate([e.serialize("useReflectionOverAlpha")],n.prototype,"_useReflectionOverAlpha",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useReflectionOverAlpha",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("useParallax")],n.prototype,"_useParallax",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useParallax",void 0),__decorate([e.serialize("useParallaxOcclusion")],n.prototype,"_useParallaxOcclusion",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useParallaxOcclusion",void 0),__decorate([e.serialize()],n.prototype,"parallaxScaleBias",void 0),__decorate([e.serialize("roughness")],n.prototype,"_roughness",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"roughness",void 0),__decorate([e.serialize()],n.prototype,"indexOfRefraction",void 0),__decorate([e.serialize()],n.prototype,"invertRefractionY",void 0),__decorate([e.serialize("useLightmapAsShadowmap")],n.prototype,"_useLightmapAsShadowmap",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useLightmapAsShadowmap",void 0),__decorate([e.serializeAsFresnelParameters("diffuseFresnelParameters")],n.prototype,"_diffuseFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"diffuseFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters("opacityFresnelParameters")],n.prototype,"_opacityFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"opacityFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters("reflectionFresnelParameters")],n.prototype,"_reflectionFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"reflectionFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters("refractionFresnelParameters")],n.prototype,"_refractionFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"refractionFresnelParameters",void 0),__decorate([e.serializeAsFresnelParameters("emissiveFresnelParameters")],n.prototype,"_emissiveFresnelParameters",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"emissiveFresnelParameters",void 0),__decorate([e.serialize("useReflectionFresnelFromSpecular")],n.prototype,"_useReflectionFresnelFromSpecular",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsFresnelDirty")],n.prototype,"useReflectionFresnelFromSpecular",void 0),__decorate([e.serialize("useGlossinessFromSpecularMapAlpha")],n.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"useGlossinessFromSpecularMapAlpha",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),__decorate([e.serialize("invertNormalMapX")],n.prototype,"_invertNormalMapX",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"invertNormalMapX",void 0),__decorate([e.serialize("invertNormalMapY")],n.prototype,"_invertNormalMapY",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"invertNormalMapY",void 0),__decorate([e.serialize("twoSidedLighting")],n.prototype,"_twoSidedLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"twoSidedLighting",void 0),__decorate([e.serialize()],n.prototype,"useLogarithmicDepth",null),n})(e.PushMaterial);e.StandardMaterial_OldVer=t;var n=(function(){function e(){}return e})();e.CustomShaderStructure=n;var r=(function(){function e(){}return e})();e.ShaderSpecialParts=r;var o=(function(e){function i(){var i=e.call(this)||this;return i.VertexStore="",i.FragmentStore="#include<__decl__defaultFragment>\n#[Fragment_Begin]\n#extension GL_OES_standard_derivatives : enable\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_helper;\nvarying vec3 localNormal;\nvarying vec3 localPosition;\nvec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\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)\nvarying vec2 vSpecularUV;\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\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n\n#[Fragment_Definitions]\n\nvoid main(void) {\n\nvNormalW = vNormalW_helper;\n#[Fragment_MainBegin]\n\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#[Fragment_Custom_Diffuse]\n\nfloat alpha=vDiffuseColor.a;\n#[Fragment_Custom_Alpha]\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n// Apply image processing if relevant. As this applies in linear space, \n// We first move from gamma to linear.\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\tcolor.rgb = toLinearSpace(color.rgb);\n#else\n\t#ifdef IMAGEPROCESSING\n\t\tcolor.rgb = toLinearSpace(color.rgb);\n\t\tcolor = applyImageProcessing(color);\n\t#endif\n#endif\n\n#[Fragment_Before_FragColor]\ngl_FragColor=color;\n}",i.VertexStore="#include<__decl__defaultVertex>\n\n#[Vertex_Begin]\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 localPosition;\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW_helper;\nvarying vec3 localNormal;\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\n#[Vertex_Definitions]\n\nvoid main(void) {\n \n #[Vertex_MainBegin]\n \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>\n\nlocalPosition = positionUpdated;\n#[Vertex_Before_PositionUpdated]\n\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\n\n#[Vertex_Before_NormalUpdated]\n\nlocalNormal = normalUpdated;\nvNormalW_helper=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\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 DIFFUSE\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#ifdef AMBIENT\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#ifdef OPACITY\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#ifdef EMISSIVE\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#ifdef LIGHTMAP\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)\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#ifdef BUMP\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}",i}return __extends(i,e),i})(n);e.ShaderForVer3_0=o;var a=(function(){function e(){}return e.Ver3_0="3.0.0",e})();e.StandardShaderVersions=a;var s=(function(i){function t(e,t){var n=i.call(this,e,t)||this;return n.CustomParts=new r,n.customShaderNameResolve=n.Builder,n.SelectVersion("3.0.0"),n}return __extends(t,i),t.prototype.AttachAfterBind=function(e,i){for(var t in this._newUniformInstances){var n=t.toString().split("-");"vec2"==n[0]?i.setVector2(n[1],this._newUniformInstances[t]):"vec3"==n[0]?i.setVector3(n[1],this._newUniformInstances[t]):"vec4"==n[0]?i.setVector4(n[1],this._newUniformInstances[t]):"mat4"==n[0]?i.setMatrix(n[1],this._newUniformInstances[t]):"float"==n[0]&&i.setFloat(n[1],this._newUniformInstances[t])}for(var t in this._newSamplerInstances){var n=t.toString().split("-");"sampler2D"==n[0]&&this._newSamplerInstances[t].isReady&&this._newSamplerInstances[t].isReady()&&i.setTexture(n[1],this._newSamplerInstances[t])}},t.prototype.ReviewUniform=function(e,i){
  101777. if("uniform"==e)for(var t in this._newUniforms)-1==this._customUniform[t].indexOf("sampler")&&i.push(this._newUniforms[t]);if("sampler"==e)for(var t in this._newUniforms)-1!=this._customUniform[t].indexOf("sampler")&&i.push(this._newUniforms[t]);return i},t.prototype.Builder=function(i,n,r,o,a){var s=this;if(this._isCreatedShader)return this._createdShaderName;this._isCreatedShader=!1,t.ShaderIndexer++;var f="custom_"+t.ShaderIndexer;this.ReviewUniform("uniform",n),this.ReviewUniform("sampler",o);var l=this._afterBind;return this._afterBind=function(e,i){if(i){s.AttachAfterBind(e,i);try{l(e,i)}catch(i){}}},e.Effect.ShadersStore[f+"VertexShader"]=this.ShaderVersion.VertexStore.replace("#[Vertex_Begin]",this.CustomParts.Vertex_Begin?this.CustomParts.Vertex_Begin:"").replace("#[Vertex_Definitions]",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Vertex_Definitions?this.CustomParts.Vertex_Definitions:"")).replace("#[Vertex_MainBegin]",this.CustomParts.Vertex_MainBegin?this.CustomParts.Vertex_MainBegin:"").replace("#[Vertex_Before_PositionUpdated]",this.CustomParts.Vertex_Before_PositionUpdated?this.CustomParts.Vertex_Before_PositionUpdated:"").replace("#[Vertex_Before_NormalUpdated]",this.CustomParts.Vertex_Before_NormalUpdated?this.CustomParts.Vertex_Before_NormalUpdated:""),e.Effect.ShadersStore[f+"PixelShader"]=this.ShaderVersion.FragmentStore.replace("#[Fragment_Begin]",this.CustomParts.Fragment_Begin?this.CustomParts.Fragment_Begin:"").replace("#[Fragment_MainBegin]",this.CustomParts.Fragment_MainBegin?this.CustomParts.Fragment_MainBegin:"").replace("#[Fragment_Definitions]",(this._customUniform?this._customUniform.join("\n"):"")+(this.CustomParts.Fragment_Definitions?this.CustomParts.Fragment_Definitions:"")).replace("#[Fragment_Custom_Diffuse]",this.CustomParts.Fragment_Custom_Diffuse?this.CustomParts.Fragment_Custom_Diffuse:"").replace("#[Fragment_Custom_Alpha]",this.CustomParts.Fragment_Custom_Alpha?this.CustomParts.Fragment_Custom_Alpha:"").replace("#[Fragment_Before_FragColor]",this.CustomParts.Fragment_Before_FragColor?this.CustomParts.Fragment_Before_FragColor:""),this._isCreatedShader=!0,this._createdShaderName=f,f},t.prototype.SelectVersion=function(e){switch(e){case"3.0.0":this.ShaderVersion=new o}},t.prototype.AddUniform=function(e,i,t){return this._customUniform||(this._customUniform=new Array,this._newUniforms=new Array,this._newSamplerInstances=new Array,this._newUniformInstances=new Array),t&&(i.indexOf("sampler"),this._newUniformInstances[i+"-"+e]=t),this._customUniform.push("uniform "+i+" "+e+";"),this._newUniforms.push(e),this},t.prototype.Fragment_Begin=function(e){return this.CustomParts.Fragment_Begin=e,this},t.prototype.Fragment_Definitions=function(e){return this.CustomParts.Fragment_Definitions=e,this},t.prototype.Fragment_MainBegin=function(e){return this.CustomParts.Fragment_MainBegin=e,this},t.prototype.Fragment_Custom_Diffuse=function(e){return this.CustomParts.Fragment_Custom_Diffuse=e.replace("result","diffuseColor"),this},t.prototype.Fragment_Custom_Alpha=function(e){return this.CustomParts.Fragment_Custom_Alpha=e.replace("result","alpha"),this},t.prototype.Fragment_Before_FragColor=function(e){return this.CustomParts.Fragment_Before_FragColor=e.replace("result","color"),this},t.prototype.Vertex_Begin=function(e){return this.CustomParts.Vertex_Begin=e,this},t.prototype.Vertex_Definitions=function(e){return this.CustomParts.Vertex_Definitions=e,this},t.prototype.Vertex_MainBegin=function(e){return this.CustomParts.Vertex_MainBegin=e,this},t.prototype.Vertex_Before_PositionUpdated=function(e){return this.CustomParts.Vertex_Before_PositionUpdated=e.replace("result","positionUpdated"),this},t.prototype.Vertex_Before_NormalUpdated=function(e){return this.CustomParts.Vertex_Before_NormalUpdated=e.replace("result","normalUpdated"),this},t.ShaderIndexer=1,t})(t);e.CustomMaterial=s})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var i=(function(e){function i(){var i=e.call(this)||this;return i.DIFFUSE=!1,i.CLIPPLANE=!1,i.ALPHATEST=!1,i.POINTSIZE=!1,i.FOG=!1,i.NORMAL=!1,i.UV1=!1,i.UV2=!1,i.VERTEXCOLOR=!1,i.VERTEXALPHA=!1,i.NUM_BONE_INFLUENCERS=0,i.BonesPerMesh=0,i.INSTANCES=!1,i.NDOTL=!0,i.CUSTOMUSERLIGHTING=!0,i.CELLBASIC=!0,i.DEPTHPREPASS=!1,i.rebuild(),i}return __extends(i,e),i})(e.MaterialDefines),t=(function(t){function n(i,n){var r=t.call(this,i,n)||this;return r.diffuseColor=new e.Color3(1,1,1),r._computeHighLevel=!1,r._disableLighting=!1,r._maxSimultaneousLights=4,r}return __extends(n,t),n.prototype.needAlphaBlending=function(){return this.alpha<1},n.prototype.needAlphaTesting=function(){return!1},n.prototype.getAlphaTestTexture=function(){return null},n.prototype.isReadyForSubMesh=function(t,n,r){if(this.isFrozen&&this._wasPreviouslyReady&&n.effect)return!0;n._materialDefines||(n._materialDefines=new i);var o=n._materialDefines,a=this.getScene();if(!this.checkReadyOnEveryCall&&n.effect&&this._renderId===a.getRenderId())return!0;var s=a.getEngine();if(o._areTexturesDirty&&(o._needUVs=!1,a.texturesEnabled&&this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled)){if(!this._diffuseTexture.isReady())return!1;o._needUVs=!0,o.DIFFUSE=!0}if(o.CELLBASIC=!this.computeHighLevel,e.MaterialHelper.PrepareDefinesForMisc(t,a,!1,this.pointsCloud,this.fogEnabled,o),o._needNormals=e.MaterialHelper.PrepareDefinesForLights(a,t,o,!1,this._maxSimultaneousLights,this._disableLighting),e.MaterialHelper.PrepareDefinesForFrameBoundValues(a,s,o,!!r),e.MaterialHelper.PrepareDefinesForAttributes(t,o,!0,!0),o.isDirty){o.markAsProcessed(),a.resetCachedMaterial();var f=new e.EffectFallbacks;o.FOG&&f.addFallback(1,"FOG"),e.MaterialHelper.HandleFallbacksForShadows(o,f,this.maxSimultaneousLights),o.NUM_BONE_INFLUENCERS>0&&f.addCPUSkinningFallback(0,t);var l=[e.VertexBuffer.PositionKind];o.NORMAL&&l.push(e.VertexBuffer.NormalKind),o.UV1&&l.push(e.VertexBuffer.UVKind),o.UV2&&l.push(e.VertexBuffer.UV2Kind),o.VERTEXCOLOR&&l.push(e.VertexBuffer.ColorKind),e.MaterialHelper.PrepareAttributesForBones(l,t,o,f),e.MaterialHelper.PrepareAttributesForInstances(l,o);var u=o.toString(),c=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vFogInfos","vFogColor","pointSize","vDiffuseInfos","mBones","vClipPlane","diffuseMatrix"],d=["diffuseSampler"],p=new Array;e.MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:o,maxSimultaneousLights:this.maxSimultaneousLights}),n.setEffect(a.getEngine().createEffect("cell",{attributes:l,uniformsNames:c,uniformBuffersNames:p,samplers:d,defines:u,fallbacks:f,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights-1}},s),o)}return!(!n.effect||!n.effect.isReady())&&(this._renderId=a.getRenderId(),this._wasPreviouslyReady=!0,!0)},n.prototype.bindForSubMesh=function(i,t,n){var r=this.getScene(),o=n._materialDefines;if(o){var a=n.effect;a&&(this._activeEffect=a,this.bindOnlyWorldMatrix(i),this._activeEffect.setMatrix("viewProjection",r.getTransformMatrix()),e.MaterialHelper.BindBonesParameters(t,this._activeEffect),this._mustRebind(r,a)&&(this._diffuseTexture&&e.StandardMaterial.DiffuseTextureEnabled&&(this._activeEffect.setTexture("diffuseSampler",this._diffuseTexture),this._activeEffect.setFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),this._activeEffect.setMatrix("diffuseMatrix",this._diffuseTexture.getTextureMatrix())),e.MaterialHelper.BindClipPlane(this._activeEffect,r),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),e.MaterialHelper.BindEyePosition(a,r)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.lightsEnabled&&!this.disableLighting&&e.MaterialHelper.BindLights(r,t,this._activeEffect,o,this._maxSimultaneousLights),r.fogEnabled&&t.applyFog&&r.fogMode!==e.Scene.FOGMODE_NONE&&this._activeEffect.setMatrix("view",r.getViewMatrix()),e.MaterialHelper.BindFogParameters(r,t,this._activeEffect),this._afterBind(t,this._activeEffect))}},n.prototype.getAnimatables=function(){var e=[];return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);return this._diffuseTexture&&e.push(this._diffuseTexture),e},n.prototype.hasTexture=function(e){return!!t.prototype.hasTexture.call(this,e)||this._diffuseTexture===e},n.prototype.dispose=function(e){this._diffuseTexture&&this._diffuseTexture.dispose(),t.prototype.dispose.call(this,e)},n.prototype.getClassName=function(){return"CellMaterial"},n.prototype.clone=function(i){var t=this;return e.SerializationHelper.Clone((function(){return new n(i,t.getScene())}),this)},n.prototype.serialize=function(){var i=e.SerializationHelper.Serialize(this);return i.customType="BABYLON.CellMaterial",i},n.Parse=function(i,t,r){return e.SerializationHelper.Parse((function(){return new n(i.name,t)}),i,t,r)},__decorate([e.serializeAsTexture("diffuseTexture")],n.prototype,"_diffuseTexture",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"diffuseTexture",void 0),__decorate([e.serializeAsColor3("diffuse")],n.prototype,"diffuseColor",void 0),__decorate([e.serialize("computeHighLevel")],n.prototype,"_computeHighLevel",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsTexturesDirty")],n.prototype,"computeHighLevel",void 0),__decorate([e.serialize("disableLighting")],n.prototype,"_disableLighting",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"disableLighting",void 0),__decorate([e.serialize("maxSimultaneousLights")],n.prototype,"_maxSimultaneousLights",void 0),__decorate([e.expandToProperty("_markAllSubMeshesAsLightsDirty")],n.prototype,"maxSimultaneousLights",void 0),n})(e.PushMaterial);e.CellMaterial=t})(BABYLON||(BABYLON={})),BABYLON.Effect.ShadersStore.cellVertexShader="precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\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<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\nvoid main(void) {\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\nvNormalW=normalize(vec3(finalWorld*vec4(normal,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 DIFFUSE\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#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n",BABYLON.Effect.ShadersStore.cellPixelShader="precision highp float;\n\nuniform vec3 vEyePosition;\nuniform vec4 vDiffuseColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n\nvec3 computeCustomDiffuseLighting(lightingInfo info,vec3 diffuseBase,float shadow)\n{\ndiffuseBase=info.diffuse*shadow;\n#ifdef CELLBASIC\nfloat level=1.0;\nif (info.ndl<0.5)\nlevel=0.5;\ndiffuseBase.rgb*vec3(level,level,level);\n#else\nfloat ToonThresholds[4];\nToonThresholds[0]=0.95;\nToonThresholds[1]=0.5;\nToonThresholds[2]=0.2;\nToonThresholds[3]=0.03;\nfloat ToonBrightnessLevels[5];\nToonBrightnessLevels[0]=1.0;\nToonBrightnessLevels[1]=0.8;\nToonBrightnessLevels[2]=0.6;\nToonBrightnessLevels[3]=0.35;\nToonBrightnessLevels[4]=0.2;\nif (info.ndl>ToonThresholds[0])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[0];\n}\nelse if (info.ndl>ToonThresholds[1])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[1];\n}\nelse if (info.ndl>ToonThresholds[2])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[2];\n}\nelse if (info.ndl>ToonThresholds[3])\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[3];\n}\nelse\n{\ndiffuseBase.rgb*=ToonBrightnessLevels[4];\n}\n#endif\nreturn max(diffuseBase,vec3(0.2));\n}\nvoid main(void)\n{\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#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#include<depthPrePass>\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nlightingInfo info;\nvec3 diffuseBase=vec3(0.,0.,0.);\nfloat shadow=1.;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif \n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor,0.0,1.0)*baseColor.rgb;;\n\nvec4 color=vec4(finalDiffuse,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}",(function(e,i){var t=i();e&&e.BABYLON||( true?module.exports=t:"function"==typeof define&&define.amd?define(["BJSMaterials"],i):"object"==typeof exports?exports.BJSMaterials=t:e.BABYLON=t)})(this,(function(){return BABYLON}));
  101778. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
  101779. /***/ }),
  101780. /* 31 */
  101781. /***/ (function(module, exports, __webpack_require__) {
  101782. "use strict";
  101783. Object.defineProperty(exports, "__esModule", { value: true });
  101784. var defaultViewer_1 = __webpack_require__(5);
  101785. var mappers_1 = __webpack_require__(2);
  101786. function InitTags(selector) {
  101787. if (selector === void 0) { selector = 'babylon'; }
  101788. var elements = document.querySelectorAll(selector);
  101789. for (var i = 0; i < elements.length; ++i) {
  101790. var element = elements.item(i);
  101791. var configMapper = mappers_1.mapperManager.getMapper('dom');
  101792. var config = configMapper.map(element);
  101793. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  101794. }
  101795. }
  101796. exports.InitTags = InitTags;
  101797. /***/ }),
  101798. /* 32 */
  101799. /***/ (function(module, exports, __webpack_require__) {
  101800. /* WEBPACK VAR INJECTION */(function(process, global) {var require;/*!
  101801. * @overview es6-promise - a tiny implementation of Promises/A+.
  101802. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  101803. * @license Licensed under MIT license
  101804. * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
  101805. * @version 4.1.1
  101806. */
  101807. (function (global, factory) {
  101808. true ? module.exports = factory() :
  101809. typeof define === 'function' && define.amd ? define(factory) :
  101810. (global.ES6Promise = factory());
  101811. }(this, (function () { 'use strict';
  101812. function objectOrFunction(x) {
  101813. var type = typeof x;
  101814. return x !== null && (type === 'object' || type === 'function');
  101815. }
  101816. function isFunction(x) {
  101817. return typeof x === 'function';
  101818. }
  101819. var _isArray = undefined;
  101820. if (Array.isArray) {
  101821. _isArray = Array.isArray;
  101822. } else {
  101823. _isArray = function (x) {
  101824. return Object.prototype.toString.call(x) === '[object Array]';
  101825. };
  101826. }
  101827. var isArray = _isArray;
  101828. var len = 0;
  101829. var vertxNext = undefined;
  101830. var customSchedulerFn = undefined;
  101831. var asap = function asap(callback, arg) {
  101832. queue[len] = callback;
  101833. queue[len + 1] = arg;
  101834. len += 2;
  101835. if (len === 2) {
  101836. // If len is 2, that means that we need to schedule an async flush.
  101837. // If additional callbacks are queued before the queue is flushed, they
  101838. // will be processed by this flush that we are scheduling.
  101839. if (customSchedulerFn) {
  101840. customSchedulerFn(flush);
  101841. } else {
  101842. scheduleFlush();
  101843. }
  101844. }
  101845. };
  101846. function setScheduler(scheduleFn) {
  101847. customSchedulerFn = scheduleFn;
  101848. }
  101849. function setAsap(asapFn) {
  101850. asap = asapFn;
  101851. }
  101852. var browserWindow = typeof window !== 'undefined' ? window : undefined;
  101853. var browserGlobal = browserWindow || {};
  101854. var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  101855. var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
  101856. // test for web worker but not in IE10
  101857. var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
  101858. // node
  101859. function useNextTick() {
  101860. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  101861. // see https://github.com/cujojs/when/issues/410 for details
  101862. return function () {
  101863. return process.nextTick(flush);
  101864. };
  101865. }
  101866. // vertx
  101867. function useVertxTimer() {
  101868. if (typeof vertxNext !== 'undefined') {
  101869. return function () {
  101870. vertxNext(flush);
  101871. };
  101872. }
  101873. return useSetTimeout();
  101874. }
  101875. function useMutationObserver() {
  101876. var iterations = 0;
  101877. var observer = new BrowserMutationObserver(flush);
  101878. var node = document.createTextNode('');
  101879. observer.observe(node, { characterData: true });
  101880. return function () {
  101881. node.data = iterations = ++iterations % 2;
  101882. };
  101883. }
  101884. // web worker
  101885. function useMessageChannel() {
  101886. var channel = new MessageChannel();
  101887. channel.port1.onmessage = flush;
  101888. return function () {
  101889. return channel.port2.postMessage(0);
  101890. };
  101891. }
  101892. function useSetTimeout() {
  101893. // Store setTimeout reference so es6-promise will be unaffected by
  101894. // other code modifying setTimeout (like sinon.useFakeTimers())
  101895. var globalSetTimeout = setTimeout;
  101896. return function () {
  101897. return globalSetTimeout(flush, 1);
  101898. };
  101899. }
  101900. var queue = new Array(1000);
  101901. function flush() {
  101902. for (var i = 0; i < len; i += 2) {
  101903. var callback = queue[i];
  101904. var arg = queue[i + 1];
  101905. callback(arg);
  101906. queue[i] = undefined;
  101907. queue[i + 1] = undefined;
  101908. }
  101909. len = 0;
  101910. }
  101911. function attemptVertx() {
  101912. try {
  101913. var r = require;
  101914. var vertx = __webpack_require__(34);
  101915. vertxNext = vertx.runOnLoop || vertx.runOnContext;
  101916. return useVertxTimer();
  101917. } catch (e) {
  101918. return useSetTimeout();
  101919. }
  101920. }
  101921. var scheduleFlush = undefined;
  101922. // Decide what async method to use to triggering processing of queued callbacks:
  101923. if (isNode) {
  101924. scheduleFlush = useNextTick();
  101925. } else if (BrowserMutationObserver) {
  101926. scheduleFlush = useMutationObserver();
  101927. } else if (isWorker) {
  101928. scheduleFlush = useMessageChannel();
  101929. } else if (browserWindow === undefined && "function" === 'function') {
  101930. scheduleFlush = attemptVertx();
  101931. } else {
  101932. scheduleFlush = useSetTimeout();
  101933. }
  101934. function then(onFulfillment, onRejection) {
  101935. var _arguments = arguments;
  101936. var parent = this;
  101937. var child = new this.constructor(noop);
  101938. if (child[PROMISE_ID] === undefined) {
  101939. makePromise(child);
  101940. }
  101941. var _state = parent._state;
  101942. if (_state) {
  101943. (function () {
  101944. var callback = _arguments[_state - 1];
  101945. asap(function () {
  101946. return invokeCallback(_state, child, callback, parent._result);
  101947. });
  101948. })();
  101949. } else {
  101950. subscribe(parent, child, onFulfillment, onRejection);
  101951. }
  101952. return child;
  101953. }
  101954. /**
  101955. `Promise.resolve` returns a promise that will become resolved with the
  101956. passed `value`. It is shorthand for the following:
  101957. ```javascript
  101958. let promise = new Promise(function(resolve, reject){
  101959. resolve(1);
  101960. });
  101961. promise.then(function(value){
  101962. // value === 1
  101963. });
  101964. ```
  101965. Instead of writing the above, your code now simply becomes the following:
  101966. ```javascript
  101967. let promise = Promise.resolve(1);
  101968. promise.then(function(value){
  101969. // value === 1
  101970. });
  101971. ```
  101972. @method resolve
  101973. @static
  101974. @param {Any} value value that the returned promise will be resolved with
  101975. Useful for tooling.
  101976. @return {Promise} a promise that will become fulfilled with the given
  101977. `value`
  101978. */
  101979. function resolve$1(object) {
  101980. /*jshint validthis:true */
  101981. var Constructor = this;
  101982. if (object && typeof object === 'object' && object.constructor === Constructor) {
  101983. return object;
  101984. }
  101985. var promise = new Constructor(noop);
  101986. resolve(promise, object);
  101987. return promise;
  101988. }
  101989. var PROMISE_ID = Math.random().toString(36).substring(16);
  101990. function noop() {}
  101991. var PENDING = void 0;
  101992. var FULFILLED = 1;
  101993. var REJECTED = 2;
  101994. var GET_THEN_ERROR = new ErrorObject();
  101995. function selfFulfillment() {
  101996. return new TypeError("You cannot resolve a promise with itself");
  101997. }
  101998. function cannotReturnOwn() {
  101999. return new TypeError('A promises callback cannot return that same promise.');
  102000. }
  102001. function getThen(promise) {
  102002. try {
  102003. return promise.then;
  102004. } catch (error) {
  102005. GET_THEN_ERROR.error = error;
  102006. return GET_THEN_ERROR;
  102007. }
  102008. }
  102009. function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
  102010. try {
  102011. then$$1.call(value, fulfillmentHandler, rejectionHandler);
  102012. } catch (e) {
  102013. return e;
  102014. }
  102015. }
  102016. function handleForeignThenable(promise, thenable, then$$1) {
  102017. asap(function (promise) {
  102018. var sealed = false;
  102019. var error = tryThen(then$$1, thenable, function (value) {
  102020. if (sealed) {
  102021. return;
  102022. }
  102023. sealed = true;
  102024. if (thenable !== value) {
  102025. resolve(promise, value);
  102026. } else {
  102027. fulfill(promise, value);
  102028. }
  102029. }, function (reason) {
  102030. if (sealed) {
  102031. return;
  102032. }
  102033. sealed = true;
  102034. reject(promise, reason);
  102035. }, 'Settle: ' + (promise._label || ' unknown promise'));
  102036. if (!sealed && error) {
  102037. sealed = true;
  102038. reject(promise, error);
  102039. }
  102040. }, promise);
  102041. }
  102042. function handleOwnThenable(promise, thenable) {
  102043. if (thenable._state === FULFILLED) {
  102044. fulfill(promise, thenable._result);
  102045. } else if (thenable._state === REJECTED) {
  102046. reject(promise, thenable._result);
  102047. } else {
  102048. subscribe(thenable, undefined, function (value) {
  102049. return resolve(promise, value);
  102050. }, function (reason) {
  102051. return reject(promise, reason);
  102052. });
  102053. }
  102054. }
  102055. function handleMaybeThenable(promise, maybeThenable, then$$1) {
  102056. if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
  102057. handleOwnThenable(promise, maybeThenable);
  102058. } else {
  102059. if (then$$1 === GET_THEN_ERROR) {
  102060. reject(promise, GET_THEN_ERROR.error);
  102061. GET_THEN_ERROR.error = null;
  102062. } else if (then$$1 === undefined) {
  102063. fulfill(promise, maybeThenable);
  102064. } else if (isFunction(then$$1)) {
  102065. handleForeignThenable(promise, maybeThenable, then$$1);
  102066. } else {
  102067. fulfill(promise, maybeThenable);
  102068. }
  102069. }
  102070. }
  102071. function resolve(promise, value) {
  102072. if (promise === value) {
  102073. reject(promise, selfFulfillment());
  102074. } else if (objectOrFunction(value)) {
  102075. handleMaybeThenable(promise, value, getThen(value));
  102076. } else {
  102077. fulfill(promise, value);
  102078. }
  102079. }
  102080. function publishRejection(promise) {
  102081. if (promise._onerror) {
  102082. promise._onerror(promise._result);
  102083. }
  102084. publish(promise);
  102085. }
  102086. function fulfill(promise, value) {
  102087. if (promise._state !== PENDING) {
  102088. return;
  102089. }
  102090. promise._result = value;
  102091. promise._state = FULFILLED;
  102092. if (promise._subscribers.length !== 0) {
  102093. asap(publish, promise);
  102094. }
  102095. }
  102096. function reject(promise, reason) {
  102097. if (promise._state !== PENDING) {
  102098. return;
  102099. }
  102100. promise._state = REJECTED;
  102101. promise._result = reason;
  102102. asap(publishRejection, promise);
  102103. }
  102104. function subscribe(parent, child, onFulfillment, onRejection) {
  102105. var _subscribers = parent._subscribers;
  102106. var length = _subscribers.length;
  102107. parent._onerror = null;
  102108. _subscribers[length] = child;
  102109. _subscribers[length + FULFILLED] = onFulfillment;
  102110. _subscribers[length + REJECTED] = onRejection;
  102111. if (length === 0 && parent._state) {
  102112. asap(publish, parent);
  102113. }
  102114. }
  102115. function publish(promise) {
  102116. var subscribers = promise._subscribers;
  102117. var settled = promise._state;
  102118. if (subscribers.length === 0) {
  102119. return;
  102120. }
  102121. var child = undefined,
  102122. callback = undefined,
  102123. detail = promise._result;
  102124. for (var i = 0; i < subscribers.length; i += 3) {
  102125. child = subscribers[i];
  102126. callback = subscribers[i + settled];
  102127. if (child) {
  102128. invokeCallback(settled, child, callback, detail);
  102129. } else {
  102130. callback(detail);
  102131. }
  102132. }
  102133. promise._subscribers.length = 0;
  102134. }
  102135. function ErrorObject() {
  102136. this.error = null;
  102137. }
  102138. var TRY_CATCH_ERROR = new ErrorObject();
  102139. function tryCatch(callback, detail) {
  102140. try {
  102141. return callback(detail);
  102142. } catch (e) {
  102143. TRY_CATCH_ERROR.error = e;
  102144. return TRY_CATCH_ERROR;
  102145. }
  102146. }
  102147. function invokeCallback(settled, promise, callback, detail) {
  102148. var hasCallback = isFunction(callback),
  102149. value = undefined,
  102150. error = undefined,
  102151. succeeded = undefined,
  102152. failed = undefined;
  102153. if (hasCallback) {
  102154. value = tryCatch(callback, detail);
  102155. if (value === TRY_CATCH_ERROR) {
  102156. failed = true;
  102157. error = value.error;
  102158. value.error = null;
  102159. } else {
  102160. succeeded = true;
  102161. }
  102162. if (promise === value) {
  102163. reject(promise, cannotReturnOwn());
  102164. return;
  102165. }
  102166. } else {
  102167. value = detail;
  102168. succeeded = true;
  102169. }
  102170. if (promise._state !== PENDING) {
  102171. // noop
  102172. } else if (hasCallback && succeeded) {
  102173. resolve(promise, value);
  102174. } else if (failed) {
  102175. reject(promise, error);
  102176. } else if (settled === FULFILLED) {
  102177. fulfill(promise, value);
  102178. } else if (settled === REJECTED) {
  102179. reject(promise, value);
  102180. }
  102181. }
  102182. function initializePromise(promise, resolver) {
  102183. try {
  102184. resolver(function resolvePromise(value) {
  102185. resolve(promise, value);
  102186. }, function rejectPromise(reason) {
  102187. reject(promise, reason);
  102188. });
  102189. } catch (e) {
  102190. reject(promise, e);
  102191. }
  102192. }
  102193. var id = 0;
  102194. function nextId() {
  102195. return id++;
  102196. }
  102197. function makePromise(promise) {
  102198. promise[PROMISE_ID] = id++;
  102199. promise._state = undefined;
  102200. promise._result = undefined;
  102201. promise._subscribers = [];
  102202. }
  102203. function Enumerator$1(Constructor, input) {
  102204. this._instanceConstructor = Constructor;
  102205. this.promise = new Constructor(noop);
  102206. if (!this.promise[PROMISE_ID]) {
  102207. makePromise(this.promise);
  102208. }
  102209. if (isArray(input)) {
  102210. this.length = input.length;
  102211. this._remaining = input.length;
  102212. this._result = new Array(this.length);
  102213. if (this.length === 0) {
  102214. fulfill(this.promise, this._result);
  102215. } else {
  102216. this.length = this.length || 0;
  102217. this._enumerate(input);
  102218. if (this._remaining === 0) {
  102219. fulfill(this.promise, this._result);
  102220. }
  102221. }
  102222. } else {
  102223. reject(this.promise, validationError());
  102224. }
  102225. }
  102226. function validationError() {
  102227. return new Error('Array Methods must be provided an Array');
  102228. }
  102229. Enumerator$1.prototype._enumerate = function (input) {
  102230. for (var i = 0; this._state === PENDING && i < input.length; i++) {
  102231. this._eachEntry(input[i], i);
  102232. }
  102233. };
  102234. Enumerator$1.prototype._eachEntry = function (entry, i) {
  102235. var c = this._instanceConstructor;
  102236. var resolve$$1 = c.resolve;
  102237. if (resolve$$1 === resolve$1) {
  102238. var _then = getThen(entry);
  102239. if (_then === then && entry._state !== PENDING) {
  102240. this._settledAt(entry._state, i, entry._result);
  102241. } else if (typeof _then !== 'function') {
  102242. this._remaining--;
  102243. this._result[i] = entry;
  102244. } else if (c === Promise$2) {
  102245. var promise = new c(noop);
  102246. handleMaybeThenable(promise, entry, _then);
  102247. this._willSettleAt(promise, i);
  102248. } else {
  102249. this._willSettleAt(new c(function (resolve$$1) {
  102250. return resolve$$1(entry);
  102251. }), i);
  102252. }
  102253. } else {
  102254. this._willSettleAt(resolve$$1(entry), i);
  102255. }
  102256. };
  102257. Enumerator$1.prototype._settledAt = function (state, i, value) {
  102258. var promise = this.promise;
  102259. if (promise._state === PENDING) {
  102260. this._remaining--;
  102261. if (state === REJECTED) {
  102262. reject(promise, value);
  102263. } else {
  102264. this._result[i] = value;
  102265. }
  102266. }
  102267. if (this._remaining === 0) {
  102268. fulfill(promise, this._result);
  102269. }
  102270. };
  102271. Enumerator$1.prototype._willSettleAt = function (promise, i) {
  102272. var enumerator = this;
  102273. subscribe(promise, undefined, function (value) {
  102274. return enumerator._settledAt(FULFILLED, i, value);
  102275. }, function (reason) {
  102276. return enumerator._settledAt(REJECTED, i, reason);
  102277. });
  102278. };
  102279. /**
  102280. `Promise.all` accepts an array of promises, and returns a new promise which
  102281. is fulfilled with an array of fulfillment values for the passed promises, or
  102282. rejected with the reason of the first passed promise to be rejected. It casts all
  102283. elements of the passed iterable to promises as it runs this algorithm.
  102284. Example:
  102285. ```javascript
  102286. let promise1 = resolve(1);
  102287. let promise2 = resolve(2);
  102288. let promise3 = resolve(3);
  102289. let promises = [ promise1, promise2, promise3 ];
  102290. Promise.all(promises).then(function(array){
  102291. // The array here would be [ 1, 2, 3 ];
  102292. });
  102293. ```
  102294. If any of the `promises` given to `all` are rejected, the first promise
  102295. that is rejected will be given as an argument to the returned promises's
  102296. rejection handler. For example:
  102297. Example:
  102298. ```javascript
  102299. let promise1 = resolve(1);
  102300. let promise2 = reject(new Error("2"));
  102301. let promise3 = reject(new Error("3"));
  102302. let promises = [ promise1, promise2, promise3 ];
  102303. Promise.all(promises).then(function(array){
  102304. // Code here never runs because there are rejected promises!
  102305. }, function(error) {
  102306. // error.message === "2"
  102307. });
  102308. ```
  102309. @method all
  102310. @static
  102311. @param {Array} entries array of promises
  102312. @param {String} label optional string for labeling the promise.
  102313. Useful for tooling.
  102314. @return {Promise} promise that is fulfilled when all `promises` have been
  102315. fulfilled, or rejected if any of them become rejected.
  102316. @static
  102317. */
  102318. function all$1(entries) {
  102319. return new Enumerator$1(this, entries).promise;
  102320. }
  102321. /**
  102322. `Promise.race` returns a new promise which is settled in the same way as the
  102323. first passed promise to settle.
  102324. Example:
  102325. ```javascript
  102326. let promise1 = new Promise(function(resolve, reject){
  102327. setTimeout(function(){
  102328. resolve('promise 1');
  102329. }, 200);
  102330. });
  102331. let promise2 = new Promise(function(resolve, reject){
  102332. setTimeout(function(){
  102333. resolve('promise 2');
  102334. }, 100);
  102335. });
  102336. Promise.race([promise1, promise2]).then(function(result){
  102337. // result === 'promise 2' because it was resolved before promise1
  102338. // was resolved.
  102339. });
  102340. ```
  102341. `Promise.race` is deterministic in that only the state of the first
  102342. settled promise matters. For example, even if other promises given to the
  102343. `promises` array argument are resolved, but the first settled promise has
  102344. become rejected before the other promises became fulfilled, the returned
  102345. promise will become rejected:
  102346. ```javascript
  102347. let promise1 = new Promise(function(resolve, reject){
  102348. setTimeout(function(){
  102349. resolve('promise 1');
  102350. }, 200);
  102351. });
  102352. let promise2 = new Promise(function(resolve, reject){
  102353. setTimeout(function(){
  102354. reject(new Error('promise 2'));
  102355. }, 100);
  102356. });
  102357. Promise.race([promise1, promise2]).then(function(result){
  102358. // Code here never runs
  102359. }, function(reason){
  102360. // reason.message === 'promise 2' because promise 2 became rejected before
  102361. // promise 1 became fulfilled
  102362. });
  102363. ```
  102364. An example real-world use case is implementing timeouts:
  102365. ```javascript
  102366. Promise.race([ajax('foo.json'), timeout(5000)])
  102367. ```
  102368. @method race
  102369. @static
  102370. @param {Array} promises array of promises to observe
  102371. Useful for tooling.
  102372. @return {Promise} a promise which settles in the same way as the first passed
  102373. promise to settle.
  102374. */
  102375. function race$1(entries) {
  102376. /*jshint validthis:true */
  102377. var Constructor = this;
  102378. if (!isArray(entries)) {
  102379. return new Constructor(function (_, reject) {
  102380. return reject(new TypeError('You must pass an array to race.'));
  102381. });
  102382. } else {
  102383. return new Constructor(function (resolve, reject) {
  102384. var length = entries.length;
  102385. for (var i = 0; i < length; i++) {
  102386. Constructor.resolve(entries[i]).then(resolve, reject);
  102387. }
  102388. });
  102389. }
  102390. }
  102391. /**
  102392. `Promise.reject` returns a promise rejected with the passed `reason`.
  102393. It is shorthand for the following:
  102394. ```javascript
  102395. let promise = new Promise(function(resolve, reject){
  102396. reject(new Error('WHOOPS'));
  102397. });
  102398. promise.then(function(value){
  102399. // Code here doesn't run because the promise is rejected!
  102400. }, function(reason){
  102401. // reason.message === 'WHOOPS'
  102402. });
  102403. ```
  102404. Instead of writing the above, your code now simply becomes the following:
  102405. ```javascript
  102406. let promise = Promise.reject(new Error('WHOOPS'));
  102407. promise.then(function(value){
  102408. // Code here doesn't run because the promise is rejected!
  102409. }, function(reason){
  102410. // reason.message === 'WHOOPS'
  102411. });
  102412. ```
  102413. @method reject
  102414. @static
  102415. @param {Any} reason value that the returned promise will be rejected with.
  102416. Useful for tooling.
  102417. @return {Promise} a promise rejected with the given `reason`.
  102418. */
  102419. function reject$1(reason) {
  102420. /*jshint validthis:true */
  102421. var Constructor = this;
  102422. var promise = new Constructor(noop);
  102423. reject(promise, reason);
  102424. return promise;
  102425. }
  102426. function needsResolver() {
  102427. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  102428. }
  102429. function needsNew() {
  102430. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  102431. }
  102432. /**
  102433. Promise objects represent the eventual result of an asynchronous operation. The
  102434. primary way of interacting with a promise is through its `then` method, which
  102435. registers callbacks to receive either a promise's eventual value or the reason
  102436. why the promise cannot be fulfilled.
  102437. Terminology
  102438. -----------
  102439. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  102440. - `thenable` is an object or function that defines a `then` method.
  102441. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  102442. - `exception` is a value that is thrown using the throw statement.
  102443. - `reason` is a value that indicates why a promise was rejected.
  102444. - `settled` the final resting state of a promise, fulfilled or rejected.
  102445. A promise can be in one of three states: pending, fulfilled, or rejected.
  102446. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  102447. state. Promises that are rejected have a rejection reason and are in the
  102448. rejected state. A fulfillment value is never a thenable.
  102449. Promises can also be said to *resolve* a value. If this value is also a
  102450. promise, then the original promise's settled state will match the value's
  102451. settled state. So a promise that *resolves* a promise that rejects will
  102452. itself reject, and a promise that *resolves* a promise that fulfills will
  102453. itself fulfill.
  102454. Basic Usage:
  102455. ------------
  102456. ```js
  102457. let promise = new Promise(function(resolve, reject) {
  102458. // on success
  102459. resolve(value);
  102460. // on failure
  102461. reject(reason);
  102462. });
  102463. promise.then(function(value) {
  102464. // on fulfillment
  102465. }, function(reason) {
  102466. // on rejection
  102467. });
  102468. ```
  102469. Advanced Usage:
  102470. ---------------
  102471. Promises shine when abstracting away asynchronous interactions such as
  102472. `XMLHttpRequest`s.
  102473. ```js
  102474. function getJSON(url) {
  102475. return new Promise(function(resolve, reject){
  102476. let xhr = new XMLHttpRequest();
  102477. xhr.open('GET', url);
  102478. xhr.onreadystatechange = handler;
  102479. xhr.responseType = 'json';
  102480. xhr.setRequestHeader('Accept', 'application/json');
  102481. xhr.send();
  102482. function handler() {
  102483. if (this.readyState === this.DONE) {
  102484. if (this.status === 200) {
  102485. resolve(this.response);
  102486. } else {
  102487. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  102488. }
  102489. }
  102490. };
  102491. });
  102492. }
  102493. getJSON('/posts.json').then(function(json) {
  102494. // on fulfillment
  102495. }, function(reason) {
  102496. // on rejection
  102497. });
  102498. ```
  102499. Unlike callbacks, promises are great composable primitives.
  102500. ```js
  102501. Promise.all([
  102502. getJSON('/posts'),
  102503. getJSON('/comments')
  102504. ]).then(function(values){
  102505. values[0] // => postsJSON
  102506. values[1] // => commentsJSON
  102507. return values;
  102508. });
  102509. ```
  102510. @class Promise
  102511. @param {function} resolver
  102512. Useful for tooling.
  102513. @constructor
  102514. */
  102515. function Promise$2(resolver) {
  102516. this[PROMISE_ID] = nextId();
  102517. this._result = this._state = undefined;
  102518. this._subscribers = [];
  102519. if (noop !== resolver) {
  102520. typeof resolver !== 'function' && needsResolver();
  102521. this instanceof Promise$2 ? initializePromise(this, resolver) : needsNew();
  102522. }
  102523. }
  102524. Promise$2.all = all$1;
  102525. Promise$2.race = race$1;
  102526. Promise$2.resolve = resolve$1;
  102527. Promise$2.reject = reject$1;
  102528. Promise$2._setScheduler = setScheduler;
  102529. Promise$2._setAsap = setAsap;
  102530. Promise$2._asap = asap;
  102531. Promise$2.prototype = {
  102532. constructor: Promise$2,
  102533. /**
  102534. The primary way of interacting with a promise is through its `then` method,
  102535. which registers callbacks to receive either a promise's eventual value or the
  102536. reason why the promise cannot be fulfilled.
  102537. ```js
  102538. findUser().then(function(user){
  102539. // user is available
  102540. }, function(reason){
  102541. // user is unavailable, and you are given the reason why
  102542. });
  102543. ```
  102544. Chaining
  102545. --------
  102546. The return value of `then` is itself a promise. This second, 'downstream'
  102547. promise is resolved with the return value of the first promise's fulfillment
  102548. or rejection handler, or rejected if the handler throws an exception.
  102549. ```js
  102550. findUser().then(function (user) {
  102551. return user.name;
  102552. }, function (reason) {
  102553. return 'default name';
  102554. }).then(function (userName) {
  102555. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  102556. // will be `'default name'`
  102557. });
  102558. findUser().then(function (user) {
  102559. throw new Error('Found user, but still unhappy');
  102560. }, function (reason) {
  102561. throw new Error('`findUser` rejected and we're unhappy');
  102562. }).then(function (value) {
  102563. // never reached
  102564. }, function (reason) {
  102565. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  102566. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  102567. });
  102568. ```
  102569. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  102570. ```js
  102571. findUser().then(function (user) {
  102572. throw new PedagogicalException('Upstream error');
  102573. }).then(function (value) {
  102574. // never reached
  102575. }).then(function (value) {
  102576. // never reached
  102577. }, function (reason) {
  102578. // The `PedgagocialException` is propagated all the way down to here
  102579. });
  102580. ```
  102581. Assimilation
  102582. ------------
  102583. Sometimes the value you want to propagate to a downstream promise can only be
  102584. retrieved asynchronously. This can be achieved by returning a promise in the
  102585. fulfillment or rejection handler. The downstream promise will then be pending
  102586. until the returned promise is settled. This is called *assimilation*.
  102587. ```js
  102588. findUser().then(function (user) {
  102589. return findCommentsByAuthor(user);
  102590. }).then(function (comments) {
  102591. // The user's comments are now available
  102592. });
  102593. ```
  102594. If the assimliated promise rejects, then the downstream promise will also reject.
  102595. ```js
  102596. findUser().then(function (user) {
  102597. return findCommentsByAuthor(user);
  102598. }).then(function (comments) {
  102599. // If `findCommentsByAuthor` fulfills, we'll have the value here
  102600. }, function (reason) {
  102601. // If `findCommentsByAuthor` rejects, we'll have the reason here
  102602. });
  102603. ```
  102604. Simple Example
  102605. --------------
  102606. Synchronous Example
  102607. ```javascript
  102608. let result;
  102609. try {
  102610. result = findResult();
  102611. // success
  102612. } catch(reason) {
  102613. // failure
  102614. }
  102615. ```
  102616. Errback Example
  102617. ```js
  102618. findResult(function(result, err){
  102619. if (err) {
  102620. // failure
  102621. } else {
  102622. // success
  102623. }
  102624. });
  102625. ```
  102626. Promise Example;
  102627. ```javascript
  102628. findResult().then(function(result){
  102629. // success
  102630. }, function(reason){
  102631. // failure
  102632. });
  102633. ```
  102634. Advanced Example
  102635. --------------
  102636. Synchronous Example
  102637. ```javascript
  102638. let author, books;
  102639. try {
  102640. author = findAuthor();
  102641. books = findBooksByAuthor(author);
  102642. // success
  102643. } catch(reason) {
  102644. // failure
  102645. }
  102646. ```
  102647. Errback Example
  102648. ```js
  102649. function foundBooks(books) {
  102650. }
  102651. function failure(reason) {
  102652. }
  102653. findAuthor(function(author, err){
  102654. if (err) {
  102655. failure(err);
  102656. // failure
  102657. } else {
  102658. try {
  102659. findBoooksByAuthor(author, function(books, err) {
  102660. if (err) {
  102661. failure(err);
  102662. } else {
  102663. try {
  102664. foundBooks(books);
  102665. } catch(reason) {
  102666. failure(reason);
  102667. }
  102668. }
  102669. });
  102670. } catch(error) {
  102671. failure(err);
  102672. }
  102673. // success
  102674. }
  102675. });
  102676. ```
  102677. Promise Example;
  102678. ```javascript
  102679. findAuthor().
  102680. then(findBooksByAuthor).
  102681. then(function(books){
  102682. // found books
  102683. }).catch(function(reason){
  102684. // something went wrong
  102685. });
  102686. ```
  102687. @method then
  102688. @param {Function} onFulfilled
  102689. @param {Function} onRejected
  102690. Useful for tooling.
  102691. @return {Promise}
  102692. */
  102693. then: then,
  102694. /**
  102695. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  102696. as the catch block of a try/catch statement.
  102697. ```js
  102698. function findAuthor(){
  102699. throw new Error('couldn't find that author');
  102700. }
  102701. // synchronous
  102702. try {
  102703. findAuthor();
  102704. } catch(reason) {
  102705. // something went wrong
  102706. }
  102707. // async with promises
  102708. findAuthor().catch(function(reason){
  102709. // something went wrong
  102710. });
  102711. ```
  102712. @method catch
  102713. @param {Function} onRejection
  102714. Useful for tooling.
  102715. @return {Promise}
  102716. */
  102717. 'catch': function _catch(onRejection) {
  102718. return this.then(null, onRejection);
  102719. }
  102720. };
  102721. /*global self*/
  102722. function polyfill$1() {
  102723. var local = undefined;
  102724. if (typeof global !== 'undefined') {
  102725. local = global;
  102726. } else if (typeof self !== 'undefined') {
  102727. local = self;
  102728. } else {
  102729. try {
  102730. local = Function('return this')();
  102731. } catch (e) {
  102732. throw new Error('polyfill failed because global object is unavailable in this environment');
  102733. }
  102734. }
  102735. var P = local.Promise;
  102736. if (P) {
  102737. var promiseToString = null;
  102738. try {
  102739. promiseToString = Object.prototype.toString.call(P.resolve());
  102740. } catch (e) {
  102741. // silently ignored
  102742. }
  102743. if (promiseToString === '[object Promise]' && !P.cast) {
  102744. return;
  102745. }
  102746. }
  102747. local.Promise = Promise$2;
  102748. }
  102749. // Strange compat..
  102750. Promise$2.polyfill = polyfill$1;
  102751. Promise$2.Promise = Promise$2;
  102752. return Promise$2;
  102753. })));
  102754. //# sourceMappingURL=es6-promise.map
  102755. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33), __webpack_require__(1)))
  102756. /***/ }),
  102757. /* 33 */
  102758. /***/ (function(module, exports) {
  102759. // shim for using process in browser
  102760. var process = module.exports = {};
  102761. // cached from whatever global is present so that test runners that stub it
  102762. // don't break things. But we need to wrap it in a try catch in case it is
  102763. // wrapped in strict mode code which doesn't define any globals. It's inside a
  102764. // function because try/catches deoptimize in certain engines.
  102765. var cachedSetTimeout;
  102766. var cachedClearTimeout;
  102767. function defaultSetTimout() {
  102768. throw new Error('setTimeout has not been defined');
  102769. }
  102770. function defaultClearTimeout () {
  102771. throw new Error('clearTimeout has not been defined');
  102772. }
  102773. (function () {
  102774. try {
  102775. if (typeof setTimeout === 'function') {
  102776. cachedSetTimeout = setTimeout;
  102777. } else {
  102778. cachedSetTimeout = defaultSetTimout;
  102779. }
  102780. } catch (e) {
  102781. cachedSetTimeout = defaultSetTimout;
  102782. }
  102783. try {
  102784. if (typeof clearTimeout === 'function') {
  102785. cachedClearTimeout = clearTimeout;
  102786. } else {
  102787. cachedClearTimeout = defaultClearTimeout;
  102788. }
  102789. } catch (e) {
  102790. cachedClearTimeout = defaultClearTimeout;
  102791. }
  102792. } ())
  102793. function runTimeout(fun) {
  102794. if (cachedSetTimeout === setTimeout) {
  102795. //normal enviroments in sane situations
  102796. return setTimeout(fun, 0);
  102797. }
  102798. // if setTimeout wasn't available but was latter defined
  102799. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  102800. cachedSetTimeout = setTimeout;
  102801. return setTimeout(fun, 0);
  102802. }
  102803. try {
  102804. // when when somebody has screwed with setTimeout but no I.E. maddness
  102805. return cachedSetTimeout(fun, 0);
  102806. } catch(e){
  102807. try {
  102808. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  102809. return cachedSetTimeout.call(null, fun, 0);
  102810. } catch(e){
  102811. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  102812. return cachedSetTimeout.call(this, fun, 0);
  102813. }
  102814. }
  102815. }
  102816. function runClearTimeout(marker) {
  102817. if (cachedClearTimeout === clearTimeout) {
  102818. //normal enviroments in sane situations
  102819. return clearTimeout(marker);
  102820. }
  102821. // if clearTimeout wasn't available but was latter defined
  102822. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  102823. cachedClearTimeout = clearTimeout;
  102824. return clearTimeout(marker);
  102825. }
  102826. try {
  102827. // when when somebody has screwed with setTimeout but no I.E. maddness
  102828. return cachedClearTimeout(marker);
  102829. } catch (e){
  102830. try {
  102831. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  102832. return cachedClearTimeout.call(null, marker);
  102833. } catch (e){
  102834. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  102835. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  102836. return cachedClearTimeout.call(this, marker);
  102837. }
  102838. }
  102839. }
  102840. var queue = [];
  102841. var draining = false;
  102842. var currentQueue;
  102843. var queueIndex = -1;
  102844. function cleanUpNextTick() {
  102845. if (!draining || !currentQueue) {
  102846. return;
  102847. }
  102848. draining = false;
  102849. if (currentQueue.length) {
  102850. queue = currentQueue.concat(queue);
  102851. } else {
  102852. queueIndex = -1;
  102853. }
  102854. if (queue.length) {
  102855. drainQueue();
  102856. }
  102857. }
  102858. function drainQueue() {
  102859. if (draining) {
  102860. return;
  102861. }
  102862. var timeout = runTimeout(cleanUpNextTick);
  102863. draining = true;
  102864. var len = queue.length;
  102865. while(len) {
  102866. currentQueue = queue;
  102867. queue = [];
  102868. while (++queueIndex < len) {
  102869. if (currentQueue) {
  102870. currentQueue[queueIndex].run();
  102871. }
  102872. }
  102873. queueIndex = -1;
  102874. len = queue.length;
  102875. }
  102876. currentQueue = null;
  102877. draining = false;
  102878. runClearTimeout(timeout);
  102879. }
  102880. process.nextTick = function (fun) {
  102881. var args = new Array(arguments.length - 1);
  102882. if (arguments.length > 1) {
  102883. for (var i = 1; i < arguments.length; i++) {
  102884. args[i - 1] = arguments[i];
  102885. }
  102886. }
  102887. queue.push(new Item(fun, args));
  102888. if (queue.length === 1 && !draining) {
  102889. runTimeout(drainQueue);
  102890. }
  102891. };
  102892. // v8 likes predictible objects
  102893. function Item(fun, array) {
  102894. this.fun = fun;
  102895. this.array = array;
  102896. }
  102897. Item.prototype.run = function () {
  102898. this.fun.apply(null, this.array);
  102899. };
  102900. process.title = 'browser';
  102901. process.browser = true;
  102902. process.env = {};
  102903. process.argv = [];
  102904. process.version = ''; // empty string to avoid regexp issues
  102905. process.versions = {};
  102906. function noop() {}
  102907. process.on = noop;
  102908. process.addListener = noop;
  102909. process.once = noop;
  102910. process.off = noop;
  102911. process.removeListener = noop;
  102912. process.removeAllListeners = noop;
  102913. process.emit = noop;
  102914. process.prependListener = noop;
  102915. process.prependOnceListener = noop;
  102916. process.listeners = function (name) { return [] }
  102917. process.binding = function (name) {
  102918. throw new Error('process.binding is not supported');
  102919. };
  102920. process.cwd = function () { return '/' };
  102921. process.chdir = function (dir) {
  102922. throw new Error('process.chdir is not supported');
  102923. };
  102924. process.umask = function() { return 0; };
  102925. /***/ }),
  102926. /* 34 */
  102927. /***/ (function(module, exports) {
  102928. /* (ignored) */
  102929. /***/ })
  102930. /******/ ]);
  102931. });
  102932. //# sourceMappingURL=viewer.js.map